{"version":3,"sources":["webpack:///firebase-database.js","webpack:///../database/dist/cjs/src/core/util/util.js","webpack:///../database/dist/cjs/src/core/util/Path.js","webpack:///../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js","webpack:///../database/dist/cjs/src/core/snap/ChildrenNode.js","webpack:///../database/dist/cjs/src/core/snap/Node.js","webpack:///../database/dist/cjs/src/core/util/validation.js","webpack:///../database/dist/cjs/src/core/operation/Operation.js","webpack:///../database/dist/cjs/src/core/view/Change.js","webpack:///../database/dist/cjs/src/core/snap/indexes/KeyIndex.js","webpack:///../database/dist/cjs/src/core/snap/nodeFromJSON.js","webpack:///../database/dist/cjs/src/core/storage/storage.js","webpack:///../database/dist/cjs/src/realtime/Constants.js","webpack:///../database/dist/cjs/src/core/snap/indexes/Index.js","webpack:///../database/dist/cjs/src/core/snap/LeafNode.js","webpack:///../database/dist/cjs/src/core/util/SortedMap.js","webpack:///../database/dist/cjs/src/core/Repo.js","webpack:///../database/dist/cjs/src/core/view/CacheNode.js","webpack:///../database/dist/cjs/src/api/Reference.js","webpack:///../database/dist/cjs/src/api/DataSnapshot.js","webpack:///../database/dist/cjs/src/core/util/ImmutableTree.js","webpack:///../database/dist/cjs/src/core/view/filter/IndexedFilter.js","webpack:///../database/dist/cjs/src/core/stats/StatsManager.js","webpack:///../database/dist/cjs/src/core/RepoManager.js","webpack:///../database/dist/cjs/src/api/Database.js","webpack:///../database/dist/cjs/src/core/util/libs/parser.js","webpack:///../database/dist/cjs/src/core/RepoInfo.js","webpack:///../database/dist/cjs/src/api/onDisconnect.js","webpack:///../database/dist/cjs/src/api/Query.js","webpack:///../database/dist/cjs/src/core/snap/snap.js","webpack:///../database/dist/cjs/src/core/snap/indexes/ValueIndex.js","webpack:///../database/dist/cjs/src/core/snap/IndexMap.js","webpack:///../database/dist/cjs/src/core/snap/childSet.js","webpack:///../database/dist/cjs/src/core/snap/comparators.js","webpack:///../database/dist/cjs/src/core/snap/indexes/PathIndex.js","webpack:///../database/dist/cjs/src/core/util/ServerValues.js","webpack:///../database/dist/cjs/src/core/SparseSnapshotTree.js","webpack:///../database/dist/cjs/src/core/util/CountedSet.js","webpack:///../database/dist/cjs/src/core/operation/Overwrite.js","webpack:///../database/dist/cjs/src/core/SyncPoint.js","webpack:///../database/dist/cjs/src/core/view/ViewCache.js","webpack:///../database/dist/cjs/src/core/stats/StatsListener.js","webpack:///../database/dist/cjs/src/core/PersistentConnection.js","webpack:///../database/dist/cjs/src/core/util/EventEmitter.js","webpack:///../database/dist/cjs/src/realtime/Connection.js","webpack:///../database/dist/cjs/src/realtime/BrowserPollConnection.js","webpack:///../database/dist/cjs/src/realtime/WebSocketConnection.js","webpack:///../database/dist/cjs/src/core/ServerActions.js","webpack:///../database/dist/cjs/src/core/view/filter/RangedFilter.js","webpack:///./database/index.js","webpack:///../database/dist/cjs/index.js","webpack:///../database/dist/cjs/src/core/storage/DOMStorageWrapper.js","webpack:///../database/dist/cjs/src/core/storage/MemoryStorage.js","webpack:///../database/dist/cjs/src/api/TransactionResult.js","webpack:///../database/dist/cjs/src/core/util/NextPushId.js","webpack:///../database/dist/cjs/src/core/view/EventRegistration.js","webpack:///../database/dist/cjs/src/core/view/Event.js","webpack:///../database/dist/cjs/src/core/SyncTree.js","webpack:///../database/dist/cjs/src/core/operation/AckUserWrite.js","webpack:///../database/dist/cjs/src/core/operation/ListenComplete.js","webpack:///../database/dist/cjs/src/core/operation/Merge.js","webpack:///../database/dist/cjs/src/core/view/View.js","webpack:///../database/dist/cjs/src/core/view/ViewProcessor.js","webpack:///../database/dist/cjs/src/core/view/ChildChangeAccumulator.js","webpack:///../database/dist/cjs/src/core/view/CompleteChildSource.js","webpack:///../database/dist/cjs/src/core/view/EventGenerator.js","webpack:///../database/dist/cjs/src/core/WriteTree.js","webpack:///../database/dist/cjs/src/core/CompoundWrite.js","webpack:///../database/dist/cjs/src/core/SnapshotHolder.js","webpack:///../database/dist/cjs/src/core/AuthTokenProvider.js","webpack:///../database/dist/cjs/src/core/stats/StatsCollection.js","webpack:///../database/dist/cjs/src/core/stats/StatsReporter.js","webpack:///../database/dist/cjs/src/core/view/EventQueue.js","webpack:///../database/dist/cjs/src/core/util/VisibilityMonitor.js","webpack:///../database/dist/cjs/src/core/util/OnlineMonitor.js","webpack:///../database/dist/cjs/src/realtime/TransportManager.js","webpack:///../database/dist/cjs/src/realtime/polling/PacketReceiver.js","webpack:///../database/dist/cjs/src/core/ReadonlyRestClient.js","webpack:///../database/dist/cjs/src/core/view/QueryParams.js","webpack:///../database/dist/cjs/src/core/view/filter/LimitedFilter.js","webpack:///../database/dist/cjs/src/core/Repo_transaction.js","webpack:///../database/dist/cjs/src/core/util/Tree.js","webpack:///../database/dist/cjs/src/api/internal.js","webpack:///../database/dist/cjs/src/api/test_access.js"],"names":["webpackJsonpFirebase","module","exports","__webpack_require__","Object","defineProperty","value","util_1","util_2","util_3","util_4","util_5","util_6","storage_1","util_7","LUIDGenerator","id","sha1","str","utf8Bytes","stringToByteArray","Sha1","update","sha1Bytes","digest","base64","encodeByteArray","buildLogMessage_","var_args","_i","arguments","length","message","i","Array","isArray","apply","stringify","logger","firstLog_","enableLogging","logger_","persistent","assert","console","log","bind","SessionStorage","set","remove","get","logWrapper","prefix","concat","error","fatal","Error","warn","warnIfPageIsSecure","window","location","protocol","indexOf","warnAboutUnsupportedMethod","methodName","isInvalidJSONNumber","data","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","executeWhenDOMReady","fn","isNodeSdk","document","readyState","called_1","wrappedFn_1","body","setTimeout","Math","floor","addEventListener","attachEvent","MIN_NAME","MAX_NAME","nameCompare","a","b","aAsInt","tryParseInt","bAsInt","stringCompare","requireKey","key","obj","ObjectToUniqueKey","keys","k","push","sort","splitStringBySize","segsize","len","dataSegs","c","substring","each","forEach","val","bindCallback","callback","context","doubleToIEEE754String","v","s","e","f","ln","bits","abs","pow","min","LN2","round","reverse","join","hexByteString","hexByte","parseInt","substr","toString","toLowerCase","isChromeExtensionContentScript","test","href","isWindowsStoreApp","Windows","UI","errorForServerCode","code","query","reason","path","toUpperCase","INTEGER_REGEXP_","RegExp","intVal","exceptionGuard","stack","callUserCallback","beingCrawled","search","exportPropGetter","object","name","fnGet","setTimeoutNonBlocking","time","timeout","Path","pathOrString","pieceNum","this","pieces_","split","copyTo","pieceNum_","enumerable","configurable","prototype","getFront","getLength","popFront","getBack","pathString","toUrlEncodedString","encodeURIComponent","String","slice","begin","parent","pieces","child","childPathObj","childPieces","isEmpty","relativePath","outerPath","innerPath","outer","inner","comparePaths","left","right","leftKeys","rightKeys","cmp","equals","other","j","contains","ValidationPath","errorPrefix_","parts_","byteLength_","max","stringLength","checkValid_","pop","last","MAX_PATH_LENGTH_BYTES","MAX_PATH_DEPTH","toErrorString","setNodeFromJSON","nodeFromJSON","setMaxNode","MAX_NODE","__extends","extendStatics","setPrototypeOf","__proto__","d","p","hasOwnProperty","__","constructor","create","Index_1","Node_1","LeafNode_1","PriorityIndex","_super","compare","aPriority","node","getPriority","bPriority","indexCmp","compareTo","isDefinedOn","indexedValueChanged","oldNode","newNode","minPost","NamedNode","MIN","maxPost","LeafNode","makePost","indexValue","priorityNode","Index","PRIORITY_INDEX","EMPTY_NODE","SortedMap_1","snap_1","PriorityIndex_1","KeyIndex_1","IndexMap_1","comparators_1","ChildrenNode","children_","priorityNode_","indexMap_","lazyHash_","validatePriorityNode","SortedMap","NAME_COMPARATOR","IndexMap","Default","isLeafNode","updatePriority","newPriorityNode","getImmediateChild","childName","getChild","front","hasChild","updateImmediateChild","newChildNode","namedNode","newChildren","newIndexMap","newPriority","removeFromIndexes","insert","addToIndexes","updateChild","newImmediateChild","numChildren","count","exportFormat","numKeys","maxKey","allIntegerKeys","forEachChild","childNode","array","hash","toHash_1","priorityHashText","childHash","getPredecessorChildName","index","idx","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","indexDefinition","minKey","getFirstChild","getLastChildName","getLastChild","action","inorderTraversal","wrappedNode","getIterator","getIteratorFrom","startPost","iterator","Wrap","next","peek","getNext","getReverseIterator","getReverseIteratorFrom","endPost","withIndex","KEY_INDEX","hasIndex","addIndex","isIndexed","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","call","defineProperties","MAX","KeyIndex","__EMPTY_NODE","__childrenNodeConstructor","Path_1","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","MAX_LEAF_SIZE_","isValidKey","isValidPathString","isValidRootPathString","replace","isValidPriority","priority","validateFirebaseDataArg","fnName","argumentNumber","optional","undefined","validateFirebaseData","errorPrefix","path_","hasDotValue_1","hasActualChild_1","validateFirebaseMergePaths","mergePaths","curPath","prevPath","validateFirebaseMergeDataArg","validatePriority","validateEventType","eventType","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","parsedUrl","repoInfo","host","namespace","validateCredential","cred","validateBoolean","bool","validateString","string","validateObject","validateObjectContainsKey","opt_type","safeGet","OperationType","OperationSource","fromUser","fromServer","queryId","tagged","User","Server","forServerTaggedQuery","Change","type","snapshotNode","oldSnap","prevName","valueChange","snapshot","VALUE","childAddedChange","childKey","CHILD_ADDED","childRemovedChange","CHILD_REMOVED","childChangedChange","newSnapshot","oldSnapshot","CHILD_CHANGED","childMovedChange","CHILD_MOVED","assertionError","json","ChildrenNode_1","jsonLeaf","USE_HINZE","node_1","jsonObj_1","childData","children_1","childrenHavePriority_1","hinzeJsonObj_1","childSet","childSet_1","buildChildSet","NAME_ONLY_COMPARATOR","sortedChildSet","getCompare",".priority","DOMStorageWrapper_1","MemoryStorage_1","createStoragefor","domStorageName","domStorage","setItem","removeItem","DOMStorageWrapper","MemoryStorage","PersistentStorage","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN","LAST_SESSION_PARAM","WEBSOCKET","LONG_POLLING","oldWrapped","newWrapped","value_",".value","getValue","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","result","hasNext","LLRBNode","color","RED","copy","reverseTraversal","min_","n","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","ServerValues_1","nodeFromJSON_1","SparseSnapshotTree_1","SyncTree_1","SnapshotHolder_1","AuthTokenProvider_1","StatsManager_1","StatsReporter_1","StatsListener_1","EventQueue_1","PersistentConnection_1","ReadonlyRestClient_1","Database_1","Repo","repoInfo_","forceRestClient","app","_this","dataUpdateCount","statsListener_","eventQueue_","EventQueue","nextWriteId_","interceptServerDataCallback_","onDisconnect_","SparseSnapshotTree","persistentConnection_","authTokenProvider","AuthTokenProvider","stats_","StatsManager","getCollection","server_","ReadonlyRestClient","onDataUpdate_","onConnectStatus_","authOverride","options","PersistentConnection","onServerInfoUpdate_","addTokenChangeListener","token","refreshAuthToken","statsReporter_","getOrCreateReporter","StatsReporter","transactions_init_","infoData_","SnapshotHolder","infoSyncTree_","SyncTree","startListening","tag","currentHashFn","onComplete","infoEvents","getNode","applyServerOverwrite","stopListening","updateInfo_","serverSyncTree_","listen","status","events","raiseEventsForChangedPath","unlisten","secure","serverTime","offsetNode","offset","Date","getTime","generateServerValues","generateWithValues","timestamp","isMerge","taggedChildren","map","raw","applyTaggedQueryMerge","taggedSnap","applyTaggedQueryOverwrite","changedChildren","applyServerMerge","snap","affectedPath","rerunTransactions_","interceptServerData_","connectStatus","runOnDisconnectEvents_","updates","updateSnapshot","getNextWriteId_","setWithPriority","newVal","log_","serverValues","newNodeUnresolved","resolveDeferredValueSnapshot","writeId","applyUserOverwrite","queueEvents","put","errorReason","success","clearEvents","ackUserWrite","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","applyUserMerge","merge","changedPath","resolvedOnDisconnectTree","resolveDeferredValueTree","forEachTree","Empty","onDisconnectCancel","forget","onDisconnectSet","onDisconnectPut","remember","onDisconnectSetWithPriority","onDisconnectUpdate","onDisconnectMerge","addEventCallbackForQuery","eventRegistration","addEventRegistration","raiseEventsAtPath","removeEventCallbackForQuery","removeEventRegistration","interrupt","resume","stats","showDelta","StatsListener","longestName","reduce","previousValue","currentValue","stat","statsIncrementCounter","metric","incrementCounter","includeStat","__database","Database","CacheNode","node_","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","isCompleteForChild","onDisconnect_1","TransactionResult_1","NextPushId_1","Query_1","Repo_1","QueryParams_1","validation_1","SyncPoint_1","Reference","repo","QueryParams","DEFAULT","getKey","validateArgCount","getParent","parentPath","getRoot","ref","databaseProp","database","validateCallback","deferred","Deferred","wrapCallback","promise","objectToMerge","newObjectToMerge","transaction","transactionUpdate","applyLocally","catch","promiseComplete","committed","reject","resolve","TransactionResult","startTransaction","setPriority","now","nextPushId","thennablePushRef","pushRef","then","Promise","onDisconnect","OnDisconnect","Query","__referenceConstructor","SyncPoint","DataSnapshot","ref_","index_","exportVal","toJSON","exists","childPathString","childPath","childRef","hasChildren","getRef","emptyChildrenSingleton","EmptyChildren","ImmutableTree","children","fromObject","tree","childSnap","findRootMostMatchingPathAndValue","predicate","childExistingPathAndValue","findRootMostValueAndPath","subtree","childTree","toSet","newChild","setTree","newTree","fold","fold_","pathSoFar","accum","findOnPath","findOnPath_","pathToFollow","nextChild","foreachOnPath","foreachOnPath_","currentRelativePath","foreach","foreach_","foreachChild","Change_1","IndexedFilter","source","optChangeAccumulator","oldChild","trackChildChange","updateFullNode","newSnap","filtersNodes","getIndexedFilter","getIndex","StatsCollection_1","hashString","collections_","StatsCollection","creatorFunction","reporters_","parser_1","_staticInstance","RepoManager","repos_","useRestClient_","getInstance","appName","dbUrl","databaseFromApp","url","parseRepoInfo","createRepo","deleteRepo","appRepos","toURLString","Reference_1","RepoManager_1","repo_","INTERNAL","DatabaseInternals","checkDeleted_","refFromURL","apiName","parsedURL","goOffline","goOnline","ServerValue","TIMESTAMP",".sv","delete","decodePath","pathStringDecoded","piece","decodeURIComponent","RepoInfo_1","dataURL","parseURL","subdomain","domain","webSocketOnly","scheme","RepoInfo","port","colonInd","slashInd","parts","Constants_1","persistenceKey","internalHost","needsQueryParam","isCacheableHost","isDemoHost","isCustomHost","updateHost","newHost","connectionURL","params","connURL","pairs","cancel","ValueIndex_1","PathIndex_1","EventRegistration_1","queryParams_","orderByCalled_","validateQueryEndpoints_","startNode","endNode","hasStart","getIndexStartValue","hasEnd","getIndexEndValue","tooManyArgsError","wrongArgTypeError","getIndexStartName","getIndexEndName","PathIndex","VALUE_INDEX","validateLimit_","hasLimit","hasAnchoredLimit","validateNoPreviousOrderByCall_","getQueryParams","on","cancelCallbackOrContext","ret","getCancelAndContextArgs_","onValueEvent","callbacks","onChildEvent","cancelCallback","container","ValueEventRegistration","ChildEventRegistration","off","validateContextObject","valueCallback","once","userCallback","cancelOrContext","firstCall","onceCallback","err","limitToFirst","limit","limitToLast","orderByChild","parsedPath","newParams","orderBy","orderByKey","orderByPriority","orderByValue","startAt","endAt","equalTo","queryObject","getQueryObject","queryIdentifier","isEqual","sameRepo","samePath","sameQueryIdentifier","ValueIndex","valueNode","_defaultIndexMap","fallbackObject","indexes_","indexSet_","indexKey","sortedMap","existingChildren","childList","sawIndexedValue","iter","newIndex","indexName","newIndexSet","clone","newIndexes","indexedChildren","existingSnap","SortedMap_2","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","keyFn","mapSortFn","buildBalancedTree","low","high","middle","base12","root","buildPennant","chunkSize","attachPennant","pennant","isOne","indexPath_","extractChild","aChild","bChild","values","resolveDeferredValue","resolvedTree","rawPri","leafNode","childrenNode","CountedSet_1","find","CountedSet","add","self_1","prefixPath","func","item","clear","getCount","Operation_1","Overwrite","OVERWRITE","operationForChild","CacheNode_1","ViewCache_1","View_1","views_","applyOperation","operation","writesCache","optCompleteServerCache","view","events_1","serverCache","serverCacheComplete","eventCache","calcCompleteEventCache","eventCacheComplete","calcCompleteEventChildren","viewCache","ViewCache","View","getInitialEvents","cancelError","removed","cancelEvents","hadCompleteView","hasCompleteView","viewQueryId","getQuery","loadsAllData","getQueryViews","filter","getCompleteServerCache","viewForQuery","getCompleteView","viewExistsForQuery","findValue","eventCache_","serverCache_","updateEventSnap","eventSnap","complete","filtered","updateServerSnap","serverSnap","getEventCache","getCompleteEventSnap","getServerCache","getCompleteServerSnap","collection_","last_","newStats","delta","app_1","VisibilityMonitor_1","OnlineMonitor_1","Connection_1","ServerActions_1","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","authTokenProvider_","authOverride_","nextPersistentConnectionId_","interruptReasons_","listens_","outstandingPuts_","outstandingPutCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","lastSessionId","establishConnectionTimer_","visible_","requestCBHash_","requestNumber_","realtime_","authToken_","forceTokenRefresh_","invalidAuthTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","scheduleConnect_","VisibilityMonitor","onVisible_","OnlineMonitor","onOnline_","sendRequest","onResponse","curReqNum","msg","r","isDefault","listenSpec","hashFn","sendListen_","req","payload","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","credential","isAdmin","token_1","authMethod","isValidFormat","requestData","res","onAuthRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","request","response","putInternal","sendPut_","queued","reportStats","onDataMessage_","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","onReady_","sessionId","handleTimestamp_","sendConnectStats_","restoreState_","clearTimeout","establishConnection_","visible","online","close","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","random","onDataMessage_1","onReady_1","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","sendRequestFn","forceRefresh","getToken","accessToken","Connection","CONSTANTS","NODE_ADMIN","serverTimeOffset","q","normalizedPathString","statusCode","explanation","notifyForInvalidToken","queries","shift","clientName","NODE_CLIENT","default","SDK_VERSION","isMobileCordova","isReactNative","currentlyOnline","ServerActions","EventEmitter","allowedEvents_","listeners_","trigger","listeners","validateEventType_","eventData","getInitialEvent","splice","et","TransportManager_1","onMessage_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","TransportManager","start_","conn","initialTransport","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","open","healthyTimeout_ms","healthyTimeout_","bytesReceived","markConnectionHealthy","bytesSent","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","t","sendData_","tryCleanupConnection","connId","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","send","start","onControl_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","ts","version","h","onConnectionEstablished_","tryStartUpgrade_","upgradeTransport","startUpgrade_","onMessage","closeConnections_","PacketReceiver_1","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_PARAM","FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM","BrowserPollConnection","transportSessionId","everConnected_","urlFn","curSegmentNum","myPacketOrderer","PacketReceiver","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","FirebaseIFrameScriptHolder","args","command","arg1","arg2","incrementIncomingBytes_","password","sendNewPolls","closeAfter","pN","handleResponse","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","createElement","shutdown_","myDisconnFrame","removeChild","dataStr","base64data","base64Encode","MAX_URL_DATA_SIZE","enqueueSegment","pw","src","style","display","appendChild","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","script","iframeContents","doc","write","iframe","contentWindow","contentDocument","alive","innerHTML","myID","myPW","theURL","nodeRestRequest","newRequest_","curDataString","theSeg","seg","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript_1","async","onload","onreadystatechange","rstate","parentNode","onerror","process","setWebSocketImpl","impl","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","keepaliveTimer","frames","totalFrames","connectionURL_","device","headers","User-Agent","platform","env","proxy","origin","mySock","onopen","onclose","onmessage","m","handleIncomingFrame","isOldAndroid","navigator","userAgent","oldAndroidRegex","oldAndroidMatch","match","parseFloat","previouslyFailed","isInMemoryStorage","appendFrame_","fullMess","jsonMess","jsonEval","handleNewFrameCount_","frameCount","extractFrameCount_","isNaN","mess","resetKeepAlive","remainingData","sendString_","clearInterval","setInterval","responsesRequiredToBeHealthy","healthyTimeout","IndexedFilter_1","RangedFilter","indexedFilter_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","matches","self","startName","endName","registerDatabase","instance","registerService","unused","TEST_ACCESS","DataSnapshot_1","domStorage_","prefix_","prefixedName_","storedVal","getItem","cache_","PUSH_CHARS","lastPushTime","lastRandChars","duplicateTime","timeStampChars","charAt","Event_1","callback_","cancelCallback_","context_","respondsTo","createEvent","change","DataEvent","getEventRunner","ctx","getEventType","cancelCB_1","cb_1","createCancelEvent","CancelEvent","hasAnyCallback","callbacks_","eventToCheck","cancelCB_2","cb_2","otherCount","otherKey","getAnyKey","thisKey","every","cb","getPath","AckUserWrite_1","ImmutableTree_1","ListenComplete_1","Merge_1","Overwrite_1","WriteTree_1","listenProvider_","syncPointTree_","pendingWriteTree_","WriteTree","tagToQueryMap_","queryToTagMap_","newData","addOverwrite","applyOperationToSyncPoints_","addMerge","changeTree","Merge","revert","getWrite","removeWrite","affectedTree_1","AckUserWrite","applyListenComplete","ListenComplete","queryKey","queryKeyForTag_","parseQueryKey_","queryPath","op","applyTaggedOperation_","applyTaggedListenComplete","foundAncestorDefaultView","pathToSyncPoint","sp","syncPoint","childSyncPoint","completeCache","viewAlreadyExists","makeQueryKey_","getNextQueryTag_","childWrites","setupListener_","maybeSyncPoint","removedAndEvents","removingDefault","findIndex","covered","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","listener","createListenerForView_","queryForListening_","tagForQuery_","queryToRemove","tagToRemove","removeTags_","writeIdsToExclude","writeTree","maybeChildSyncPoint","childMap","views_1","childViews","removedQuery","removedQueryKey","removedQueryTag","queriesToStop","queries_1","childQueries","queryToStop","splitIndex","nextQueryTag_","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","affectedTree","ACK_USER_WRITE","LISTEN_COMPLETE","MERGE","ViewProcessor_1","EventGenerator_1","query_","initialViewCache","eventRegistrations_","indexFilter","getNodeFilter","processor_","ViewProcessor","initialServerCache","initialEventCache","newServerCache","newEventCache","viewCache_","eventGenerator_","EventGenerator","cache","path_1","registration","maybeEvent","remaining","existing","completeServerCache","oldViewCache","assertIndexed","generateEventsForChanges_","changes","initialChanges","registrations","generateEventsForChanges","ChildChangeAccumulator_1","CompleteChildSource_1","ProcessorResult","filter_","newViewCache","filterServerNode","accumulator","ChildChangeAccumulator","overwrite","applyUserOverwrite_","applyServerOverwrite_","applyUserMerge_","applyServerMerge_","revertUserWrite_","ackUserWrite_","listenComplete_","getChanges","maybeAddValueEvent_","isLeafOrEmpty","oldCompleteSnap","generateEventCacheAfterServerEvent_","changePath","oldEventSnap","shadowingWrite","serverNode","completeChildren","completeEventChildren","completeNode","oldEventNode","updatedPriority","calcEventCacheAfterServerOverwrite","childChangePath","newEventChild","eventChildUpdate","calcCompleteChild","changedSnap","oldServerSnap","serverFilter","newServerNode","NO_COMPLETE_CHILD_SOURCE","WriteTreeCompleteChildSource","getCompleteChild","newEventSnap","cacheHasChild_","curViewCache","writePath","applyMerge_","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","oldEventCache","serverChildren","changeMap_","oldChange","oldType","getValues","NoCompleteChildSource_","getChildAfterChild","writes_","optCompleteServerCache_","completeServerData","nodes","calcIndexedSlice","eventRegistrations","moves","generateEventsForType_","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","aWrapped","bWrapped","CompoundWrite_1","visibleWrites_","CompoundWrite","allWrites_","lastWriteId_","WriteTreeRef","addWrite","addWrites","record","writeToRemove","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","getCompleteWriteData","getCompleteNode","treePath","includeHiddenWrites","childCompoundWrite","hasCompleteWrite","mergeAtPath","layerTree_","layeredCache","shadowingNode","subMerge","completeServerChildren","topLevelSet","merge_1","getCompleteChildren","existingEventSnap","existingServerSnap","childMerge","toIterate","writeRecord","findKey","DefaultFilter_","writes","treeRoot","compoundWrite","deepNode","treePath_","writeTree_","existingServerCache","rootmost","rootMostPath","newWrite","applySubtreeWrite_","priorityWrite_1","rootNode_","newSnapshotNode","app_","removeTokenChangeListener","errorMessage","counters_","amount","deepCopy","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","collection","statsToReport_","reportStats_","reportedStats","haveStatsToReport","eventLists_","recursionDepth_","eventDataList","currList","eventPath","EventList","raiseQueuedEventsMatchingPredicate_","sentAll","eventList","raise","events_","eventFn","EventEmitter_1","hidden","visibilityChange","online_","BrowserPollConnection_1","WebSocketConnection_1","initTransports_","isWebSocketsAvailable","isSkipPollConnection","transports_","transports_1","ALL_TRANSPORTS","transport","pendingResponses","currentResponseNum","closeAfterResponse","onClose","responseNum","requestNum","this_1","toProcess","getListenId_","listenId","thisListen","queryStringParamaters","toRestQueryStringParameters","restRequest_","status_1","queryStringParameters","authTokenData","authToken","querystring","xhr","XMLHttpRequest","responseText","LimitedFilter_1","RangedFilter_1","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","limit_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","isViewFromLeft","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","getLimit","copy_","newLimit","VIEW_FROM_RIGHT","WIRE_PROTOCOL_CONSTANTS","INDEX_START_VALUE","INDEX_START_NAME","INDEX_END_VALUE","INDEX_END_NAME","LIMIT","viewFrom","VIEW_FROM","INDEX","LimitedFilter","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","rangedFilter_","reverse_","fullLimitUpdateChild_","inRange","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","newChildNamedNode","windowBoundary","oldChildSnap","compareNext","TransactionStatus","Tree_1","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","Tree","watchRef","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","subTree","nodeQueue","setValue","priorityForNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","queue","buildTransactionQueue_","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","txnsToRerun","abortTransaction","currentNode","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","from","forEachAncestor","abortTransactionsOnNode_","forEachDescendant","lastSent","TreeNode","childCount","name_","parent_","pathObj","updateParents_","includeSelf","childrenFirst","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","forceLongPolling","forceWebSockets","setSecurityDebugCallback","interceptServerData","DataConnection","simpleListen","echo","onEcho","RealTimeConnection","hijackHash","newHash","oldPut","opt_onComplete","opt_hash","ConnectionTarget","listens","firebaseRef"],"mappings":";;;;;AAKA,IACQA,sBAAsB,IACvB,CAED,SAAUC,EAAQC,EAASC,GAEjC,YCKAC,QAAAC,eAAAH,EAAA,cAA8CI,OAAA,GAC9C,IAAAC,GAAAJ,EAAA,GACAK,EAAAL,EAAA,GACAM,EAAAN,EAAA,GACAO,EAAAP,EAAA,GACAQ,EAAAR,EAAA,GACAS,EAAAT,EAAA,GACAU,EAAAV,EAAA,IACAW,EAAAX,EAAA,EAKAD,GAAAa,cAAA,WACA,GAAAC,GAAA,CACA,mBACA,MAAAA,SAQAd,EAAAe,KAAA,SAAAC,GACA,GAAAC,GAAAR,EAAAS,kBAAAF,GACAD,EAAA,GAAAP,GAAAW,IACAJ,GAAAK,OAAAH,EACA,IAAAI,GAAAN,EAAAO,QACA,OAAAf,GAAAgB,OAAAC,gBAAAH,GAOA,IAAAI,GAAA,WAEA,OADAC,MACAC,EAAA,EAAoBA,EAAAC,UAAAC,OAAuBF,IAC3CD,EAAAC,GAAAC,UAAAD,EAGA,QADAG,GAAA,GACAC,EAAA,EAAmBA,EAAAL,EAAAG,OAAqBE,IACxCC,MAAAC,QAAAP,EAAAK,KACAL,EAAAK,IACA,gBAAAL,GAAAK,IACA,gBAAAL,GAAAK,GAAAF,OACAC,GAAAL,EAAAS,MAAA,KAAAR,EAAAK,IAEA,gBAAAL,GAAAK,GACAD,GAAApB,EAAAyB,UAAAT,EAAAK,IAG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aAAA,SAAAxoD,EAAAiY,GACA7Y,KAAAo3B,YAAA,KAA2BxzB,EAAAhD,GAAgBiY,IAM3C5C,EAAA4B,qBAAAtX,UAAA8oD,KAAA,SAAArvD,EAAAsvD,GACAtpD,KAAAo3B,YAAA,QAA8BzzB,EAAA3J,GAAUsvD,IAGxCtzD,EAAAuzD,mBAAAp0B,EAAAsG,WAKAzlC,EAAAwzD,WAAA,SAAAC,GACA,GAAAC,GAAAzzC,EAAA4B,qBAAAtX,UAAAsb,GAOA,OANA5F,GAAA4B,qBAAAtX,UAAAsb,IAAA,SAAAjb,EAAA5G,EAAA2vD,EAAAC,OACAv9C,KAAAu9C,IACAA,EAAAH,KAEAC,EAAAz+C,KAAAjL,KAAAY,EAAA5G,EAAA2vD,EAAAC,IAEA,WACA3zC,EAAA4B,qBAAAtX,UAAAsb,IAAA6tC,IAMA1zD,EAAA6zD,iBAAAzhC,EAAAO,SAKA3yB,EAAAw3B,gBAAA,SAAA9uB,GACA,MAAAA,GAAA8uB,mBAMAx3B,EAAA8zD,QAAA,SAAAC,GACA,MAAAA,GAAAhqC,KAAA9I,EAAA0e,IAOA3/B,EAAAsgB,gBAAA,SAAAA,GACA4Q,EAAAd,YAAAG,cAAAjQ,uBnF02gBG,KACO,MAAMld,GACN,KAAUE,OACR","file":"firebase-database.js","sourcesContent":["/*!\n * @license Firebase v4.8.0\n * Build: rev-c6c0976\n * Terms: https://firebase.google.com/terms/\n */\ntry {\n webpackJsonpFirebase([0],[\n/* 0 */,\n/* 1 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar util_6 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(13);\nvar util_7 = __webpack_require__(0);\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n if (typeof console !== 'undefined') {\n if (typeof console.log === 'function') {\n exports.logger = console.log.bind(console);\n }\n else if (typeof console.log === 'object') {\n // IE does this.\n exports.logger = function (message) {\n console.log(message);\n };\n }\n }\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.error !== 'undefined') {\n console.error(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = buildLogMessage_.apply(void 0, var_args);\n throw new Error('FIREBASE FATAL ERROR: ' + message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.warn !== 'undefined') {\n console.warn(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n/***/ }),\n/* 2 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n/***/ }),\n/* 3 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = __webpack_require__(15);\nvar util_1 = __webpack_require__(1);\nvar Node_1 = __webpack_require__(5);\nvar LeafNode_1 = __webpack_require__(16);\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n __extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n/***/ }),\n/* 4 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar SortedMap_1 = __webpack_require__(17);\nvar Node_1 = __webpack_require__(5);\nvar snap_1 = __webpack_require__(37);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar KeyIndex_1 = __webpack_require__(10);\nvar IndexMap_1 = __webpack_require__(39);\nvar LeafNode_1 = __webpack_require__(16);\nvar comparators_1 = __webpack_require__(41);\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n __extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n/***/ }),\n/* 5 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n/***/ }),\n/* 6 */,\n/* 7 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n !exports.isValidKey(parsedUrl.repoInfo.namespace) ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n/***/ }),\n/* 8 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n/***/ }),\n/* 9 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n/***/ }),\n/* 10 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = __webpack_require__(15);\nvar Node_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n __extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n/***/ }),\n/* 11 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(4);\nvar LeafNode_1 = __webpack_require__(16);\nvar Node_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar childSet_1 = __webpack_require__(40);\nvar comparators_1 = __webpack_require__(41);\nvar IndexMap_1 = __webpack_require__(39);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n/***/ }),\n/* 12 */,\n/* 13 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = __webpack_require__(80);\nvar MemoryStorage_1 = __webpack_require__(81);\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n/***/ }),\n/* 14 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n/***/ }),\n/* 15 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(1);\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n/***/ }),\n/* 16 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar snap_1 = __webpack_require__(37);\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n/***/ }),\n/* 17 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\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);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n/***/ }),\n/* 18 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = __webpack_require__(43);\nvar nodeFromJSON_1 = __webpack_require__(11);\nvar Path_1 = __webpack_require__(2);\nvar SparseSnapshotTree_1 = __webpack_require__(44);\nvar SyncTree_1 = __webpack_require__(86);\nvar SnapshotHolder_1 = __webpack_require__(97);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar AuthTokenProvider_1 = __webpack_require__(98);\nvar StatsManager_1 = __webpack_require__(25);\nvar StatsReporter_1 = __webpack_require__(100);\nvar StatsListener_1 = __webpack_require__(49);\nvar EventQueue_1 = __webpack_require__(101);\nvar PersistentConnection_1 = __webpack_require__(50);\nvar ReadonlyRestClient_1 = __webpack_require__(106);\nvar Database_1 = __webpack_require__(32);\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n/***/ }),\n/* 19 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n/***/ }),\n/* 20 */,\n/* 21 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar onDisconnect_1 = __webpack_require__(35);\nvar TransactionResult_1 = __webpack_require__(82);\nvar util_1 = __webpack_require__(1);\nvar NextPushId_1 = __webpack_require__(83);\nvar Query_1 = __webpack_require__(36);\nvar Repo_1 = __webpack_require__(18);\nvar Path_1 = __webpack_require__(2);\nvar QueryParams_1 = __webpack_require__(107);\nvar validation_1 = __webpack_require__(7);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar SyncPoint_1 = __webpack_require__(47);\nvar Reference = /** @class */ (function (_super) {\n __extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n/***/ }),\n/* 22 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(7);\nvar Path_1 = __webpack_require__(2);\nvar PriorityIndex_1 = __webpack_require__(3);\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n/***/ }),\n/* 23 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = __webpack_require__(17);\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(1);\nvar util_2 = __webpack_require__(0);\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n/***/ }),\n/* 24 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(9);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar PriorityIndex_1 = __webpack_require__(3);\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n/***/ }),\n/* 25 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = __webpack_require__(99);\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n/***/ }),\n/* 26 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Repo_1 = __webpack_require__(18);\nvar util_2 = __webpack_require__(1);\nvar parser_1 = __webpack_require__(33);\nvar validation_1 = __webpack_require__(7);\n__webpack_require__(109);\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.intializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n/***/ }),\n/* 27 */,\n/* 28 */,\n/* 29 */,\n/* 30 */,\n/* 31 */,\n/* 32 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar parser_1 = __webpack_require__(33);\nvar Path_1 = __webpack_require__(2);\nvar Reference_1 = __webpack_require__(21);\nvar Repo_1 = __webpack_require__(18);\nvar RepoManager_1 = __webpack_require__(26);\nvar util_2 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(7);\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a reference to the root or the path specified in opt_pathString.\n * @param {string=} pathString\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.ref = function (pathString) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n return pathString !== undefined ? this.root_.child(pathString) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return Promise.resolve();\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n/***/ }),\n/* 33 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(2);\nvar RepoInfo_1 = __webpack_require__(34);\nvar util_1 = __webpack_require__(1);\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if (!namespace || namespace == 'undefined') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host and path.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n host = dataURL.substring(0, slashInd);\n pathString = decodePath(dataURL.substring(slashInd));\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n/***/ }),\n/* 34 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(13);\nvar Constants_1 = __webpack_require__(14);\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost;\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n/***/ }),\n/* 35 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar validation_1 = __webpack_require__(7);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n/***/ }),\n/* 36 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar KeyIndex_1 = __webpack_require__(10);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar ValueIndex_1 = __webpack_require__(38);\nvar PathIndex_1 = __webpack_require__(42);\nvar util_2 = __webpack_require__(1);\nvar Path_1 = __webpack_require__(2);\nvar validation_1 = __webpack_require__(7);\nvar util_3 = __webpack_require__(0);\nvar EventRegistration_1 = __webpack_require__(84);\nvar util_4 = __webpack_require__(0);\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n/***/ }),\n/* 37 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n/***/ }),\n/* 38 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = __webpack_require__(15);\nvar Node_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(1);\nvar nodeFromJSON_1 = __webpack_require__(11);\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n __extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n/***/ }),\n/* 39 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar childSet_1 = __webpack_require__(40);\nvar util_2 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(5);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar KeyIndex_1 = __webpack_require__(10);\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n/***/ }),\n/* 40 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = __webpack_require__(17);\nvar SortedMap_2 = __webpack_require__(17);\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n/***/ }),\n/* 41 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n/***/ }),\n/* 42 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar Index_1 = __webpack_require__(15);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar Node_1 = __webpack_require__(5);\nvar nodeFromJSON_1 = __webpack_require__(11);\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n __extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n/***/ }),\n/* 43 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar SparseSnapshotTree_1 = __webpack_require__(44);\nvar LeafNode_1 = __webpack_require__(16);\nvar nodeFromJSON_1 = __webpack_require__(11);\nvar PriorityIndex_1 = __webpack_require__(3);\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n/***/ }),\n/* 44 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(2);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar CountedSet_1 = __webpack_require__(45);\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n/***/ }),\n/* 45 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n/***/ }),\n/* 46 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(8);\nvar Path_1 = __webpack_require__(2);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n/***/ }),\n/* 47 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(19);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar ViewCache_1 = __webpack_require__(48);\nvar View_1 = __webpack_require__(90);\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n/***/ }),\n/* 48 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(4);\nvar CacheNode_1 = __webpack_require__(19);\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n/***/ }),\n/* 49 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n/***/ }),\n/* 50 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(1);\nvar Path_1 = __webpack_require__(2);\nvar VisibilityMonitor_1 = __webpack_require__(102);\nvar OnlineMonitor_1 = __webpack_require__(103);\nvar util_5 = __webpack_require__(0);\nvar Connection_1 = __webpack_require__(52);\nvar util_6 = __webpack_require__(0);\nvar util_7 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(55);\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n __extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body && typeof console !== 'undefined') {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n/***/ }),\n/* 51 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n/***/ }),\n/* 52 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar storage_1 = __webpack_require__(13);\nvar Constants_1 = __webpack_require__(14);\nvar TransportManager_1 = __webpack_require__(104);\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\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)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\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.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n/***/ }),\n/* 53 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\nvar CountedSet_1 = __webpack_require__(45);\nvar StatsManager_1 = __webpack_require__(25);\nvar PacketReceiver_1 = __webpack_require__(105);\nvar Constants_1 = __webpack_require__(14);\nvar util_2 = __webpack_require__(0);\nvar util_3 = __webpack_require__(0);\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n/***/ }),\n/* 54 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(6);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsManager_1 = __webpack_require__(25);\nvar Constants_1 = __webpack_require__(14);\nvar util_3 = __webpack_require__(0);\nvar storage_1 = __webpack_require__(13);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(27)))\n\n/***/ }),\n/* 55 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n/***/ }),\n/* 56 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(24);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar Node_1 = __webpack_require__(5);\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n/***/ }),\n/* 57 */,\n/* 58 */,\n/* 59 */,\n/* 60 */,\n/* 61 */,\n/* 62 */,\n/* 63 */,\n/* 64 */,\n/* 65 */,\n/* 66 */,\n/* 67 */,\n/* 68 */,\n/* 69 */,\n/* 70 */,\n/* 71 */,\n/* 72 */,\n/* 73 */,\n/* 74 */,\n/* 75 */,\n/* 76 */,\n/* 77 */,\n/* 78 */\n/***/ (function(module, exports, __webpack_require__) {\n\n/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = __webpack_require__(79);\n\n\n/***/ }),\n/* 79 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = __webpack_require__(6);\nvar Database_1 = __webpack_require__(32);\nexports.Database = Database_1.Database;\nvar Query_1 = __webpack_require__(36);\nexports.Query = Query_1.Query;\nvar Reference_1 = __webpack_require__(21);\nexports.Reference = Reference_1.Reference;\nvar util_1 = __webpack_require__(1);\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = __webpack_require__(26);\nvar INTERNAL = __webpack_require__(111);\nvar TEST_ACCESS = __webpack_require__(112);\nvar util_2 = __webpack_require__(0);\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = __webpack_require__(22);\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = __webpack_require__(35);\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n/***/ }),\n/* 80 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n/***/ }),\n/* 81 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n/***/ }),\n/* 82 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n/***/ }),\n/* 83 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n/***/ }),\n/* 84 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = __webpack_require__(22);\nvar Event_1 = __webpack_require__(85);\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n/***/ }),\n/* 85 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n/***/ }),\n/* 86 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar AckUserWrite_1 = __webpack_require__(87);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar util_3 = __webpack_require__(0);\nvar ImmutableTree_1 = __webpack_require__(23);\nvar ListenComplete_1 = __webpack_require__(88);\nvar Merge_1 = __webpack_require__(89);\nvar Operation_1 = __webpack_require__(8);\nvar Overwrite_1 = __webpack_require__(46);\nvar Path_1 = __webpack_require__(2);\nvar SyncPoint_1 = __webpack_require__(47);\nvar WriteTree_1 = __webpack_require__(95);\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n/***/ }),\n/* 87 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar Operation_1 = __webpack_require__(8);\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n/***/ }),\n/* 88 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = __webpack_require__(2);\nvar Operation_1 = __webpack_require__(8);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n/***/ }),\n/* 89 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(8);\nvar Overwrite_1 = __webpack_require__(46);\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n/***/ }),\n/* 90 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = __webpack_require__(24);\nvar ViewProcessor_1 = __webpack_require__(91);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar CacheNode_1 = __webpack_require__(19);\nvar ViewCache_1 = __webpack_require__(48);\nvar EventGenerator_1 = __webpack_require__(94);\nvar util_1 = __webpack_require__(0);\nvar Operation_1 = __webpack_require__(8);\nvar Change_1 = __webpack_require__(9);\nvar PriorityIndex_1 = __webpack_require__(3);\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n/***/ }),\n/* 91 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = __webpack_require__(8);\nvar util_1 = __webpack_require__(0);\nvar ChildChangeAccumulator_1 = __webpack_require__(92);\nvar Change_1 = __webpack_require__(9);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar KeyIndex_1 = __webpack_require__(10);\nvar ImmutableTree_1 = __webpack_require__(23);\nvar Path_1 = __webpack_require__(2);\nvar CompleteChildSource_1 = __webpack_require__(93);\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n/***/ }),\n/* 92 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(9);\nvar util_2 = __webpack_require__(0);\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n/***/ }),\n/* 93 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = __webpack_require__(19);\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n/***/ }),\n/* 94 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = __webpack_require__(5);\nvar Change_1 = __webpack_require__(9);\nvar util_1 = __webpack_require__(0);\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n/***/ }),\n/* 95 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar CompoundWrite_1 = __webpack_require__(96);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n/***/ }),\n/* 96 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = __webpack_require__(23);\nvar Path_1 = __webpack_require__(2);\nvar util_1 = __webpack_require__(0);\nvar Node_1 = __webpack_require__(5);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(0);\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n/***/ }),\n/* 97 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = __webpack_require__(4);\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n/***/ }),\n/* 98 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n/***/ }),\n/* 99 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(0);\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n/***/ }),\n/* 100 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar StatsListener_1 = __webpack_require__(49);\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n/***/ }),\n/* 101 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n/***/ }),\n/* 102 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar EventEmitter_1 = __webpack_require__(51);\nvar util_1 = __webpack_require__(0);\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n __extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n/***/ }),\n/* 103 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar EventEmitter_1 = __webpack_require__(51);\nvar util_2 = __webpack_require__(0);\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n __extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n/***/ }),\n/* 104 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = __webpack_require__(53);\nvar WebSocketConnection_1 = __webpack_require__(54);\nvar util_1 = __webpack_require__(1);\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n/***/ }),\n/* 105 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(1);\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n/***/ }),\n/* 106 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar util_3 = __webpack_require__(0);\nvar util_4 = __webpack_require__(0);\nvar util_5 = __webpack_require__(0);\nvar ServerActions_1 = __webpack_require__(55);\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n __extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n/***/ }),\n/* 107 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar util_2 = __webpack_require__(1);\nvar KeyIndex_1 = __webpack_require__(10);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar ValueIndex_1 = __webpack_require__(38);\nvar PathIndex_1 = __webpack_require__(42);\nvar IndexedFilter_1 = __webpack_require__(24);\nvar LimitedFilter_1 = __webpack_require__(108);\nvar RangedFilter_1 = __webpack_require__(56);\nvar util_3 = __webpack_require__(0);\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n/***/ }),\n/* 108 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = __webpack_require__(56);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar Node_1 = __webpack_require__(5);\nvar util_1 = __webpack_require__(0);\nvar Change_1 = __webpack_require__(9);\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n/***/ }),\n/* 109 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Reference_1 = __webpack_require__(21);\nvar DataSnapshot_1 = __webpack_require__(22);\nvar Path_1 = __webpack_require__(2);\nvar Tree_1 = __webpack_require__(110);\nvar PriorityIndex_1 = __webpack_require__(3);\nvar util_2 = __webpack_require__(1);\nvar ServerValues_1 = __webpack_require__(43);\nvar validation_1 = __webpack_require__(7);\nvar util_3 = __webpack_require__(0);\nvar nodeFromJSON_1 = __webpack_require__(11);\nvar ChildrenNode_1 = __webpack_require__(4);\nvar Repo_1 = __webpack_require__(18);\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n/***/ }),\n/* 110 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = __webpack_require__(0);\nvar Path_1 = __webpack_require__(2);\nvar util_2 = __webpack_require__(0);\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n/***/ }),\n/* 111 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = __webpack_require__(54);\nvar BrowserPollConnection_1 = __webpack_require__(53);\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n/***/ }),\n/* 112 */\n/***/ (function(module, exports, __webpack_require__) {\n\n\"use strict\";\n\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = __webpack_require__(34);\nvar PersistentConnection_1 = __webpack_require__(50);\nvar RepoManager_1 = __webpack_require__(26);\nvar Connection_1 = __webpack_require__(52);\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n/***/ })\n],[78]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-database.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-database.js","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar util_6 = require(\"@firebase/util\");\nvar storage_1 = require(\"../storage/storage\");\nvar util_7 = require(\"@firebase/util\");\n/**\n * Returns a locally-unique ID (generated by just incrementing up from 0 each time its called).\n * @type {function(): number} Generated ID.\n */\nexports.LUIDGenerator = (function () {\n var id = 1;\n return function () {\n return id++;\n };\n})();\n/**\n * Sha1 hash of the input string\n * @param {!string} str The string to hash\n * @return {!string} The resulting hash\n */\nexports.sha1 = function (str) {\n var utf8Bytes = util_5.stringToByteArray(str);\n var sha1 = new util_4.Sha1();\n sha1.update(utf8Bytes);\n var sha1Bytes = sha1.digest();\n return util_3.base64.encodeByteArray(sha1Bytes);\n};\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nvar buildLogMessage_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = '';\n for (var i = 0; i < var_args.length; i++) {\n if (Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')) {\n message += buildLogMessage_.apply(null, var_args[i]);\n }\n else if (typeof var_args[i] === 'object') {\n message += util_6.stringify(var_args[i]);\n }\n else {\n message += var_args[i];\n }\n message += ' ';\n }\n return message;\n};\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexports.logger = null;\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nvar firstLog_ = true;\n/**\n * The implementation of Firebase.enableLogging (defined here to break dependencies)\n * @param {boolean|?function(string)} logger_ A flag to turn on logging, or a custom logger\n * @param {boolean=} persistent Whether or not to persist logging settings across refreshes\n */\nexports.enableLogging = function (logger_, persistent) {\n util_1.assert(!persistent || (logger_ === true || logger_ === false), \"Can't turn on custom loggers persistently.\");\n if (logger_ === true) {\n if (typeof console !== 'undefined') {\n if (typeof console.log === 'function') {\n exports.logger = console.log.bind(console);\n }\n else if (typeof console.log === 'object') {\n // IE does this.\n exports.logger = function (message) {\n console.log(message);\n };\n }\n }\n if (persistent)\n storage_1.SessionStorage.set('logging_enabled', true);\n }\n else if (typeof logger_ === 'function') {\n exports.logger = logger_;\n }\n else {\n exports.logger = null;\n storage_1.SessionStorage.remove('logging_enabled');\n }\n};\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexports.log = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (firstLog_ === true) {\n firstLog_ = false;\n if (exports.logger === null && storage_1.SessionStorage.get('logging_enabled') === true)\n exports.enableLogging(true);\n }\n if (exports.logger) {\n var message = buildLogMessage_.apply(null, var_args);\n exports.logger(message);\n }\n};\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexports.logWrapper = function (prefix) {\n return function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n exports.log.apply(void 0, [prefix].concat(var_args));\n };\n};\n/**\n * @param {...string} var_args\n */\nexports.error = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.error !== 'undefined') {\n console.error(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * @param {...string} var_args\n */\nexports.fatal = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var message = buildLogMessage_.apply(void 0, var_args);\n throw new Error('FIREBASE FATAL ERROR: ' + message);\n};\n/**\n * @param {...*} var_args\n */\nexports.warn = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (typeof console !== 'undefined') {\n var message = 'FIREBASE WARNING: ' + buildLogMessage_.apply(void 0, var_args);\n if (typeof console.warn !== 'undefined') {\n console.warn(message);\n }\n else {\n console.log(message);\n }\n }\n};\n/**\n * Logs a warning if the containing page uses https. Called when a call to new Firebase\n * does not use https.\n */\nexports.warnIfPageIsSecure = function () {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1) {\n exports.warn('Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().');\n }\n};\n/**\n * @param {!String} methodName\n */\nexports.warnAboutUnsupportedMethod = function (methodName) {\n exports.warn(methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.');\n};\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexports.isInvalidJSONNumber = function (data) {\n return (typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY));\n};\n/**\n * @param {function()} fn\n */\nexports.executeWhenDOMReady = function (fn) {\n if (util_7.isNodeSdk() || document.readyState === 'complete') {\n fn();\n }\n else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n var called_1 = false;\n var wrappedFn_1 = function () {\n if (!document.body) {\n setTimeout(wrappedFn_1, Math.floor(10));\n return;\n }\n if (!called_1) {\n called_1 = true;\n fn();\n }\n };\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn_1, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn_1, false);\n }\n else if (document.attachEvent) {\n // IE.\n document.attachEvent('onreadystatechange', function () {\n if (document.readyState === 'complete')\n wrappedFn_1();\n });\n // fallback to onload.\n window.attachEvent('onload', wrappedFn_1);\n // jQuery has an extra hack for IE that we could employ (based on\n // http://javascript.nwbox.com/IEContentLoaded/) But it looks really old.\n // I'm hoping we don't need it.\n }\n }\n};\n/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexports.MIN_NAME = '[MIN_NAME]';\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexports.MAX_NAME = '[MAX_NAME]';\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexports.nameCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a === exports.MIN_NAME || b === exports.MAX_NAME) {\n return -1;\n }\n else if (b === exports.MIN_NAME || a === exports.MAX_NAME) {\n return 1;\n }\n else {\n var aAsInt = exports.tryParseInt(a), bAsInt = exports.tryParseInt(b);\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n }\n else {\n return -1;\n }\n }\n else if (bAsInt !== null) {\n return 1;\n }\n else {\n return a < b ? -1 : 1;\n }\n }\n};\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexports.stringCompare = function (a, b) {\n if (a === b) {\n return 0;\n }\n else if (a < b) {\n return -1;\n }\n else {\n return 1;\n }\n};\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexports.requireKey = function (key, obj) {\n if (obj && key in obj) {\n return obj[key];\n }\n else {\n throw new Error('Missing required key (' + key + ') in object: ' + util_6.stringify(obj));\n }\n};\n/**\n * @param {*} obj\n * @return {string}\n */\nexports.ObjectToUniqueKey = function (obj) {\n if (typeof obj !== 'object' || obj === null)\n return util_6.stringify(obj);\n var keys = [];\n for (var k in obj) {\n keys.push(k);\n }\n // Export as json, but with the keys sorted.\n keys.sort();\n var key = '{';\n for (var i = 0; i < keys.length; i++) {\n if (i !== 0)\n key += ',';\n key += util_6.stringify(keys[i]);\n key += ':';\n key += exports.ObjectToUniqueKey(obj[keys[i]]);\n }\n key += '}';\n return key;\n};\n/**\n * Splits a string into a number of smaller segments of maximum size\n * @param {!string} str The string\n * @param {!number} segsize The maximum number of chars in the string.\n * @return {Array.} The string, split into appropriately-sized chunks\n */\nexports.splitStringBySize = function (str, segsize) {\n var len = str.length;\n if (len <= segsize) {\n return [str];\n }\n var dataSegs = [];\n for (var c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n }\n else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\n/**\n * Apply a function to each (key, value) pair in an object or\n * apply a function to each (index, value) pair in an array\n * @param {!(Object|Array)} obj The object or array to iterate over\n * @param {function(?, ?)} fn The function to apply\n */\nexports.each = function (obj, fn) {\n if (Array.isArray(obj)) {\n for (var i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\n }\n }\n else {\n /**\n * in the conversion of code we removed the goog.object.forEach\n * function which did a value,key callback. We standardized on\n * a single impl that does a key, value callback. So we invert\n * to not have to touch the `each` code points\n */\n util_2.forEach(obj, function (key, val) { return fn(val, key); });\n }\n};\n/**\n * Like goog.bind, but doesn't bother to create a closure if opt_context is null/undefined.\n * @param {function(*)} callback Callback function.\n * @param {?Object=} context Optional context to bind to.\n * @return {function(*)}\n */\nexports.bindCallback = function (callback, context) {\n return context ? callback.bind(context) : callback;\n};\n/**\n * Borrowed from http://hg.secondlife.com/llsd/src/tip/js/typedarray.js (MIT License)\n * I made one modification at the end and removed the NaN / Infinity\n * handling (since it seemed broken [caused an overflow] and we don't need it). See MJL comments.\n * @param {!number} v A double\n * @return {string}\n */\nexports.doubleToIEEE754String = function (v) {\n util_1.assert(!exports.isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n var ebits = 11, fbits = 52;\n var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str;\n // Compute sign, exponent, fraction\n // Skip NaN / Infinity handling --MJL.\n if (v === 0) {\n e = 0;\n f = 0;\n s = 1 / v === -Infinity ? 1 : 0;\n }\n else {\n s = v < 0;\n v = Math.abs(v);\n if (v >= Math.pow(2, 1 - bias)) {\n // Normalized\n ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);\n e = ln + bias;\n f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));\n }\n else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\n }\n // Pack sign, exponent, fraction\n bits = [];\n for (i = fbits; i; i -= 1) {\n bits.push(f % 2 ? 1 : 0);\n f = Math.floor(f / 2);\n }\n for (i = ebits; i; i -= 1) {\n bits.push(e % 2 ? 1 : 0);\n e = Math.floor(e / 2);\n }\n bits.push(s ? 1 : 0);\n bits.reverse();\n str = bits.join('');\n // Return the data as a hex string. --MJL\n var hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n var hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1)\n hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\n/**\n * Used to detect if we're in a Chrome content script (which executes in an\n * isolated environment where long-polling doesn't work).\n * @return {boolean}\n */\nexports.isChromeExtensionContentScript = function () {\n return !!(typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href));\n};\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexports.isWindowsStoreApp = function () {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexports.errorForServerCode = function (code, query) {\n var reason = 'Unknown Error';\n if (code === 'too_big') {\n reason =\n 'The data requested exceeds the maximum size ' +\n 'that can be accessed with a single request.';\n }\n else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n }\n else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n var error = new Error(code + ' at ' + query.path.toString() + ': ' + reason);\n error.code = code.toUpperCase();\n return error;\n};\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexports.INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexports.tryParseInt = function (str) {\n if (exports.INTEGER_REGEXP_.test(str)) {\n var intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\n/**\n * Helper to run some code but catch any exceptions and re-throw them later.\n * Useful for preventing user callbacks from breaking internal code.\n *\n * Re-throwing the exception from a setTimeout is a little evil, but it's very\n * convenient (we don't have to try to figure out when is a safe point to\n * re-throw it), and the behavior seems reasonable:\n *\n * * If you aren't pausing on exceptions, you get an error in the console with\n * the correct stack trace.\n * * If you're pausing on all exceptions, the debugger will pause on your\n * exception and then again when we rethrow it.\n * * If you're only pausing on uncaught exceptions, the debugger will only pause\n * on us re-throwing it.\n *\n * @param {!function()} fn The code to guard.\n */\nexports.exceptionGuard = function (fn) {\n try {\n fn();\n }\n catch (e) {\n // Re-throw exception when it's safe.\n setTimeout(function () {\n // It used to be that \"throw e\" would result in a good console error with\n // relevant context, but as of Chrome 39, you just get the firebase.js\n // file/line number where we re-throw it, which is useless. So we log\n // e.stack explicitly.\n var stack = e.stack || '';\n exports.warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\n};\n/**\n * Helper function to safely call opt_callback with the specified arguments. It:\n * 1. Turns into a no-op if opt_callback is null or undefined.\n * 2. Wraps the call inside exceptionGuard to prevent exceptions from breaking our state.\n *\n * @param {?Function=} callback Optional onComplete callback.\n * @param {...*} var_args Arbitrary args to be passed to opt_onComplete\n */\nexports.callUserCallback = function (callback) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (typeof callback === 'function') {\n exports.exceptionGuard(function () {\n callback.apply(void 0, var_args);\n });\n }\n};\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexports.beingCrawled = function () {\n var userAgent = (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\n // For now we whitelist the most popular crawlers. We should refine this to be the set of crawlers we\n // believe to support JavaScript/AJAX rendering.\n // NOTE: Google Webmaster Tools doesn't really belong, but their \"This is how a visitor to your website\n // would have seen the page\" is flaky if we don't treat it as a crawler.\n return (userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0);\n};\n/**\n * Export a property of an object using a getter function.\n *\n * @param {!Object} object\n * @param {string} name\n * @param {!function(): *} fnGet\n */\nexports.exportPropGetter = function (object, name, fnGet) {\n Object.defineProperty(object, name, { get: fnGet });\n};\n/**\n * Same as setTimeout() except on Node.JS it will /not/ prevent the process from exiting.\n *\n * It is removed with clearTimeout() as normal.\n *\n * @param {Function} fn Function to run.\n * @param {number} time Milliseconds to wait before running.\n * @return {number|Object} The setTimeout() return value.\n */\nexports.setTimeoutNonBlocking = function (fn, time) {\n var timeout = setTimeout(fn, time);\n if (typeof timeout === 'object' && timeout['unref']) {\n timeout['unref']();\n }\n return timeout;\n};\n\n//# sourceMappingURL=util.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/util.js\n// module id = 1\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\nvar Path = /** @class */ (function () {\n /**\n * @param {string|Array.} pathOrString Path string to parse,\n * or another path, or the raw tokens array\n * @param {number=} pieceNum\n */\n function Path(pathOrString, pieceNum) {\n if (pieceNum === void 0) {\n this.pieces_ = pathOrString.split('/');\n // Remove empty pieces.\n var copyTo = 0;\n for (var i = 0; i < this.pieces_.length; i++) {\n if (this.pieces_[i].length > 0) {\n this.pieces_[copyTo] = this.pieces_[i];\n copyTo++;\n }\n }\n this.pieces_.length = copyTo;\n this.pieceNum_ = 0;\n }\n else {\n this.pieces_ = pathOrString;\n this.pieceNum_ = pieceNum;\n }\n }\n Object.defineProperty(Path, \"Empty\", {\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n get: function () {\n return new Path('');\n },\n enumerable: true,\n configurable: true\n });\n Path.prototype.getFront = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n return this.pieces_[this.pieceNum_];\n };\n /**\n * @return {number} The number of segments in this path\n */\n Path.prototype.getLength = function () {\n return this.pieces_.length - this.pieceNum_;\n };\n /**\n * @return {!Path}\n */\n Path.prototype.popFront = function () {\n var pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n };\n /**\n * @return {?string}\n */\n Path.prototype.getBack = function () {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n return null;\n };\n Path.prototype.toString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + this.pieces_[i];\n }\n return pathString || '/';\n };\n Path.prototype.toUrlEncodedString = function () {\n var pathString = '';\n for (var i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n return pathString || '/';\n };\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n Path.prototype.slice = function (begin) {\n if (begin === void 0) { begin = 0; }\n return this.pieces_.slice(this.pieceNum_ + begin);\n };\n /**\n * @return {?Path}\n */\n Path.prototype.parent = function () {\n if (this.pieceNum_ >= this.pieces_.length)\n return null;\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n return new Path(pieces, 0);\n };\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n Path.prototype.child = function (childPathObj) {\n var pieces = [];\n for (var i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n if (childPathObj instanceof Path) {\n for (var i = childPathObj.pieceNum_; i < childPathObj.pieces_.length; i++) {\n pieces.push(childPathObj.pieces_[i]);\n }\n }\n else {\n var childPieces = childPathObj.split('/');\n for (var i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0)\n pieces.push(childPieces[i]);\n }\n }\n return new Path(pieces, 0);\n };\n /**\n * @return {boolean} True if there are no segments in this path\n */\n Path.prototype.isEmpty = function () {\n return this.pieceNum_ >= this.pieces_.length;\n };\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n Path.relativePath = function (outerPath, innerPath) {\n var outer = outerPath.getFront(), inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n }\n else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n }\n else {\n throw new Error('INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')');\n }\n };\n /**\n * @param {!Path} left\n * @param {!Path} right\n * @return {number} -1, 0, 1 if left is less, equal, or greater than the right.\n */\n Path.comparePaths = function (left, right) {\n var leftKeys = left.slice();\n var rightKeys = right.slice();\n for (var i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n var cmp = util_1.nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0)\n return cmp;\n }\n if (leftKeys.length === rightKeys.length)\n return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n };\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n Path.prototype.equals = function (other) {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n for (var i = this.pieceNum_, j = other.pieceNum_; i <= this.pieces_.length; i++, j++) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n return true;\n };\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n Path.prototype.contains = function (other) {\n var i = this.pieceNum_;\n var j = other.pieceNum_;\n if (this.getLength() > other.getLength()) {\n return false;\n }\n while (i < this.pieces_.length) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n ++i;\n ++j;\n }\n return true;\n };\n return Path;\n}()); // end Path\nexports.Path = Path;\n/**\n * Dynamic (mutable) path used to count path lengths.\n *\n * This class is used to efficiently check paths for valid\n * length (in UTF8 bytes) and depth (used in path validation).\n *\n * Throws Error exception if path is ever invalid.\n *\n * The definition of a path always begins with '/'.\n */\nvar ValidationPath = /** @class */ (function () {\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n function ValidationPath(path, errorPrefix_) {\n this.errorPrefix_ = errorPrefix_;\n /** @type {!Array} */\n this.parts_ = path.slice();\n /** @type {number} Initialize to number of '/' chars needed in path. */\n this.byteLength_ = Math.max(1, this.parts_.length);\n for (var i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += util_2.stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n Object.defineProperty(ValidationPath, \"MAX_PATH_DEPTH\", {\n /** @const {number} Maximum key depth. */\n get: function () {\n return 32;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(ValidationPath, \"MAX_PATH_LENGTH_BYTES\", {\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n get: function () {\n return 768;\n },\n enumerable: true,\n configurable: true\n });\n /** @param {string} child */\n ValidationPath.prototype.push = function (child) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += util_2.stringLength(child);\n this.checkValid_();\n };\n ValidationPath.prototype.pop = function () {\n var last = this.parts_.pop();\n this.byteLength_ -= util_2.stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n };\n ValidationPath.prototype.checkValid_ = function () {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').');\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(this.errorPrefix_ +\n 'path specified exceeds the maximum depth that can be written (' +\n ValidationPath.MAX_PATH_DEPTH +\n ') or object contains a cycle ' +\n this.toErrorString());\n }\n };\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n ValidationPath.prototype.toErrorString = function () {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n };\n return ValidationPath;\n}());\nexports.ValidationPath = ValidationPath;\n\n//# sourceMappingURL=Path.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Path.js\n// module id = 2\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar util_1 = require(\"../../util/util\");\nvar Node_1 = require(\"../Node\");\nvar LeafNode_1 = require(\"../LeafNode\");\nvar nodeFromJSON;\nvar MAX_NODE;\nfunction setNodeFromJSON(val) {\n nodeFromJSON = val;\n}\nexports.setNodeFromJSON = setNodeFromJSON;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar PriorityIndex = /** @class */ (function (_super) {\n __extends(PriorityIndex, _super);\n function PriorityIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.compare = function (a, b) {\n var aPriority = a.node.getPriority();\n var bPriority = b.node.getPriority();\n var indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.isDefinedOn = function (node) {\n return !node.getPriority().isEmpty();\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.getPriority().equals(newNode.getPriority());\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n PriorityIndex.prototype.maxPost = function () {\n return new Node_1.NamedNode(util_1.MAX_NAME, new LeafNode_1.LeafNode('[PRIORITY-POST]', MAX_NODE));\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n PriorityIndex.prototype.makePost = function (indexValue, name) {\n var priorityNode = nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, new LeafNode_1.LeafNode('[PRIORITY-POST]', priorityNode));\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n PriorityIndex.prototype.toString = function () {\n return '.priority';\n };\n return PriorityIndex;\n}(Index_1.Index));\nexports.PriorityIndex = PriorityIndex;\nexports.PRIORITY_INDEX = new PriorityIndex();\n\n//# sourceMappingURL=PriorityIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PriorityIndex.js\n// module id = 3\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar Node_1 = require(\"./Node\");\nvar snap_1 = require(\"./snap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar comparators_1 = require(\"./comparators\");\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\nvar EMPTY_NODE;\n/**\n * ChildrenNode is a class for storing internal nodes in a DataSnapshot\n * (i.e. nodes with children). It implements Node and stores the\n * list of children in the children property, sorted by child name.\n *\n * @constructor\n * @implements {Node}\n */\nvar ChildrenNode = /** @class */ (function () {\n /**\n *\n * @param {!SortedMap.} children_ List of children\n * of this node..\n * @param {?Node} priorityNode_ The priority of this node (as a snapshot node).\n * @param {!IndexMap} indexMap_\n */\n function ChildrenNode(children_, priorityNode_, indexMap_) {\n this.children_ = children_;\n this.priorityNode_ = priorityNode_;\n this.indexMap_ = indexMap_;\n this.lazyHash_ = null;\n /**\n * Note: The only reason we allow null priority is for EMPTY_NODE, since we can't use\n * EMPTY_NODE as the priority of EMPTY_NODE. We might want to consider making EMPTY_NODE its own\n * class instead of an empty ChildrenNode.\n */\n if (this.priorityNode_) {\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n if (this.children_.isEmpty()) {\n util_1.assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), 'An empty node cannot have a priority');\n }\n }\n Object.defineProperty(ChildrenNode, \"EMPTY_NODE\", {\n get: function () {\n return (EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), null, IndexMap_1.IndexMap.Default)));\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n ChildrenNode.prototype.isLeafNode = function () {\n return false;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPriority = function () {\n return this.priorityNode_ || EMPTY_NODE;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updatePriority = function (newPriorityNode) {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n }\n else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n }\n else {\n var child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getChild = function (path) {\n var front = path.getFront();\n if (front === null)\n return this;\n return this.getImmediateChild(front).getChild(path.popFront());\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hasChild = function (childName) {\n return this.children_.get(childName) !== null;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n util_1.assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else {\n var namedNode = new Node_1.NamedNode(childName, newChildNode);\n var newChildren = void 0, newIndexMap = void 0, newPriority = void 0;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);\n }\n else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else {\n util_1.assert(path.getFront() !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n var newImmediateChild = this.getImmediateChild(front).updateChild(path.popFront(), newChildNode);\n return this.updateImmediateChild(front, newImmediateChild);\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.isEmpty = function () {\n return this.children_.isEmpty();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.numChildren = function () {\n return this.children_.count();\n };\n /** @inheritDoc */\n ChildrenNode.prototype.val = function (exportFormat) {\n if (this.isEmpty())\n return null;\n var obj = {};\n var numKeys = 0, maxKey = 0, allIntegerKeys = true;\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n obj[key] = childNode.val(exportFormat);\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n }\n else {\n allIntegerKeys = false;\n }\n });\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n var array = [];\n for (var key in obj)\n array[key] = obj[key];\n return array;\n }\n else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n };\n /** @inheritDoc */\n ChildrenNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash_1 = '';\n if (!this.getPriority().isEmpty())\n toHash_1 +=\n 'priority:' +\n snap_1.priorityHashText(this.getPriority().val()) +\n ':';\n this.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n var childHash = childNode.hash();\n if (childHash !== '')\n toHash_1 += ':' + key + ':' + childHash;\n });\n this.lazyHash_ = toHash_1 === '' ? '' : util_2.sha1(toHash_1);\n }\n return this.lazyHash_;\n };\n /** @inheritDoc */\n ChildrenNode.prototype.getPredecessorChildName = function (childName, childNode, index) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n var predecessor = idx.getPredecessorKey(new Node_1.NamedNode(childName, childNode));\n return predecessor ? predecessor.name : null;\n }\n else {\n return this.children_.getPredecessorKey(childName);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getFirstChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var minKey = idx.minKey();\n return minKey && minKey.name;\n }\n else {\n return this.children_.minKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getFirstChild = function (indexDefinition) {\n var minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new Node_1.NamedNode(minKey, this.children_.get(minKey));\n }\n else {\n return null;\n }\n };\n /**\n * Given an index, return the key name of the largest value we have, according to that index\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n ChildrenNode.prototype.getLastChildName = function (indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n var maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n }\n else {\n return this.children_.maxKey();\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n ChildrenNode.prototype.getLastChild = function (indexDefinition) {\n var maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new Node_1.NamedNode(maxKey, this.children_.get(maxKey));\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.forEachChild = function (index, action) {\n var idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function (wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n }\n else {\n return this.children_.inorderTraversal(action);\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n ChildrenNode.prototype.getIterator = function (indexDefinition) {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n };\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getIteratorFrom = function (startPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, function (key) { return key; });\n }\n else {\n var iterator = this.children_.getIteratorFrom(startPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, startPost) < 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIterator = function (indexDefinition) {\n return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);\n };\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n ChildrenNode.prototype.getReverseIteratorFrom = function (endPost, indexDefinition) {\n var idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function (key) {\n return key;\n });\n }\n else {\n var iterator = this.children_.getReverseIteratorFrom(endPost.name, Node_1.NamedNode.Wrap);\n var next = iterator.peek();\n while (next != null && indexDefinition.compare(next, endPost) > 0) {\n iterator.getNext();\n next = iterator.peek();\n }\n return iterator;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.compareTo = function (other) {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n }\n else {\n return -1;\n }\n }\n else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n }\n else if (other === exports.MAX_NODE) {\n return -1;\n }\n else {\n // Must be another node with children.\n return 0;\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.withIndex = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)) {\n return this;\n }\n else {\n var newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.isIndexed = function (index) {\n return index === KeyIndex_1.KEY_INDEX || this.indexMap_.hasIndex(index);\n };\n /**\n * @inheritDoc\n */\n ChildrenNode.prototype.equals = function (other) {\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n return false;\n }\n else {\n var otherChildrenNode = other;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n }\n else if (this.children_.count() === otherChildrenNode.children_.count()) {\n var thisIter = this.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var otherIter = otherChildrenNode.getIterator(PriorityIndex_1.PRIORITY_INDEX);\n var thisCurrent = thisIter.getNext();\n var otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n }\n else {\n return false;\n }\n }\n };\n /**\n * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used\n * instead.\n *\n * @private\n * @param {!Index} indexDefinition\n * @return {?SortedMap.}\n */\n ChildrenNode.prototype.resolveIndex_ = function (indexDefinition) {\n if (indexDefinition === KeyIndex_1.KEY_INDEX) {\n return null;\n }\n else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n };\n /**\n * @private\n * @type {RegExp}\n */\n ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n return ChildrenNode;\n}());\nexports.ChildrenNode = ChildrenNode;\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nvar MaxNode = /** @class */ (function (_super) {\n __extends(MaxNode, _super);\n function MaxNode() {\n return _super.call(this, new SortedMap_1.SortedMap(comparators_1.NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap_1.IndexMap.Default) || this;\n }\n MaxNode.prototype.compareTo = function (other) {\n if (other === this) {\n return 0;\n }\n else {\n return 1;\n }\n };\n MaxNode.prototype.equals = function (other) {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n };\n MaxNode.prototype.getPriority = function () {\n return this;\n };\n MaxNode.prototype.getImmediateChild = function (childName) {\n return ChildrenNode.EMPTY_NODE;\n };\n MaxNode.prototype.isEmpty = function () {\n return false;\n };\n return MaxNode;\n}(ChildrenNode));\nexports.MaxNode = MaxNode;\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexports.MAX_NODE = new MaxNode();\nObject.defineProperties(Node_1.NamedNode, {\n MIN: {\n value: new Node_1.NamedNode(util_2.MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new Node_1.NamedNode(util_2.MAX_NAME, exports.MAX_NODE)\n }\n});\n/**\n * Reference Extensions\n */\nKeyIndex_1.KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode_1.LeafNode.__childrenNodeConstructor = ChildrenNode;\nsnap_1.setMaxNode(exports.MAX_NODE);\nPriorityIndex_1.setMaxNode(exports.MAX_NODE);\n\n//# sourceMappingURL=ChildrenNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/ChildrenNode.js\n// module id = 4\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nvar NamedNode = /** @class */ (function () {\n function NamedNode(name, node) {\n this.name = name;\n this.node = node;\n }\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n NamedNode.Wrap = function (name, node) {\n return new NamedNode(name, node);\n };\n return NamedNode;\n}());\nexports.NamedNode = NamedNode;\n\n//# sourceMappingURL=Node.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/Node.js\n// module id = 5\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexports.INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexports.INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexports.MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n/**\n * @param {*} key\n * @return {boolean}\n */\nexports.isValidKey = function (key) {\n return (typeof key === 'string' && key.length !== 0 && !exports.INVALID_KEY_REGEX_.test(key));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidPathString = function (pathString) {\n return (typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !exports.INVALID_PATH_REGEX_.test(pathString));\n};\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexports.isValidRootPathString = function (pathString) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n return exports.isValidPathString(pathString);\n};\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexports.isValidPriority = function (priority) {\n return (priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !util_2.isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && util_1.contains(priority, '.sv')));\n};\n/**\n * Pre-validate a datum passed as an argument to Firebase function.\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n exports.validateFirebaseData(util_3.errorPrefix(fnName, argumentNumber, optional), data, path);\n};\n/**\n * Validate a data object client-side before sending to server.\n *\n * @param {string} errorPrefix\n * @param {*} data\n * @param {!Path|!ValidationPath} path_\n */\nexports.validateFirebaseData = function (errorPrefix, data, path_) {\n var path = path_ instanceof Path_1.Path ? new Path_1.ValidationPath(path_, errorPrefix) : path_;\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString());\n }\n if (util_2.isInvalidJSONNumber(data)) {\n throw new Error(errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString());\n }\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (typeof data === 'string' &&\n data.length > exports.MAX_LEAF_SIZE_ / 3 &&\n util_4.stringLength(data) > exports.MAX_LEAF_SIZE_) {\n throw new Error(errorPrefix +\n 'contains a string greater than ' +\n exports.MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\");\n }\n // TODO = Perf = Consider combining the recursive validation of keys into NodeFromJSON\n // to save extra walking of large objects.\n if (data && typeof data === 'object') {\n var hasDotValue_1 = false, hasActualChild_1 = false;\n util_1.forEach(data, function (key, value) {\n if (key === '.value') {\n hasDotValue_1 = true;\n }\n else if (key !== '.priority' && key !== '.sv') {\n hasActualChild_1 = true;\n if (!exports.isValidKey(key)) {\n throw new Error(errorPrefix +\n ' contains an invalid key (' +\n key +\n ') ' +\n path.toErrorString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n path.push(key);\n exports.validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n if (hasDotValue_1 && hasActualChild_1) {\n throw new Error(errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.');\n }\n }\n};\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexports.validateFirebaseMergePaths = function (errorPrefix, mergePaths) {\n var i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n var keys = curPath.slice();\n for (var j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n }\n else if (!exports.isValidKey(keys[j])) {\n throw new Error(errorPrefix +\n 'contains an invalid key (' +\n keys[j] +\n ') in path ' +\n curPath.toString() +\n '. Keys must be non-empty strings ' +\n 'and can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\"');\n }\n }\n }\n // Check that update keys are not descendants of each other.\n // We rely on the property that sorting guarantees that ancestors come\n // right before descendants.\n mergePaths.sort(Path_1.Path.comparePaths);\n var prevPath = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString());\n }\n prevPath = curPath;\n }\n};\n/**\n * pre-validate an object passed as an argument to firebase function (\n * must be an object - e.g. for firebase.update()).\n *\n * @param {string} fnName\n * @param {number} argumentNumber\n * @param {*} data\n * @param {!Path} path\n * @param {boolean} optional\n */\nexports.validateFirebaseMergeDataArg = function (fnName, argumentNumber, data, path, optional) {\n if (optional && data === undefined)\n return;\n var errorPrefix = util_3.errorPrefix(fnName, argumentNumber, optional);\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(errorPrefix + ' must be an object containing the children to replace.');\n }\n var mergePaths = [];\n util_1.forEach(data, function (key, value) {\n var curPath = new Path_1.Path(key);\n exports.validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!exports.isValidPriority(value)) {\n throw new Error(errorPrefix +\n \"contains an invalid value for '\" +\n curPath.toString() +\n \"', which must be a valid \" +\n 'Firebase priority (a string, finite number, server value, or null).');\n }\n }\n mergePaths.push(curPath);\n });\n exports.validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\nexports.validatePriority = function (fnName, argumentNumber, priority, optional) {\n if (optional && priority === undefined)\n return;\n if (util_2.isInvalidJSONNumber(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'is ' +\n priority.toString() +\n ', but must be a valid Firebase priority (a string, finite number, ' +\n 'server value, or null).');\n // Special case to allow importing data with a .sv.\n if (!exports.isValidPriority(priority))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).');\n};\nexports.validateEventType = function (fnName, argumentNumber, eventType, optional) {\n if (optional && eventType === undefined)\n return;\n switch (eventType) {\n case 'value':\n case 'child_added':\n case 'child_removed':\n case 'child_changed':\n case 'child_moved':\n break;\n default:\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".');\n }\n};\nexports.validateKey = function (fnName, argumentNumber, key, optional) {\n if (optional && key === undefined)\n return;\n if (!exports.isValidKey(key))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid key = \"' +\n key +\n '\". Firebase keys must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"/\", \"[\", or \"]\").');\n};\nexports.validatePathString = function (fnName, argumentNumber, pathString, optional) {\n if (optional && pathString === undefined)\n return;\n if (!exports.isValidPathString(pathString))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"');\n};\nexports.validateRootPathString = function (fnName, argumentNumber, pathString, optional) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n exports.validatePathString(fnName, argumentNumber, pathString, optional);\n};\nexports.validateWritablePath = function (fnName, path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\nexports.validateUrl = function (fnName, argumentNumber, parsedUrl) {\n // TODO = Validate server better.\n var pathString = parsedUrl.path.toString();\n if (!(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n !exports.isValidKey(parsedUrl.repoInfo.namespace) ||\n (pathString.length !== 0 && !exports.isValidRootPathString(pathString))) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".');\n }\n};\nexports.validateCredential = function (fnName, argumentNumber, cred, optional) {\n if (optional && cred === undefined)\n return;\n if (!(typeof cred === 'string'))\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).');\n};\nexports.validateBoolean = function (fnName, argumentNumber, bool, optional) {\n if (optional && bool === undefined)\n return;\n if (typeof bool !== 'boolean')\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) + 'must be a boolean.');\n};\nexports.validateString = function (fnName, argumentNumber, string, optional) {\n if (optional && string === undefined)\n return;\n if (!(typeof string === 'string')) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid string.');\n }\n};\nexports.validateObject = function (fnName, argumentNumber, obj, optional) {\n if (optional && obj === undefined)\n return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid object.');\n }\n};\nexports.validateObjectContainsKey = function (fnName, argumentNumber, obj, key, optional, opt_type) {\n var objectContainsKey = obj && typeof obj === 'object' && util_1.contains(obj, key);\n if (!objectContainsKey) {\n if (optional) {\n return;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"');\n }\n }\n if (opt_type) {\n var val = util_1.safeGet(obj, key);\n if ((opt_type === 'number' && !(typeof val === 'number')) ||\n (opt_type === 'string' && !(typeof val === 'string')) ||\n (opt_type === 'boolean' && !(typeof val === 'boolean')) ||\n (opt_type === 'function' && !(typeof val === 'function')) ||\n (opt_type === 'object' && !(typeof val === 'object') && val)) {\n if (optional) {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'contains invalid value for key \"' +\n key +\n '\" (must be of type \"' +\n opt_type +\n '\")');\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"');\n }\n }\n }\n};\n\n//# sourceMappingURL=validation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/validation.js\n// module id = 7\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n *\n * @enum\n */\nvar OperationType;\n(function (OperationType) {\n OperationType[OperationType[\"OVERWRITE\"] = 0] = \"OVERWRITE\";\n OperationType[OperationType[\"MERGE\"] = 1] = \"MERGE\";\n OperationType[OperationType[\"ACK_USER_WRITE\"] = 2] = \"ACK_USER_WRITE\";\n OperationType[OperationType[\"LISTEN_COMPLETE\"] = 3] = \"LISTEN_COMPLETE\";\n})(OperationType = exports.OperationType || (exports.OperationType = {}));\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nvar OperationSource = /** @class */ (function () {\n function OperationSource(fromUser, fromServer, queryId, tagged) {\n this.fromUser = fromUser;\n this.fromServer = fromServer;\n this.queryId = queryId;\n this.tagged = tagged;\n util_1.assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.User = new OperationSource(\n /*fromUser=*/ true, false, null, \n /*tagged=*/ false);\n /**\n * @const\n * @type {!OperationSource}\n */\n OperationSource.Server = new OperationSource(false, \n /*fromServer=*/ true, null, \n /*tagged=*/ false);\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n OperationSource.forServerTaggedQuery = function (queryId) {\n return new OperationSource(false, \n /*fromServer=*/ true, queryId, \n /*tagged=*/ true);\n };\n return OperationSource;\n}());\nexports.OperationSource = OperationSource;\n\n//# sourceMappingURL=Operation.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Operation.js\n// module id = 8\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * @constructor\n * @struct\n * @param {!string} type The event type\n * @param {!Node} snapshotNode The data\n * @param {string=} childName The name for this child, if it's a child event\n * @param {Node=} oldSnap Used for intermediate processing of child changed events\n * @param {string=} prevName The name for the previous child, if applicable\n */\nvar Change = /** @class */ (function () {\n function Change(type, snapshotNode, childName, oldSnap, prevName) {\n this.type = type;\n this.snapshotNode = snapshotNode;\n this.childName = childName;\n this.oldSnap = oldSnap;\n this.prevName = prevName;\n }\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.valueChange = function (snapshot) {\n return new Change(Change.VALUE, snapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childAddedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childRemovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n };\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n Change.childChangedChange = function (childKey, newSnapshot, oldSnapshot) {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n };\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n Change.childMovedChange = function (childKey, snapshot) {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n };\n //event types\n /** Event type for a child added */\n Change.CHILD_ADDED = 'child_added';\n /** Event type for a child removed */\n Change.CHILD_REMOVED = 'child_removed';\n /** Event type for a child changed */\n Change.CHILD_CHANGED = 'child_changed';\n /** Event type for a child moved */\n Change.CHILD_MOVED = 'child_moved';\n /** Event type for a value change */\n Change.VALUE = 'value';\n return Change;\n}());\nexports.Change = Change;\n\n//# sourceMappingURL=Change.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Change.js\n// module id = 9\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar util_2 = require(\"@firebase/util\");\nvar __EMPTY_NODE;\nvar KeyIndex = /** @class */ (function (_super) {\n __extends(KeyIndex, _super);\n function KeyIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Object.defineProperty(KeyIndex, \"__EMPTY_NODE\", {\n get: function () {\n return __EMPTY_NODE;\n },\n set: function (val) {\n __EMPTY_NODE = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.compare = function (a, b) {\n return util_1.nameCompare(a.name, b.name);\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.isDefinedOn = function (node) {\n // We could probably return true here (since every node has a key), but it's never called\n // so just leaving unimplemented for now.\n throw util_2.assertionError('KeyIndex.isDefinedOn not expected to be called.');\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return false; // The key for a node never changes.\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n KeyIndex.prototype.maxPost = function () {\n // TODO: This should really be created once and cached in a static property, but\n // NamedNode isn't defined yet, so I can't use it in a static. Bleh.\n return new Node_1.NamedNode(util_1.MAX_NAME, __EMPTY_NODE);\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n KeyIndex.prototype.makePost = function (indexValue, name) {\n util_2.assert(typeof indexValue === 'string', 'KeyIndex indexValue must always be a string.');\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new Node_1.NamedNode(indexValue, __EMPTY_NODE);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n KeyIndex.prototype.toString = function () {\n return '.key';\n };\n return KeyIndex;\n}(Index_1.Index));\nexports.KeyIndex = KeyIndex;\nexports.KEY_INDEX = new KeyIndex();\n\n//# sourceMappingURL=KeyIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/KeyIndex.js\n// module id = 10\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./ChildrenNode\");\nvar LeafNode_1 = require(\"./LeafNode\");\nvar Node_1 = require(\"./Node\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar comparators_1 = require(\"./comparators\");\nvar IndexMap_1 = require(\"./IndexMap\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar USE_HINZE = true;\n/**\n * Constructs a snapshot node representing the passed JSON and returns it.\n * @param {*} json JSON to create a node for.\n * @param {?string|?number=} priority Optional priority to use. This will be ignored if the\n * passed JSON contains a .priority property.\n * @return {!Node}\n */\nfunction nodeFromJSON(json, priority) {\n if (priority === void 0) { priority = null; }\n if (json === null) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n util_2.assert(priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in priority), 'Invalid priority type found: ' + typeof priority);\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n var jsonLeaf = json;\n return new LeafNode_1.LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n if (!(json instanceof Array) && USE_HINZE) {\n var children_1 = [];\n var childrenHavePriority_1 = false;\n var hinzeJsonObj_1 = json;\n util_1.forEach(hinzeJsonObj_1, function (key, child) {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n var childNode = nodeFromJSON(hinzeJsonObj_1[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority_1 =\n childrenHavePriority_1 || !childNode.getPriority().isEmpty();\n children_1.push(new Node_1.NamedNode(key, childNode));\n }\n }\n });\n if (children_1.length == 0) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var childSet = childSet_1.buildChildSet(children_1, comparators_1.NAME_ONLY_COMPARATOR, function (namedNode) { return namedNode.name; }, comparators_1.NAME_COMPARATOR);\n if (childrenHavePriority_1) {\n var sortedChildSet = childSet_1.buildChildSet(children_1, PriorityIndex_1.PRIORITY_INDEX.getCompare());\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap_1.IndexMap({ '.priority': sortedChildSet }, { '.priority': PriorityIndex_1.PRIORITY_INDEX }));\n }\n else {\n return new ChildrenNode_1.ChildrenNode(childSet, nodeFromJSON(priority), IndexMap_1.IndexMap.Default);\n }\n }\n else {\n var node_1 = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var jsonObj_1 = json;\n util_1.forEach(jsonObj_1, function (key, childData) {\n if (util_1.contains(jsonObj_1, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n var childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node_1 = node_1.updateImmediateChild(key, childNode);\n }\n }\n });\n return node_1.updatePriority(nodeFromJSON(priority));\n }\n}\nexports.nodeFromJSON = nodeFromJSON;\nPriorityIndex_1.setNodeFromJSON(nodeFromJSON);\n\n//# sourceMappingURL=nodeFromJSON.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/nodeFromJSON.js\n// module id = 11\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DOMStorageWrapper_1 = require(\"./DOMStorageWrapper\");\nvar MemoryStorage_1 = require(\"./MemoryStorage\");\n/**\n * Helper to create a DOMStorageWrapper or else fall back to MemoryStorage.\n * TODO: Once MemoryStorage and DOMStorageWrapper have a shared interface this method annotation should change\n * to reflect this type\n *\n * @param {string} domStorageName Name of the underlying storage object\n * (e.g. 'localStorage' or 'sessionStorage').\n * @return {?} Turning off type information until a common interface is defined.\n */\nvar createStoragefor = function (domStorageName) {\n try {\n // NOTE: just accessing \"localStorage\" or \"window['localStorage']\" may throw a security exception,\n // so it must be inside the try/catch.\n if (typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined') {\n // Need to test cache. Just because it's here doesn't mean it works\n var domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper_1.DOMStorageWrapper(domStorage);\n }\n }\n catch (e) { }\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage_1.MemoryStorage();\n};\n/** A storage object that lasts across sessions */\nexports.PersistentStorage = createStoragefor('localStorage');\n/** A storage object that only lasts one session */\nexports.SessionStorage = createStoragefor('sessionStorage');\n\n//# sourceMappingURL=storage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/storage.js\n// module id = 13\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.PROTOCOL_VERSION = '5';\nexports.VERSION_PARAM = 'v';\nexports.TRANSPORT_SESSION_PARAM = 's';\nexports.REFERER_PARAM = 'r';\nexports.FORGE_REF = 'f';\nexports.FORGE_DOMAIN = 'firebaseio.com';\nexports.LAST_SESSION_PARAM = 'ls';\nexports.WEBSOCKET = 'websocket';\nexports.LONG_POLLING = 'long_polling';\n\n//# sourceMappingURL=Constants.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Constants.js\n// module id = 14\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\n/**\n *\n * @constructor\n */\nvar Index = /** @class */ (function () {\n function Index() {\n }\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n Index.prototype.getCompare = function () {\n return this.compare.bind(this);\n };\n /**\n * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,\n * it's possible that the changes are isolated to parts of the snapshot that are not indexed.\n *\n * @param {!Node} oldNode\n * @param {!Node} newNode\n * @return {boolean} True if the portion of the snapshot being indexed changed between oldNode and newNode\n */\n Index.prototype.indexedValueChanged = function (oldNode, newNode) {\n var oldWrapped = new Node_1.NamedNode(util_1.MIN_NAME, oldNode);\n var newWrapped = new Node_1.NamedNode(util_1.MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n };\n /**\n * @return {!NamedNode} a node wrapper that will sort equal to or less than\n * any other node wrapper, using this index\n */\n Index.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n return Index;\n}());\nexports.Index = Index;\n\n//# sourceMappingURL=Index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/Index.js\n// module id = 15\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar snap_1 = require(\"./snap\");\nvar __childrenNodeConstructor;\n/**\n * LeafNode is a class for storing leaf nodes in a DataSnapshot. It\n * implements Node and stores the value of the node (a string,\n * number, or boolean) accessible via getValue().\n */\nvar LeafNode = /** @class */ (function () {\n /**\n * @implements {Node}\n * @param {!(string|number|boolean|Object)} value_ The value to store in this leaf node.\n * The object type is possible in the event of a deferred value\n * @param {!Node=} priorityNode_ The priority of this node.\n */\n function LeafNode(value_, priorityNode_) {\n if (priorityNode_ === void 0) { priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE; }\n this.value_ = value_;\n this.priorityNode_ = priorityNode_;\n this.lazyHash_ = null;\n util_1.assert(this.value_ !== undefined && this.value_ !== null, \"LeafNode shouldn't be created with null/undefined value.\");\n snap_1.validatePriorityNode(this.priorityNode_);\n }\n Object.defineProperty(LeafNode, \"__childrenNodeConstructor\", {\n get: function () {\n return __childrenNodeConstructor;\n },\n set: function (val) {\n __childrenNodeConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /** @inheritDoc */\n LeafNode.prototype.isLeafNode = function () {\n return true;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPriority = function () {\n return this.priorityNode_;\n };\n /** @inheritDoc */\n LeafNode.prototype.updatePriority = function (newPriorityNode) {\n return new LeafNode(this.value_, newPriorityNode);\n };\n /** @inheritDoc */\n LeafNode.prototype.getImmediateChild = function (childName) {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.getChild = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.hasChild = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.getPredecessorChildName = function (childName, childNode) {\n return null;\n };\n /** @inheritDoc */\n LeafNode.prototype.updateImmediateChild = function (childName, newChildNode) {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n }\n else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n }\n else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.updateChild = function (path, newChildNode) {\n var front = path.getFront();\n if (front === null) {\n return newChildNode;\n }\n else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n }\n else {\n util_1.assert(front !== '.priority' || path.getLength() === 1, '.priority must be the last token in a path');\n return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(path.popFront(), newChildNode));\n }\n };\n /** @inheritDoc */\n LeafNode.prototype.isEmpty = function () {\n return false;\n };\n /** @inheritDoc */\n LeafNode.prototype.numChildren = function () {\n return 0;\n };\n /** @inheritDoc */\n LeafNode.prototype.forEachChild = function (index, action) {\n return false;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.val = function (exportFormat) {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else\n return this.getValue();\n };\n /** @inheritDoc */\n LeafNode.prototype.hash = function () {\n if (this.lazyHash_ === null) {\n var toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n snap_1.priorityHashText(this.priorityNode_.val()) +\n ':';\n var type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += util_2.doubleToIEEE754String(this.value_);\n }\n else {\n toHash += this.value_;\n }\n this.lazyHash_ = util_2.sha1(toHash);\n }\n return this.lazyHash_;\n };\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n LeafNode.prototype.getValue = function () {\n return this.value_;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.compareTo = function (other) {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n }\n else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n }\n else {\n util_1.assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other);\n }\n };\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n LeafNode.prototype.compareToLeafNode_ = function (otherLeaf) {\n var otherLeafType = typeof otherLeaf.value_;\n var thisLeafType = typeof this.value_;\n var otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n var thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n util_1.assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n util_1.assert(thisIndex >= 0, 'Unknown leaf type: ' + thisLeafType);\n if (otherIndex === thisIndex) {\n // Same type, compare values\n if (thisLeafType === 'object') {\n // Deferred value nodes are all equal, but we should also never get to this point...\n return 0;\n }\n else {\n // Note that this works because true > false, all others are number or string comparisons\n if (this.value_ < otherLeaf.value_) {\n return -1;\n }\n else if (this.value_ === otherLeaf.value_) {\n return 0;\n }\n else {\n return 1;\n }\n }\n }\n else {\n return thisIndex - otherIndex;\n }\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.withIndex = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.isIndexed = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LeafNode.prototype.equals = function (other) {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n }\n else if (other.isLeafNode()) {\n var otherLeaf = other;\n return (this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_));\n }\n else {\n return false;\n }\n };\n /**\n * The sort order for comparing leaf nodes of different types. If two leaf nodes have\n * the same type, the comparison falls back to their value\n * @type {Array.}\n * @const\n */\n LeafNode.VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n return LeafNode;\n}());\nexports.LeafNode = LeafNode;\n\n//# sourceMappingURL=LeafNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/LeafNode.js\n// module id = 16\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * An iterator over an LLRBNode.\n */\nvar SortedMapIterator = /** @class */ (function () {\n /**\n * @template K, V, T\n * @param {LLRBNode|LLRBEmptyNode} node Node to iterate.\n * @param {?K} startKey\n * @param {function(K, K): number} comparator\n * @param {boolean} isReverse_ Whether or not to iterate in reverse\n * @param {(function(K, V):T)=} resultGenerator_\n */\n function SortedMapIterator(node, startKey, comparator, isReverse_, resultGenerator_) {\n if (resultGenerator_ === void 0) { resultGenerator_ = null; }\n this.isReverse_ = isReverse_;\n this.resultGenerator_ = resultGenerator_;\n /** @private\n * @type {Array.}\n */\n this.nodeStack_ = [];\n var cmp = 1;\n while (!node.isEmpty()) {\n node = node;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_)\n cmp *= -1;\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n }\n else {\n node = node.right;\n }\n }\n else if (cmp === 0) {\n // This node is exactly equal to our start key. Push it on the stack, but stop iterating;\n this.nodeStack_.push(node);\n break;\n }\n else {\n // This node is greater than our start key, add it to the stack and move to the next one\n this.nodeStack_.push(node);\n if (this.isReverse_) {\n node = node.right;\n }\n else {\n node = node.left;\n }\n }\n }\n }\n SortedMapIterator.prototype.getNext = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_.pop();\n var result;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else\n result = { key: node.key, value: node.value };\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n }\n else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n return result;\n };\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack_.length > 0;\n };\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack_.length === 0)\n return null;\n var node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n }\n else {\n return { key: node.key, value: node.value };\n }\n };\n return SortedMapIterator;\n}());\nexports.SortedMapIterator = SortedMapIterator;\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nvar LLRBNode = /** @class */ (function () {\n /**\n * @template K, V\n * @param {!K} key Key associated with this node.\n * @param {!V} value Value associated with this node.\n * @param {?boolean} color Whether this node is red.\n * @param {?(LLRBNode|LLRBEmptyNode)=} left Left child.\n * @param {?(LLRBNode|LLRBEmptyNode)=} right Right child.\n */\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE;\n }\n /**\n * Returns a copy of the current node, optionally replacing pieces of it.\n *\n * @param {?K} key New key for the node, or null.\n * @param {?V} value New value for the node, or null.\n * @param {?boolean} color New color for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} left New left child for the node, or null.\n * @param {?LLRBNode|LLRBEmptyNode} right New right child for the node, or null.\n * @return {!LLRBNode} The node copy.\n */\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\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);\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBNode.prototype.count = function () {\n return this.left.count() + 1 + this.right.count();\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBNode.prototype.isEmpty = function () {\n return false;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n LLRBNode.prototype.inorderTraversal = function (action) {\n return (this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action));\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!Object, !Object)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {*} True if traversal was aborted.\n */\n LLRBNode.prototype.reverseTraversal = function (action) {\n return (this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action));\n };\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n LLRBNode.prototype.min_ = function () {\n if (this.left.isEmpty()) {\n return this;\n }\n else {\n return this.left.min_();\n }\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.minKey = function () {\n return this.min_().key;\n };\n /**\n * @return {!K} The maximum key in the tree.\n */\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n }\n else {\n return this.right.maxKey();\n }\n };\n /**\n *\n * @param {!Object} key Key to insert.\n * @param {!Object} value Value to insert.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with the key/value added.\n */\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var cmp, n;\n n = this;\n cmp = comparator(key, n.key);\n if (cmp < 0) {\n n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);\n }\n else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n }\n else {\n n = n.copy(null, null, null, null, n.right.insert(key, value, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n LLRBNode.prototype.removeMin_ = function () {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n var n = this;\n if (!n.left.isRed_() && !n.left.left.isRed_())\n n = n.moveRedLeft_();\n n = n.copy(null, null, null, n.left.removeMin_(), null);\n return n.fixUp_();\n };\n /**\n * @param {!Object} key The key of the item to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the specified item removed.\n */\n LLRBNode.prototype.remove = function (key, comparator) {\n var n, smallest;\n n = this;\n if (comparator(key, n.key) < 0) {\n if (!n.left.isEmpty() && !n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, n.left.remove(key, comparator), null);\n }\n else {\n if (n.left.isRed_())\n n = n.rotateRight_();\n if (!n.right.isEmpty() && !n.right.isRed_() && !n.right.left.isRed_()) {\n n = n.moveRedRight_();\n }\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return SortedMap.EMPTY_NODE;\n }\n else {\n smallest = n.right.min_();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin_());\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n };\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n LLRBNode.prototype.isRed_ = function () {\n return this.color;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n LLRBNode.prototype.fixUp_ = function () {\n var n = this;\n if (n.right.isRed_() && !n.left.isRed_())\n n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_())\n n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_())\n n = n.colorFlip_();\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n LLRBNode.prototype.moveRedLeft_ = function () {\n var n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(null, null, null, null, n.right.rotateRight_());\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n LLRBNode.prototype.moveRedRight_ = function () {\n var n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n LLRBNode.prototype.rotateLeft_ = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n LLRBNode.prototype.rotateRight_ = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n LLRBNode.prototype.colorFlip_ = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n };\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n LLRBNode.prototype.checkMaxDepth_ = function () {\n var blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBNode.prototype.check_ = function () {\n var blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed_()) {\n throw new Error('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n }\n else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n };\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}());\nexports.LLRBNode = LLRBNode;\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nvar LLRBEmptyNode = /** @class */ (function () {\n function LLRBEmptyNode() {\n }\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n };\n /**\n * Returns a copy of the tree, with the specified key/value added.\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBNode} New tree, with item added.\n */\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value, null);\n };\n /**\n * Returns a copy of the tree, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @param {Comparator} comparator Comparator.\n * @return {!LLRBEmptyNode} New tree, with item removed.\n */\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n /**\n * @return {number} The total number of nodes in the tree.\n */\n LLRBEmptyNode.prototype.count = function () {\n return 0;\n };\n /**\n * @return {boolean} True if the tree is empty.\n */\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n /**\n * Traverses the tree in key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V):*} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n /**\n * Traverses the tree in reverse key order and calls the specified action function\n * for each node.\n *\n * @param {function(!K, !V)} action Callback function to be called for each\n * node. If it returns true, traversal is aborted.\n * @return {boolean} True if traversal was aborted.\n */\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n /**\n * @return {null}\n */\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n LLRBEmptyNode.prototype.check_ = function () {\n return 0;\n };\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n LLRBEmptyNode.prototype.isRed_ = function () {\n return false;\n };\n return LLRBEmptyNode;\n}());\nexports.LLRBEmptyNode = LLRBEmptyNode;\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nvar SortedMap = /** @class */ (function () {\n /**\n * @template K, V\n * @param {function(K, K):number} comparator_ Key comparator.\n * @param {LLRBNode=} root_ (Optional) Root node for the map.\n */\n function SortedMap(comparator_, root_) {\n if (root_ === void 0) { root_ = SortedMap.EMPTY_NODE; }\n this.comparator_ = comparator_;\n this.root_ = root_;\n }\n /**\n * Returns a copy of the map, with the specified key/value added or replaced.\n * (TODO: We should perhaps rename this method to 'put')\n *\n * @param {!K} key Key to be added.\n * @param {!V} value Value to be added.\n * @return {!SortedMap.} New map, with item added.\n */\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator_, this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns a copy of the map, with the specified key removed.\n *\n * @param {!K} key The key to remove.\n * @return {!SortedMap.} New map, with item removed.\n */\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator_, this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null));\n };\n /**\n * Returns the value of the node with the given key, or null.\n *\n * @param {!K} key The key to look up.\n * @return {?V} The value of the node with the given key, or null if the\n * key doesn't exist.\n */\n SortedMap.prototype.get = function (key) {\n var cmp;\n var node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n };\n /**\n * Returns the key of the item *before* the specified key, or null if key is the first item.\n * @param {K} key The key to find the predecessor of\n * @return {?K} The predecessor key.\n */\n SortedMap.prototype.getPredecessorKey = function (key) {\n var cmp, node = this.root_, rightParent = null;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n if (!node.left.isEmpty()) {\n node = node.left;\n while (!node.right.isEmpty())\n node = node.right;\n return node.key;\n }\n else if (rightParent) {\n return rightParent.key;\n }\n else {\n return null; // first item.\n }\n }\n else if (cmp < 0) {\n node = node.left;\n }\n else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n throw new Error('Attempted to find predecessor key for a nonexistent key. What gives?');\n };\n /**\n * @return {boolean} True if the map is empty.\n */\n SortedMap.prototype.isEmpty = function () {\n return this.root_.isEmpty();\n };\n /**\n * @return {number} The total number of nodes in the map.\n */\n SortedMap.prototype.count = function () {\n return this.root_.count();\n };\n /**\n * @return {?K} The minimum key in the map.\n */\n SortedMap.prototype.minKey = function () {\n return this.root_.minKey();\n };\n /**\n * @return {?K} The maximum key in the map.\n */\n SortedMap.prototype.maxKey = function () {\n return this.root_.maxKey();\n };\n /**\n * Traverses the map in key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!K, !V):*} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} The first truthy value returned by action, or the last falsey\n * value returned by action\n */\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root_.inorderTraversal(action);\n };\n /**\n * Traverses the map in reverse key order and calls the specified action function\n * for each key/value pair.\n *\n * @param {function(!Object, !Object)} action Callback function to be called\n * for each key/value pair. If action returns true, traversal is aborted.\n * @return {*} True if the traversal was aborted.\n */\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root_.reverseTraversal(action);\n };\n /**\n * Returns an iterator over the SortedMap.\n * @template T\n * @param {(function(K, V):T)=} resultGenerator\n * @return {SortedMapIterator.} The iterator.\n */\n SortedMap.prototype.getIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);\n };\n SortedMap.prototype.getReverseIteratorFrom = function (key, resultGenerator) {\n return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);\n };\n SortedMap.prototype.getReverseIterator = function (resultGenerator) {\n return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);\n };\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n SortedMap.EMPTY_NODE = new LLRBEmptyNode();\n return SortedMap;\n}());\nexports.SortedMap = SortedMap;\n\n//# sourceMappingURL=SortedMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/SortedMap.js\n// module id = 17\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar Path_1 = require(\"./util/Path\");\nvar SparseSnapshotTree_1 = require(\"./SparseSnapshotTree\");\nvar SyncTree_1 = require(\"./SyncTree\");\nvar SnapshotHolder_1 = require(\"./SnapshotHolder\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar AuthTokenProvider_1 = require(\"./AuthTokenProvider\");\nvar StatsManager_1 = require(\"./stats/StatsManager\");\nvar StatsReporter_1 = require(\"./stats/StatsReporter\");\nvar StatsListener_1 = require(\"./stats/StatsListener\");\nvar EventQueue_1 = require(\"./view/EventQueue\");\nvar PersistentConnection_1 = require(\"./PersistentConnection\");\nvar ReadonlyRestClient_1 = require(\"./ReadonlyRestClient\");\nvar Database_1 = require(\"../api/Database\");\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\n * A connection to a single data repository.\n */\nvar Repo = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue_1.EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null;\n // A list of data pieces and paths to be set when this client disconnects.\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n var authTokenProvider = new AuthTokenProvider_1.AuthTokenProvider(app);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo_);\n if (forceRestClient || util_2.beingCrawled()) {\n this.server_ = new ReadonlyRestClient_1.ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider);\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n }\n else {\n var authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n try {\n util_1.stringify(authOverride);\n }\n catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n this.persistentConnection_ = new PersistentConnection_1.PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n });\n // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n this.statsReporter_ = StatsManager_1.StatsManager.getOrCreateReporter(repoInfo_, function () { return new StatsReporter_1.StatsReporter(_this.stats_, _this.server_); });\n this.transactions_init_();\n // Used for .info.\n this.infoData_ = new SnapshotHolder_1.SnapshotHolder();\n this.infoSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n var node = _this.infoData_.getNode(query.path);\n // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: function () { }\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree_1.SyncTree({\n startListening: function (query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n });\n // No synchronous events for network-backed sync trees\n return [];\n },\n stopListening: function (query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n Repo.prototype.toString = function () {\n return ((this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host);\n };\n /**\n * @return {!string} The namespace represented by the repo.\n */\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path_1.Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n Repo.prototype.generateServerValues = function () {\n return ServerValues_1.generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\n * Called by realtime when we get new messages from the server.\n *\n * @private\n * @param {string} pathString\n * @param {*} data\n * @param {boolean} isMerge\n * @param {?number} tag\n */\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path_1.Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n var events = [];\n if (tag) {\n if (isMerge) {\n var taggedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n }\n else {\n var taggedSnap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n }\n else if (isMerge) {\n var changedChildren = util_3.map(data, function (raw) {\n return nodeFromJSON_1.nodeFromJSON(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n }\n else {\n var snap = nodeFromJSON_1.nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n var affectedPath = path;\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @param {?function(!string, *):*} callback\n * @private\n */\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\n * @param {!Object} updates\n * @private\n */\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n util_2.each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path_1.Path('/.info/' + pathString);\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\n * @return {!number}\n * @private\n */\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\n // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, newPriority);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(/*export=*/ true), function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('set at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n // Start with our existing data and merge each child into it.\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util_3.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(changedValue);\n changedChildren[changedKey] = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n if (!success) {\n util_2.warn('update at ' + path + ' failed: ' + status);\n }\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util_3.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n _this.rerunTransactions_(affectedPath);\n });\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n }\n else {\n util_2.log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = ServerValues_1.resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path_1.Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n var affectedPath = _this.abortTransactions_(path);\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree_1.SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path_1.Path.Empty, events);\n };\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n var newNode = nodeFromJSON_1.nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(/*export=*/ true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n if (util_3.isEmpty(childrenToMerge)) {\n util_2.log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util_3.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON_1.nodeFromJSON(childNode);\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) { showDelta = false; }\n if (typeof console === 'undefined')\n return;\n var stats;\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener_1.StatsListener(this.stats_);\n stats = this.statsListener_.get();\n }\n else {\n stats = this.stats_.get();\n }\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util_3.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++)\n stat += ' ';\n console.log(stat + value);\n });\n };\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\n * @param {...*} var_args\n * @private\n */\n Repo.prototype.log_ = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n util_2.log.apply(void 0, [prefix].concat(var_args));\n };\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n util_2.exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n }\n else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason)\n message += ': ' + errorReason;\n var error = new Error(message);\n error.code = code;\n callback(error);\n }\n });\n }\n };\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function () {\n return this.__database || (this.__database = new Database_1.Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}());\nexports.Repo = Repo;\n\n//# sourceMappingURL=Repo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo.js\n// module id = 18\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * A cache node only stores complete children. Additionally it holds a flag whether the node can be considered fully\n * initialized in the sense that we know at one point in time this represented a valid state of the world, e.g.\n * initialized with data from the server, or a complete overwrite by the client. The filtered flag also tracks\n * whether a node potentially had children removed due to a filter.\n */\nvar CacheNode = /** @class */ (function () {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n function CacheNode(node_, fullyInitialized_, filtered_) {\n this.node_ = node_;\n this.fullyInitialized_ = fullyInitialized_;\n this.filtered_ = filtered_;\n }\n /**\n * Returns whether this node was fully initialized with either server data or a complete overwrite by the client\n * @return {boolean}\n */\n CacheNode.prototype.isFullyInitialized = function () {\n return this.fullyInitialized_;\n };\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n CacheNode.prototype.isFiltered = function () {\n return this.filtered_;\n };\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForPath = function (path) {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n var childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n };\n /**\n * @param {!string} key\n * @return {boolean}\n */\n CacheNode.prototype.isCompleteForChild = function (key) {\n return ((this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key));\n };\n /**\n * @return {!Node}\n */\n CacheNode.prototype.getNode = function () {\n return this.node_;\n };\n return CacheNode;\n}());\nexports.CacheNode = CacheNode;\n\n//# sourceMappingURL=CacheNode.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CacheNode.js\n// module id = 19\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar onDisconnect_1 = require(\"./onDisconnect\");\nvar TransactionResult_1 = require(\"./TransactionResult\");\nvar util_1 = require(\"../core/util/util\");\nvar NextPushId_1 = require(\"../core/util/NextPushId\");\nvar Query_1 = require(\"./Query\");\nvar Repo_1 = require(\"../core/Repo\");\nvar Path_1 = require(\"../core/util/Path\");\nvar QueryParams_1 = require(\"../core/view/QueryParams\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar SyncPoint_1 = require(\"../core/SyncPoint\");\nvar Reference = /** @class */ (function (_super) {\n __extends(Reference, _super);\n /**\n * Call options:\n * new Reference(Repo, Path) or\n * new Reference(url: string, string|RepoManager)\n *\n * Externally - this is the firebase.database.Reference type.\n *\n * @param {!Repo} repo\n * @param {(!Path)} path\n * @extends {Query}\n */\n function Reference(repo, path) {\n var _this = this;\n if (!(repo instanceof Repo_1.Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n }\n // call Query's constructor, passing in the repo and path.\n _this = _super.call(this, repo, path, QueryParams_1.QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n Reference.prototype.getKey = function () {\n util_2.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty())\n return null;\n else\n return this.path.getBack();\n };\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n Reference.prototype.child = function (pathString) {\n util_2.validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n }\n else if (!(pathString instanceof Path_1.Path)) {\n if (this.path.getFront() === null)\n validation_1.validateRootPathString('Reference.child', 1, pathString, false);\n else\n validation_1.validatePathString('Reference.child', 1, pathString, false);\n }\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n Reference.prototype.getParent = function () {\n util_2.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n Reference.prototype.getRoot = function () {\n util_2.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n };\n /** @return {!Database} */\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.set = function (newVal, onComplete) {\n util_2.validateArgCount('Reference.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.set', this.path);\n validation_1.validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util_2.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, \n /*priority=*/ null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util_2.validateArgCount('Reference.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.update', this.path);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_1.warn('Passing an Array to Firebase.update() is deprecated. ' +\n 'Use set() if you want to overwrite the existing data, or ' +\n 'an Object with integer keys if you really do want to ' +\n 'only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util_2.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util_2.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('Reference.setWithPriority', this.path);\n validation_1.validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validation_1.validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util_2.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.remove = function (onComplete) {\n util_2.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('Reference.remove', this.path);\n util_2.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util_2.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validation_1.validateWritablePath('Reference.transaction', this.path);\n util_2.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util_2.validateCallback('Reference.transaction', 2, onComplete, true);\n // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n validation_1.validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n if (applyLocally === undefined)\n applyLocally = true;\n var deferred = new util_3.Deferred();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () { });\n }\n var promiseComplete = function (error, committed, snapshot) {\n if (error) {\n deferred.reject(error);\n }\n else {\n deferred.resolve(new TransactionResult_1.TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n Reference.prototype.setPriority = function (priority, onComplete) {\n util_2.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validation_1.validateWritablePath('Reference.setPriority', this.path);\n validation_1.validatePriority('Reference.setPriority', 1, priority, false);\n util_2.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n Reference.prototype.push = function (value, onComplete) {\n util_2.validateArgCount('Reference.push', 0, 2, arguments.length);\n validation_1.validateWritablePath('Reference.push', this.path);\n validation_1.validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util_2.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = NextPushId_1.nextPushId(now);\n // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () { return pushRef; });\n }\n else {\n promise = Promise.resolve(pushRef);\n }\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n if (typeof onComplete === 'function') {\n promise.catch(function () { });\n }\n return thennablePushRef;\n };\n /**\n * @return {!OnDisconnect}\n */\n Reference.prototype.onDisconnect = function () {\n validation_1.validateWritablePath('Reference.onDisconnect', this.path);\n return new onDisconnect_1.OnDisconnect(this.repo, this.path);\n };\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function () {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function () {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function () {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function () {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query_1.Query));\nexports.Reference = Reference;\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery_1.Query.__referenceConstructor = Reference;\nSyncPoint_1.SyncPoint.__referenceConstructor = Reference;\n\n//# sourceMappingURL=Reference.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Reference.js\n// module id = 21\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar Path_1 = require(\"../core/util/Path\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\n/**\n * Class representing a firebase data snapshot. It wraps a SnapshotNode and\n * surfaces the public methods (val, forEach, etc.) we want to expose.\n */\nvar DataSnapshot = /** @class */ (function () {\n /**\n * @param {!Node} node_ A SnapshotNode to wrap.\n * @param {!Reference} ref_ The ref of the location this snapshot came from.\n * @param {!Index} index_ The iteration order for this snapshot\n */\n function DataSnapshot(node_, ref_, index_) {\n this.node_ = node_;\n this.ref_ = ref_;\n this.index_ = index_;\n }\n /**\n * Retrieves the snapshot contents as JSON. Returns null if the snapshot is\n * empty.\n *\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.val = function () {\n util_1.validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n };\n /**\n * Returns the snapshot contents as JSON, including priorities of node. Suitable for exporting\n * the entire node contents.\n * @return {*} JSON representation of the DataSnapshot contents, or null if empty.\n */\n DataSnapshot.prototype.exportVal = function () {\n util_1.validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n DataSnapshot.prototype.toJSON = function () {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n util_1.validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n };\n /**\n * Returns whether the snapshot contains a non-null value.\n *\n * @return {boolean} Whether the snapshot contains a non-null value, or is empty.\n */\n DataSnapshot.prototype.exists = function () {\n util_1.validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n };\n /**\n * Returns a DataSnapshot of the specified child node's contents.\n *\n * @param {!string} childPathString Path to a child.\n * @return {!DataSnapshot} DataSnapshot for child node.\n */\n DataSnapshot.prototype.child = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validation_1.validatePathString('DataSnapshot.child', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n var childRef = this.ref_.child(childPath);\n return new DataSnapshot(this.node_.getChild(childPath), childRef, PriorityIndex_1.PRIORITY_INDEX);\n };\n /**\n * Returns whether the snapshot contains a child at the specified path.\n *\n * @param {!string} childPathString Path to a child.\n * @return {boolean} Whether the child exists.\n */\n DataSnapshot.prototype.hasChild = function (childPathString) {\n util_1.validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validation_1.validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n var childPath = new Path_1.Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n };\n /**\n * Returns the priority of the object, or null if no priority was set.\n *\n * @return {string|number|null} The priority.\n */\n DataSnapshot.prototype.getPriority = function () {\n util_1.validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val();\n };\n /**\n * Iterates through child nodes and calls the specified action for each one.\n *\n * @param {function(!DataSnapshot)} action Callback function to be called\n * for each child.\n * @return {boolean} True if forEach was canceled by action returning true for\n * one of the child nodes.\n */\n DataSnapshot.prototype.forEach = function (action) {\n var _this = this;\n util_1.validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n util_1.validateCallback('DataSnapshot.forEach', 1, action, false);\n if (this.node_.isLeafNode())\n return false;\n var childrenNode = this.node_;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, function (key, node) {\n return action(new DataSnapshot(node, _this.ref_.child(key), PriorityIndex_1.PRIORITY_INDEX));\n });\n };\n /**\n * Returns whether this DataSnapshot has children.\n * @return {boolean} True if the DataSnapshot contains 1 or more child nodes.\n */\n DataSnapshot.prototype.hasChildren = function () {\n util_1.validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n if (this.node_.isLeafNode())\n return false;\n else\n return !this.node_.isEmpty();\n };\n Object.defineProperty(DataSnapshot.prototype, \"key\", {\n get: function () {\n return this.ref_.getKey();\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n DataSnapshot.prototype.numChildren = function () {\n util_1.validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n return this.node_.numChildren();\n };\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n DataSnapshot.prototype.getRef = function () {\n util_1.validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n return this.ref_;\n };\n Object.defineProperty(DataSnapshot.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return DataSnapshot;\n}());\nexports.DataSnapshot = DataSnapshot;\n\n//# sourceMappingURL=DataSnapshot.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/DataSnapshot.js\n// module id = 22\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"./SortedMap\");\nvar Path_1 = require(\"./Path\");\nvar util_1 = require(\"./util\");\nvar util_2 = require(\"@firebase/util\");\nvar emptyChildrenSingleton;\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nvar EmptyChildren = function () {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap_1.SortedMap(util_1.stringCompare);\n }\n return emptyChildrenSingleton;\n};\n/**\n * A tree with immutable elements.\n */\nvar ImmutableTree = /** @class */ (function () {\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n function ImmutableTree(value, children) {\n if (children === void 0) { children = EmptyChildren(); }\n this.value = value;\n this.children = children;\n }\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n ImmutableTree.fromObject = function (obj) {\n var tree = ImmutableTree.Empty;\n util_2.forEach(obj, function (childPath, childSnap) {\n tree = tree.set(new Path_1.Path(childPath), childSnap);\n });\n return tree;\n };\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n ImmutableTree.prototype.isEmpty = function () {\n return this.value === null && this.children.isEmpty();\n };\n /**\n * Given a path and predicate, return the first node and the path to that node\n * where the predicate returns true.\n *\n * TODO Do a perf test -- If we're creating a bunch of {path: value:} objects\n * on the way back out, it may be better to pass down a pathSoFar obj.\n *\n * @param {!Path} relativePath The remainder of the path\n * @param {function(T):boolean} predicate The predicate to satisfy to return a\n * node\n * @return {?{path:!Path, value:!T}}\n */\n ImmutableTree.prototype.findRootMostMatchingPathAndValue = function (relativePath, predicate) {\n if (this.value != null && predicate(this.value)) {\n return { path: Path_1.Path.Empty, value: this.value };\n }\n else {\n if (relativePath.isEmpty()) {\n return null;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child !== null) {\n var childExistingPathAndValue = child.findRootMostMatchingPathAndValue(relativePath.popFront(), predicate);\n if (childExistingPathAndValue != null) {\n var fullPath = new Path_1.Path(front).child(childExistingPathAndValue.path);\n return { path: fullPath, value: childExistingPathAndValue.value };\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n * Find, if it exists, the shortest subpath of the given path that points a defined\n * value in the tree\n * @param {!Path} relativePath\n * @return {?{path: !Path, value: !T}}\n */\n ImmutableTree.prototype.findRootMostValueAndPath = function (relativePath) {\n return this.findRootMostMatchingPathAndValue(relativePath, function () { return true; });\n };\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n ImmutableTree.prototype.subtree = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this;\n }\n else {\n var front = relativePath.getFront();\n var childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Sets a value at the specified path.\n *\n * @param {!Path} relativePath Path to set value at.\n * @param {?T} toSet Value to set.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.set = function (relativePath, toSet) {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.set(relativePath.popFront(), toSet);\n var newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Removes the value at the specified path.\n *\n * @param {!Path} relativePath Path to value to remove.\n * @return {!ImmutableTree.} Resulting tree.\n */\n ImmutableTree.prototype.remove = function (relativePath) {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(null, this.children);\n }\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n var newChild = child.remove(relativePath.popFront());\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n }\n else {\n return new ImmutableTree(this.value, newChildren);\n }\n }\n else {\n return this;\n }\n }\n };\n /**\n * Gets a value from the tree.\n *\n * @param {!Path} relativePath Path to get value for.\n * @return {?T} Value at path, or null.\n */\n ImmutableTree.prototype.get = function (relativePath) {\n if (relativePath.isEmpty()) {\n return this.value;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n }\n else {\n return null;\n }\n }\n };\n /**\n * Replace the subtree at the specified path with the given new tree.\n *\n * @param {!Path} relativePath Path to replace subtree for.\n * @param {!ImmutableTree} newTree New tree.\n * @return {!ImmutableTree} Resulting tree.\n */\n ImmutableTree.prototype.setTree = function (relativePath, newTree) {\n if (relativePath.isEmpty()) {\n return newTree;\n }\n else {\n var front = relativePath.getFront();\n var child = this.children.get(front) || ImmutableTree.Empty;\n var newChild = child.setTree(relativePath.popFront(), newTree);\n var newChildren = void 0;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n }\n else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\n };\n /**\n * Performs a depth first fold on this tree. Transforms a tree into a single\n * value, given a function that operates on the path to a node, an optional\n * current value, and a map of child names to folded subtrees\n * @template V\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n */\n ImmutableTree.prototype.fold = function (fn) {\n return this.fold_(Path_1.Path.Empty, fn);\n };\n /**\n * Recursive helper for public-facing fold() method\n * @template V\n * @param {!Path} pathSoFar\n * @param {function(Path, ?T, Object.):V} fn\n * @return {V}\n * @private\n */\n ImmutableTree.prototype.fold_ = function (pathSoFar, fn) {\n var accum = {};\n this.children.inorderTraversal(function (childKey, childTree) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n };\n /**\n * Find the first matching value on the given path. Return the result of applying f to it.\n * @template V\n * @param {!Path} path\n * @param {!function(!Path, !T):?V} f\n * @return {?V}\n */\n ImmutableTree.prototype.findOnPath = function (path, f) {\n return this.findOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.findOnPath_ = function (pathToFollow, pathSoFar, f) {\n var result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n }\n else {\n if (pathToFollow.isEmpty()) {\n return null;\n }\n else {\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(pathToFollow.popFront(), pathSoFar.child(front), f);\n }\n else {\n return null;\n }\n }\n }\n };\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n ImmutableTree.prototype.foreachOnPath = function (path, f) {\n return this.foreachOnPath_(path, Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreachOnPath_ = function (pathToFollow, currentRelativePath, f) {\n if (pathToFollow.isEmpty()) {\n return this;\n }\n else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n var front = pathToFollow.getFront();\n var nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(pathToFollow.popFront(), currentRelativePath.child(front), f);\n }\n else {\n return ImmutableTree.Empty;\n }\n }\n };\n /**\n * Calls the given function for each node in the tree that has a value.\n *\n * @param {function(!Path, !T)} f A function to be called with\n * the path from the root of the tree to a node, and the value at that node.\n * Called in depth-first order.\n */\n ImmutableTree.prototype.foreach = function (f) {\n this.foreach_(Path_1.Path.Empty, f);\n };\n ImmutableTree.prototype.foreach_ = function (currentRelativePath, f) {\n this.children.inorderTraversal(function (childName, childTree) {\n childTree.foreach_(currentRelativePath.child(childName), f);\n });\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n };\n /**\n *\n * @param {function(string, !T)} f\n */\n ImmutableTree.prototype.foreachChild = function (f) {\n this.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n });\n };\n ImmutableTree.Empty = new ImmutableTree(null);\n return ImmutableTree;\n}());\nexports.ImmutableTree = ImmutableTree;\n\n//# sourceMappingURL=ImmutableTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ImmutableTree.js\n// module id = 23\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\n/**\n * Doesn't really filter nodes but applies an index to the node and keeps track of any changes\n *\n * @constructor\n * @implements {NodeFilter}\n * @param {!Index} index\n */\nvar IndexedFilter = /** @class */ (function () {\n function IndexedFilter(index_) {\n this.index_ = index_;\n }\n IndexedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n util_1.assert(snap.isIndexed(this.index_), 'A node must be indexed if only a child is updated');\n var oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {\n // There's an edge case where a child can enter or leave the view because affectedPath was set to null.\n // In this case, affectedPath will appear null in both the old and new snapshots. So we need\n // to avoid treating these cases as \"nothing changed.\"\n if (oldChild.isEmpty() == newChild.isEmpty()) {\n // Nothing changed.\n // This assert should be valid, but it's expensive (can dominate perf testing) so don't actually do it.\n //assert(oldChild.equals(newChild), 'Old and new snapshots should be equal.');\n return snap;\n }\n }\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, oldChild));\n }\n else {\n util_1.assert(snap.isLeafNode(), 'A child remove without an old child only makes sense on a leaf node');\n }\n }\n else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, newChild));\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, newChild, oldChild));\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n }\n else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(key, childNode));\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (oldSnap.hasChild(key)) {\n var oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(Change_1.Change.childChangedChange(key, childNode, oldChild));\n }\n }\n else {\n optChangeAccumulator.trackChildChange(Change_1.Change.childAddedChange(key, childNode));\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n if (oldSnap.isEmpty()) {\n return ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n else {\n return oldSnap.updatePriority(newPriority);\n }\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.filtersNodes = function () {\n return false;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndexedFilter = function () {\n return this;\n };\n /**\n * @inheritDoc\n */\n IndexedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n return IndexedFilter;\n}());\nexports.IndexedFilter = IndexedFilter;\n\n//# sourceMappingURL=IndexedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/IndexedFilter.js\n// module id = 24\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar StatsCollection_1 = require(\"./StatsCollection\");\nvar StatsManager = /** @class */ (function () {\n function StatsManager() {\n }\n StatsManager.getCollection = function (repoInfo) {\n var hashString = repoInfo.toString();\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection_1.StatsCollection();\n }\n return this.collections_[hashString];\n };\n StatsManager.getOrCreateReporter = function (repoInfo, creatorFunction) {\n var hashString = repoInfo.toString();\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n return this.reporters_[hashString];\n };\n StatsManager.collections_ = {};\n StatsManager.reporters_ = {};\n return StatsManager;\n}());\nexports.StatsManager = StatsManager;\n\n//# sourceMappingURL=StatsManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsManager.js\n// module id = 25\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Repo_1 = require(\"./Repo\");\nvar util_2 = require(\"./util/util\");\nvar parser_1 = require(\"./util/libs/parser\");\nvar validation_1 = require(\"./util/validation\");\nrequire(\"./Repo_transaction\");\n/** @const {string} */\nvar DATABASE_URL_OPTION = 'databaseURL';\nvar _staticInstance;\n/**\n * Creates and caches Repo instances.\n */\nvar RepoManager = /** @class */ (function () {\n function RepoManager() {\n /**\n * @private {!Object.>}\n */\n this.repos_ = {};\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n this.useRestClient_ = false;\n }\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n };\n // TODO(koss): Remove these functions unless used in tests?\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\n * This function should only ever be called to CREATE a new database instance.\n *\n * @param {!FirebaseApp} app\n * @return {!Database}\n */\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n util_2.fatal(\"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.intializeApp().');\n }\n var parsedUrl = parser_1.parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validation_1.validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n util_2.fatal('Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).');\n }\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util_1.safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || util_1.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n util_2.fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\n * Ensures a repo doesn't already exist and then creates one using the\n * provided app.\n *\n * @param {!RepoInfo} repoInfo The metadata about the Repo\n * @param {!FirebaseApp} app\n * @return {!Repo} The Repo object for the specified server / repoName.\n */\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util_1.safeGet(this.repos_, app.name);\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n var repo = util_1.safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n util_2.fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n repo = new Repo_1.Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n return RepoManager;\n}());\nexports.RepoManager = RepoManager;\n\n//# sourceMappingURL=RepoManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoManager.js\n// module id = 26\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar parser_1 = require(\"../core/util/libs/parser\");\nvar Path_1 = require(\"../core/util/Path\");\nvar Reference_1 = require(\"./Reference\");\nvar Repo_1 = require(\"../core/Repo\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar util_2 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nvar Database = /** @class */ (function () {\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n function Database(repo_) {\n this.repo_ = repo_;\n if (!(repo_ instanceof Repo_1.Repo)) {\n util_1.fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n this.root_ = new Reference_1.Reference(repo_, Path_1.Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n Object.defineProperty(Database.prototype, \"app\", {\n get: function () {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Returns a reference to the root or the path specified in opt_pathString.\n * @param {string=} pathString\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.ref = function (pathString) {\n this.checkDeleted_('ref');\n util_2.validateArgCount('database.ref', 0, 1, arguments.length);\n return pathString !== undefined ? this.root_.child(pathString) : this.root_;\n };\n /**\n * Returns a reference to the root or the path specified in url.\n * We throw a exception if the url is not in the same domain as the\n * current repo.\n * @param {string} url\n * @return {!Reference} Firebase reference.\n */\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util_2.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parser_1.parseRepoInfo(url);\n validation_1.validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n util_1.fatal(apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n this.repo_.repoInfo_.host +\n ')');\n }\n return this.ref(parsedURL.path.toString());\n };\n /**\n * @param {string} apiName\n */\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n util_1.fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n };\n // Make individual repo go offline.\n Database.prototype.goOffline = function () {\n util_2.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n Database.prototype.goOnline = function () {\n util_2.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}());\nexports.Database = Database;\nvar DatabaseInternals = /** @class */ (function () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n DatabaseInternals.prototype.delete = function () {\n this.database.checkDeleted_('delete');\n RepoManager_1.RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return Promise.resolve();\n };\n return DatabaseInternals;\n}());\nexports.DatabaseInternals = DatabaseInternals;\n\n//# sourceMappingURL=Database.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Database.js\n// module id = 32\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../Path\");\nvar RepoInfo_1 = require(\"../../RepoInfo\");\nvar util_1 = require(\"../util\");\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString) {\n var pathStringDecoded = '';\n var pieces = pathString.split('/');\n for (var i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n var piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n }\n catch (e) { }\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexports.parseRepoInfo = function (dataURL) {\n var parsedUrl = exports.parseURL(dataURL), namespace = parsedUrl.subdomain;\n if (parsedUrl.domain === 'firebase') {\n util_1.fatal(parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead');\n }\n // Catch common error of uninitialized namespace value.\n if (!namespace || namespace == 'undefined') {\n util_1.fatal('Cannot parse Firebase url. Please use https://.firebaseio.com');\n }\n if (!parsedUrl.secure) {\n util_1.warnIfPageIsSecure();\n }\n var webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n return {\n repoInfo: new RepoInfo_1.RepoInfo(parsedUrl.host, parsedUrl.secure, namespace, webSocketOnly),\n path: new Path_1.Path(parsedUrl.pathString)\n };\n};\n/**\n *\n * @param {!string} dataURL\n * @return {{host: string, port: number, domain: string, subdomain: string, secure: boolean, scheme: string, pathString: string}}\n */\nexports.parseURL = function (dataURL) {\n // Default to empty strings in the event of a malformed string.\n var host = '', domain = '', subdomain = '', pathString = '';\n // Always default to SSL, unless otherwise specified.\n var secure = true, scheme = 'https', port = 443;\n // Don't do any validation here. The caller is responsible for validating the result of parsing.\n if (typeof dataURL === 'string') {\n // Parse scheme.\n var colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n // Parse host and path.\n var slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n host = dataURL.substring(0, slashInd);\n pathString = decodePath(dataURL.substring(slashInd));\n var parts = host.split('.');\n if (parts.length === 3) {\n // Normalize namespaces to lowercase to share storage / connection.\n domain = parts[1];\n subdomain = parts[0].toLowerCase();\n }\n else if (parts.length === 2) {\n domain = parts[0];\n }\n // If we have a port, use scheme for determining if it's secure.\n colonInd = host.indexOf(':');\n if (colonInd >= 0) {\n secure = scheme === 'https' || scheme === 'wss';\n port = parseInt(host.substring(colonInd + 1), 10);\n }\n }\n return {\n host: host,\n port: port,\n domain: domain,\n subdomain: subdomain,\n secure: secure,\n scheme: scheme,\n pathString: pathString\n };\n};\n\n//# sourceMappingURL=parser.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/libs/parser.js\n// module id = 33\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar storage_1 = require(\"./storage/storage\");\nvar Constants_1 = require(\"../realtime/Constants\");\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nvar RepoInfo = /** @class */ (function () {\n /**\n * @param {string} host Hostname portion of the url for the repo\n * @param {boolean} secure Whether or not this repo is accessed over ssl\n * @param {string} namespace The namespace represented by the repo\n * @param {boolean} webSocketOnly Whether to prefer websockets over all other transports (used by Nest).\n * @param {string=} persistenceKey Override the default session persistence storage key\n */\n function RepoInfo(host, secure, namespace, webSocketOnly, persistenceKey) {\n if (persistenceKey === void 0) { persistenceKey = ''; }\n this.secure = secure;\n this.namespace = namespace;\n this.webSocketOnly = webSocketOnly;\n this.persistenceKey = persistenceKey;\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = storage_1.PersistentStorage.get('host:' + host) || this.host;\n }\n RepoInfo.prototype.needsQueryParam = function () {\n return this.host !== this.internalHost;\n };\n RepoInfo.prototype.isCacheableHost = function () {\n return this.internalHost.substr(0, 2) === 's-';\n };\n RepoInfo.prototype.isDemoHost = function () {\n return this.domain === 'firebaseio-demo.com';\n };\n RepoInfo.prototype.isCustomHost = function () {\n return (this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com');\n };\n RepoInfo.prototype.updateHost = function (newHost) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n storage_1.PersistentStorage.set('host:' + this.host, this.internalHost);\n }\n }\n };\n /**\n * Returns the websocket URL for this repo\n * @param {string} type of connection\n * @param {Object} params list\n * @return {string} The URL for this repo\n */\n RepoInfo.prototype.connectionURL = function (type, params) {\n util_1.assert(typeof type === 'string', 'typeof type must == string');\n util_1.assert(typeof params === 'object', 'typeof params must == object');\n var connURL;\n if (type === Constants_1.WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n }\n else if (type === Constants_1.LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n }\n else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n var pairs = [];\n util_2.forEach(params, function (key, value) {\n pairs.push(key + '=' + value);\n });\n return connURL + pairs.join('&');\n };\n /** @return {string} */\n RepoInfo.prototype.toString = function () {\n var str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n };\n /** @return {string} */\n RepoInfo.prototype.toURLString = function () {\n return (this.secure ? 'https://' : 'http://') + this.host;\n };\n return RepoInfo;\n}());\nexports.RepoInfo = RepoInfo;\n\n//# sourceMappingURL=RepoInfo.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/RepoInfo.js\n// module id = 34\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_2 = require(\"../core/util/util\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar OnDisconnect = /** @class */ (function () {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n function OnDisconnect(repo_, path_) {\n this.repo_ = repo_;\n this.path_ = path_;\n }\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.cancel = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n util_1.validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectCancel(this.path_, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.remove = function (onComplete) {\n util_1.validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.remove', this.path_);\n util_1.validateCallback('OnDisconnect.remove', 1, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.set = function (value, onComplete) {\n util_1.validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.set', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n util_1.validateCallback('OnDisconnect.set', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSet(this.path_, value, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.setWithPriority = function (value, priority, onComplete) {\n util_1.validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validation_1.validateFirebaseDataArg('OnDisconnect.setWithPriority', 1, value, this.path_, false);\n validation_1.validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n util_1.validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectSetWithPriority(this.path_, value, priority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n OnDisconnect.prototype.update = function (objectToMerge, onComplete) {\n util_1.validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validation_1.validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n util_2.warn('Passing an Array to firebase.database.onDisconnect().update() is deprecated. Use set() if you want to overwrite the ' +\n 'existing data, or an Object with integer keys if you really do want to only update some of the children.');\n }\n validation_1.validateFirebaseMergeDataArg('OnDisconnect.update', 1, objectToMerge, this.path_, false);\n util_1.validateCallback('OnDisconnect.update', 2, onComplete, true);\n var deferred = new util_3.Deferred();\n this.repo_.onDisconnectUpdate(this.path_, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n return OnDisconnect;\n}());\nexports.OnDisconnect = OnDisconnect;\n\n//# sourceMappingURL=onDisconnect.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/onDisconnect.js\n// module id = 35\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar KeyIndex_1 = require(\"../core/snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../core/snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../core/snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../core/snap/indexes/PathIndex\");\nvar util_2 = require(\"../core/util/util\");\nvar Path_1 = require(\"../core/util/Path\");\nvar validation_1 = require(\"../core/util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar EventRegistration_1 = require(\"../core/view/EventRegistration\");\nvar util_4 = require(\"@firebase/util\");\nvar __referenceConstructor;\n/**\n * A Query represents a filter to be applied to a firebase location. This object purely represents the\n * query expression (and exposes our public API to build the query). The actual query logic is in ViewBase.js.\n *\n * Since every Firebase reference is a query, Firebase inherits from this object.\n */\nvar Query = /** @class */ (function () {\n function Query(repo, path, queryParams_, orderByCalled_) {\n this.repo = repo;\n this.path = path;\n this.queryParams_ = queryParams_;\n this.orderByCalled_ = orderByCalled_;\n }\n Object.defineProperty(Query, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n Query.validateQueryEndpoints_ = function (params) {\n var startNode = null;\n var endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n if (params.getIndex() === KeyIndex_1.KEY_INDEX) {\n var tooManyArgsError = 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n var wrongArgTypeError = 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n if (startName != util_2.MIN_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n if (endName != util_2.MAX_NAME) {\n throw new Error(tooManyArgsError);\n }\n else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n }\n else if (params.getIndex() === PriorityIndex_1.PRIORITY_INDEX) {\n if ((startNode != null && !validation_1.isValidPriority(startNode)) ||\n (endNode != null && !validation_1.isValidPriority(endNode))) {\n throw new Error('Query: When ordering by priority, the first argument passed to startAt(), ' +\n 'endAt(), or equalTo() must be a valid priority value (null, a number, or a string).');\n }\n }\n else {\n util_1.assert(params.getIndex() instanceof PathIndex_1.PathIndex ||\n params.getIndex() === ValueIndex_1.VALUE_INDEX, 'unknown index type.');\n if ((startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')) {\n throw new Error('Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.');\n }\n }\n };\n /**\n * Validates that limit* has been called with the correct combination of parameters\n * @param {!QueryParams} params\n * @private\n */\n Query.validateLimit_ = function (params) {\n if (params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()) {\n throw new Error(\"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\");\n }\n };\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n Query.prototype.validateNoPreviousOrderByCall_ = function (fnName) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n };\n /**\n * @return {!QueryParams}\n */\n Query.prototype.getQueryParams = function () {\n return this.queryParams_;\n };\n /**\n * @return {!Reference}\n */\n Query.prototype.getRef = function () {\n util_3.validateArgCount('Query.ref', 0, 0, arguments.length);\n // This is a slight hack. We cannot goog.require('fb.api.Firebase'), since Firebase requires fb.api.Query.\n // However, we will always export 'Firebase' to the global namespace, so it's guaranteed to exist by the time this\n // method gets called.\n return new Query.__referenceConstructor(this.repo, this.path);\n };\n /**\n * @param {!string} eventType\n * @param {!function(DataSnapshot, string=)} callback\n * @param {(function(Error)|Object)=} cancelCallbackOrContext\n * @param {Object=} context\n * @return {!function(DataSnapshot, string=)}\n */\n Query.prototype.on = function (eventType, callback, cancelCallbackOrContext, context) {\n util_3.validateArgCount('Query.on', 2, 4, arguments.length);\n validation_1.validateEventType('Query.on', 1, eventType, false);\n util_3.validateCallback('Query.on', 2, callback, false);\n var ret = Query.getCancelAndContextArgs_('Query.on', cancelCallbackOrContext, context);\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n }\n else {\n var callbacks = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n };\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onValueEvent = function (callback, cancelCallback, context) {\n var container = new EventRegistration_1.ValueEventRegistration(callback, cancelCallback || null, context || null);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n Query.prototype.onChildEvent = function (callbacks, cancelCallback, context) {\n var container = new EventRegistration_1.ChildEventRegistration(callbacks, cancelCallback, context);\n this.repo.addEventCallbackForQuery(this, container);\n };\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n Query.prototype.off = function (eventType, callback, context) {\n util_3.validateArgCount('Query.off', 0, 3, arguments.length);\n validation_1.validateEventType('Query.off', 1, eventType, true);\n util_3.validateCallback('Query.off', 2, callback, true);\n util_3.validateContextObject('Query.off', 3, context, true);\n var container = null;\n var callbacks = null;\n if (eventType === 'value') {\n var valueCallback = callback || null;\n container = new EventRegistration_1.ValueEventRegistration(valueCallback, null, context || null);\n }\n else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new EventRegistration_1.ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n };\n /**\n * Attaches a listener, waits for the first event, and then removes the listener\n * @param {!string} eventType\n * @param {!function(!DataSnapshot, string=)} userCallback\n * @param cancelOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n Query.prototype.once = function (eventType, userCallback, cancelOrContext, context) {\n var _this = this;\n util_3.validateArgCount('Query.once', 1, 4, arguments.length);\n validation_1.validateEventType('Query.once', 1, eventType, false);\n util_3.validateCallback('Query.once', 2, userCallback, true);\n var ret = Query.getCancelAndContextArgs_('Query.once', cancelOrContext, context);\n // TODO: Implement this more efficiently (in particular, use 'get' wire protocol for 'value' event)\n // TODO: consider actually wiring the callbacks into the promise. We cannot do this without a breaking change\n // because the API currently expects callbacks will be called synchronously if the data is cached, but this is\n // against the Promise specification.\n var firstCall = true;\n var deferred = new util_4.Deferred();\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(function () { });\n var onceCallback = function (snapshot) {\n // NOTE: Even though we unsubscribe, we may get called multiple times if a single action (e.g. set() with JSON)\n // triggers multiple events (e.g. child_added or child_changed).\n if (firstCall) {\n firstCall = false;\n _this.off(eventType, onceCallback);\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n this.on(eventType, onceCallback, \n /*cancel=*/ function (err) {\n _this.off(eventType, onceCallback);\n if (ret.cancel)\n ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n });\n return deferred.promise;\n };\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToFirst = function (limit) {\n util_3.validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToFirst: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToFirst(limit), this.orderByCalled_);\n };\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n Query.prototype.limitToLast = function (limit) {\n util_3.validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0) {\n throw new Error('Query.limitToLast: First argument must be a positive integer.');\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error('Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).');\n }\n return new Query(this.repo, this.path, this.queryParams_.limitToLast(limit), this.orderByCalled_);\n };\n /**\n * Given a child path, return a new query ordered by the specified grandchild path.\n * @param {!string} path\n * @return {!Query}\n */\n Query.prototype.orderByChild = function (path) {\n util_3.validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error('Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.');\n }\n else if (path === '$priority') {\n throw new Error('Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.');\n }\n else if (path === '$value') {\n throw new Error('Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.');\n }\n validation_1.validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n var parsedPath = new Path_1.Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error('Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.');\n }\n var index = new PathIndex_1.PathIndex(parsedPath);\n var newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n Query.prototype.orderByKey = function () {\n util_3.validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n var newParams = this.queryParams_.orderBy(KeyIndex_1.KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n Query.prototype.orderByPriority = function () {\n util_3.validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n var newParams = this.queryParams_.orderBy(PriorityIndex_1.PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n Query.prototype.orderByValue = function () {\n util_3.validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n var newParams = this.queryParams_.orderBy(ValueIndex_1.VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.startAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.startAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validation_1.validateKey('Query.startAt', 2, name, true);\n var newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).');\n }\n // Calling with no params tells us to start at the beginning.\n if (value === undefined) {\n value = null;\n name = null;\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n Query.prototype.endAt = function (value, name) {\n if (value === void 0) { value = null; }\n util_3.validateArgCount('Query.endAt', 0, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validation_1.validateKey('Query.endAt', 2, name, true);\n var newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n };\n /**\n * Load the selection of children with exactly the specified value, and, optionally,\n * the specified name.\n * @param {number|string|boolean|null} value\n * @param {string=} name\n * @return {!Query}\n */\n Query.prototype.equalTo = function (value, name) {\n util_3.validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validation_1.validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validation_1.validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error('Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).');\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error('Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).');\n }\n return this.startAt(value, name).endAt(value, name);\n };\n /**\n * @return {!string} URL for this location.\n */\n Query.prototype.toString = function () {\n util_3.validateArgCount('Query.toString', 0, 0, arguments.length);\n return this.repo.toString() + this.path.toUrlEncodedString();\n };\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n Query.prototype.toJSON = function () {\n // An optional spacer argument is unnecessary for a string.\n util_3.validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n };\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n Query.prototype.queryObject = function () {\n return this.queryParams_.getQueryObject();\n };\n /**\n * @return {!string}\n */\n Query.prototype.queryIdentifier = function () {\n var obj = this.queryObject();\n var id = util_2.ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n };\n /**\n * Return true if this query and the provided query are equivalent; otherwise, return false.\n * @param {Query} other\n * @return {boolean}\n */\n Query.prototype.isEqual = function (other) {\n util_3.validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n var error = 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n var sameRepo = this.repo === other.repo;\n var samePath = this.path.equals(other.path);\n var sameQueryIdentifier = this.queryIdentifier() === other.queryIdentifier();\n return sameRepo && samePath && sameQueryIdentifier;\n };\n /**\n * Helper used by .on and .once to extract the context and or cancel arguments.\n * @param {!string} fnName The function name (on or once)\n * @param {(function(Error)|Object)=} cancelOrContext\n * @param {Object=} context\n * @return {{cancel: ?function(Error), context: ?Object}}\n * @private\n */\n Query.getCancelAndContextArgs_ = function (fnName, cancelOrContext, context) {\n var ret = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext;\n util_3.validateCallback(fnName, 3, ret.cancel, true);\n ret.context = context;\n util_3.validateContextObject(fnName, 4, ret.context, true);\n }\n else if (cancelOrContext) {\n // we have either a cancel callback or a context.\n if (typeof cancelOrContext === 'object' && cancelOrContext !== null) {\n // it's a context!\n ret.context = cancelOrContext;\n }\n else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n }\n else {\n throw new Error(util_3.errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.');\n }\n }\n return ret;\n };\n Object.defineProperty(Query.prototype, \"ref\", {\n get: function () {\n return this.getRef();\n },\n enumerable: true,\n configurable: true\n });\n return Query;\n}());\nexports.Query = Query;\n\n//# sourceMappingURL=Query.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/Query.js\n// module id = 36\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar MAX_NODE;\nfunction setMaxNode(val) {\n MAX_NODE = val;\n}\nexports.setMaxNode = setMaxNode;\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexports.priorityHashText = function (priority) {\n if (typeof priority === 'number')\n return 'number:' + util_2.doubleToIEEE754String(priority);\n else\n return 'string:' + priority;\n};\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexports.validatePriorityNode = function (priorityNode) {\n if (priorityNode.isLeafNode()) {\n var val = priorityNode.val();\n util_1.assert(typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && util_3.contains(val, '.sv')), 'Priority must be a string or number.');\n }\n else {\n util_1.assert(priorityNode === MAX_NODE || priorityNode.isEmpty(), 'priority of unexpected type.');\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n util_1.assert(priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(), \"Priority nodes can't have a priority of their own.\");\n};\n\n//# sourceMappingURL=snap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/snap.js\n// module id = 37\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Index_1 = require(\"./Index\");\nvar Node_1 = require(\"../Node\");\nvar util_1 = require(\"../../util/util\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nvar ValueIndex = /** @class */ (function (_super) {\n __extends(ValueIndex, _super);\n function ValueIndex() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.compare = function (a, b) {\n var indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return util_1.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.isDefinedOn = function (node) {\n return true;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.indexedValueChanged = function (oldNode, newNode) {\n return !oldNode.equals(newNode);\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.minPost = function () {\n return Node_1.NamedNode.MIN;\n };\n /**\n * @inheritDoc\n */\n ValueIndex.prototype.maxPost = function () {\n return Node_1.NamedNode.MAX;\n };\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n ValueIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n return new Node_1.NamedNode(name, valueNode);\n };\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n ValueIndex.prototype.toString = function () {\n return '.value';\n };\n return ValueIndex;\n}(Index_1.Index));\nexports.ValueIndex = ValueIndex;\nexports.VALUE_INDEX = new ValueIndex();\n\n//# sourceMappingURL=ValueIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/ValueIndex.js\n// module id = 38\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar childSet_1 = require(\"./childSet\");\nvar util_2 = require(\"@firebase/util\");\nvar Node_1 = require(\"./Node\");\nvar PriorityIndex_1 = require(\"./indexes/PriorityIndex\");\nvar KeyIndex_1 = require(\"./indexes/KeyIndex\");\nvar _defaultIndexMap;\nvar fallbackObject = {};\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nvar IndexMap = /** @class */ (function () {\n function IndexMap(indexes_, indexSet_) {\n this.indexes_ = indexes_;\n this.indexSet_ = indexSet_;\n }\n Object.defineProperty(IndexMap, \"Default\", {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n get: function () {\n util_1.assert(fallbackObject && PriorityIndex_1.PRIORITY_INDEX, 'ChildrenNode.ts has not been loaded');\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap({ '.priority': fallbackObject }, { '.priority': PriorityIndex_1.PRIORITY_INDEX });\n return _defaultIndexMap;\n },\n enumerable: true,\n configurable: true\n });\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n IndexMap.prototype.get = function (indexKey) {\n var sortedMap = util_2.safeGet(this.indexes_, indexKey);\n if (!sortedMap)\n throw new Error('No index defined for ' + indexKey);\n if (sortedMap === fallbackObject) {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n else {\n return sortedMap;\n }\n };\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n IndexMap.prototype.hasIndex = function (indexDefinition) {\n return util_2.contains(this.indexSet_, indexDefinition.toString());\n };\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addIndex = function (indexDefinition, existingChildren) {\n util_1.assert(indexDefinition !== KeyIndex_1.KEY_INDEX, \"KeyIndex always exists and isn't meant to be added to the IndexMap.\");\n var childList = [];\n var sawIndexedValue = false;\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n var newIndex;\n if (sawIndexedValue) {\n newIndex = childSet_1.buildChildSet(childList, indexDefinition.getCompare());\n }\n else {\n newIndex = fallbackObject;\n }\n var indexName = indexDefinition.toString();\n var newIndexSet = util_2.clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n var newIndexes = util_2.clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n };\n /**\n * Ensure that this node is properly tracked in any indexes that we're maintaining\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.addToIndexes = function (namedNode, existingChildren) {\n var _this = this;\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren, indexName) {\n var index = util_2.safeGet(_this.indexSet_, indexName);\n util_1.assert(index, 'Missing index implementation for ' + indexName);\n if (indexedChildren === fallbackObject) {\n // Check to see if we need to index everything\n if (index.isDefinedOn(namedNode.node)) {\n // We need to build this index\n var childList = [];\n var iter = existingChildren.getIterator(Node_1.NamedNode.Wrap);\n var next = iter.getNext();\n while (next) {\n if (next.name != namedNode.name) {\n childList.push(next);\n }\n next = iter.getNext();\n }\n childList.push(namedNode);\n return childSet_1.buildChildSet(childList, index.getCompare());\n }\n else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n var newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n /**\n * Create a new IndexMap instance with the given value removed\n * @param {!NamedNode} namedNode\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n IndexMap.prototype.removeFromIndexes = function (namedNode, existingChildren) {\n var newIndexes = util_2.map(this.indexes_, function (indexedChildren) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n }\n else {\n var existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(new Node_1.NamedNode(namedNode.name, existingSnap));\n }\n else {\n // No record of this child\n return indexedChildren;\n }\n }\n });\n return new IndexMap(newIndexes, this.indexSet_);\n };\n return IndexMap;\n}());\nexports.IndexMap = IndexMap;\n\n//# sourceMappingURL=IndexMap.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/IndexMap.js\n// module id = 39\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar SortedMap_1 = require(\"../util/SortedMap\");\nvar SortedMap_2 = require(\"../util/SortedMap\");\nvar LOG_2 = Math.log(2);\n/**\n * @constructor\n */\nvar Base12Num = /** @class */ (function () {\n /**\n * @param {number} length\n */\n function Base12Num(length) {\n var logBase2 = function (num) {\n return parseInt((Math.log(num) / LOG_2), 10);\n };\n var bitMask = function (bits) { return parseInt(Array(bits + 1).join('1'), 2); };\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n var mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n /**\n * @return {boolean}\n */\n Base12Num.prototype.nextBitIsOne = function () {\n //noinspection JSBitwiseOperatorUsage\n var result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n };\n return Base12Num;\n}());\n/**\n * Takes a list of child nodes and constructs a SortedSet using the given comparison\n * function\n *\n * Uses the algorithm described in the paper linked here:\n * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.46.1458\n *\n * @template K, V\n * @param {Array.} childList Unsorted list of children\n * @param {function(!NamedNode, !NamedNode):number} cmp The comparison method to be used\n * @param {(function(NamedNode):K)=} keyFn An optional function to extract K from a node wrapper, if K's\n * type is not NamedNode\n * @param {(function(K, K):number)=} mapSortFn An optional override for comparator used by the generated sorted map\n * @return {SortedMap.}\n */\nexports.buildChildSet = function (childList, cmp, keyFn, mapSortFn) {\n childList.sort(cmp);\n var buildBalancedTree = function (low, high) {\n var length = high - low;\n var namedNode;\n var key;\n if (length == 0) {\n return null;\n }\n else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, null, null);\n }\n else {\n var middle = parseInt((length / 2), 10) + low;\n var left = buildBalancedTree(low, middle);\n var right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : namedNode;\n return new SortedMap_1.LLRBNode(key, namedNode.node, SortedMap_1.LLRBNode.BLACK, left, right);\n }\n };\n var buildFrom12Array = function (base12) {\n var node = null;\n var root = null;\n var index = childList.length;\n var buildPennant = function (chunkSize, color) {\n var low = index - chunkSize;\n var high = index;\n index -= chunkSize;\n var childTree = buildBalancedTree(low + 1, high);\n var namedNode = childList[low];\n var key = keyFn ? keyFn(namedNode) : namedNode;\n attachPennant(new SortedMap_1.LLRBNode(key, namedNode.node, color, null, childTree));\n };\n var attachPennant = function (pennant) {\n if (node) {\n node.left = pennant;\n node = pennant;\n }\n else {\n root = pennant;\n node = pennant;\n }\n };\n for (var i = 0; i < base12.count; ++i) {\n var isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n var chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n }\n else {\n // current == 2\n buildPennant(chunkSize, SortedMap_1.LLRBNode.BLACK);\n buildPennant(chunkSize, SortedMap_1.LLRBNode.RED);\n }\n }\n return root;\n };\n var base12 = new Base12Num(childList.length);\n var root = buildFrom12Array(base12);\n return new SortedMap_2.SortedMap(mapSortFn || cmp, root);\n};\n\n//# sourceMappingURL=childSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/childSet.js\n// module id = 40\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\nfunction NAME_ONLY_COMPARATOR(left, right) {\n return util_1.nameCompare(left.name, right.name);\n}\nexports.NAME_ONLY_COMPARATOR = NAME_ONLY_COMPARATOR;\nfunction NAME_COMPARATOR(left, right) {\n return util_1.nameCompare(left, right);\n}\nexports.NAME_COMPARATOR = NAME_COMPARATOR;\n\n//# sourceMappingURL=comparators.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/comparators.js\n// module id = 41\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../../util/util\");\nvar Index_1 = require(\"./Index\");\nvar ChildrenNode_1 = require(\"../ChildrenNode\");\nvar Node_1 = require(\"../Node\");\nvar nodeFromJSON_1 = require(\"../nodeFromJSON\");\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nvar PathIndex = /** @class */ (function (_super) {\n __extends(PathIndex, _super);\n function PathIndex(indexPath_) {\n var _this = _super.call(this) || this;\n _this.indexPath_ = indexPath_;\n util_1.assert(!indexPath_.isEmpty() && indexPath_.getFront() !== '.priority', \"Can't create PathIndex with empty path or .priority key\");\n return _this;\n }\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n PathIndex.prototype.extractChild = function (snap) {\n return snap.getChild(this.indexPath_);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.isDefinedOn = function (node) {\n return !node.getChild(this.indexPath_).isEmpty();\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.compare = function (a, b) {\n var aChild = this.extractChild(a.node);\n var bChild = this.extractChild(b.node);\n var indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return util_2.nameCompare(a.name, b.name);\n }\n else {\n return indexCmp;\n }\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.makePost = function (indexValue, name) {\n var valueNode = nodeFromJSON_1.nodeFromJSON(indexValue);\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);\n return new Node_1.NamedNode(name, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.maxPost = function () {\n var node = ChildrenNode_1.ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, ChildrenNode_1.MAX_NODE);\n return new Node_1.NamedNode(util_2.MAX_NAME, node);\n };\n /**\n * @inheritDoc\n */\n PathIndex.prototype.toString = function () {\n return this.indexPath_.slice().join('/');\n };\n return PathIndex;\n}(Index_1.Index));\nexports.PathIndex = PathIndex;\n\n//# sourceMappingURL=PathIndex.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/snap/indexes/PathIndex.js\n// module id = 42\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar SparseSnapshotTree_1 = require(\"../SparseSnapshotTree\");\nvar LeafNode_1 = require(\"../snap/LeafNode\");\nvar nodeFromJSON_1 = require(\"../snap/nodeFromJSON\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexports.generateWithValues = function (values) {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\n/**\n * Value to use when firing local events. When writing server values, fire\n * local events with an approximate value, otherwise return value as-is.\n * @param {(Object|string|number|boolean)} value\n * @param {!Object} serverValues\n * @return {!(string|number|boolean)}\n */\nexports.resolveDeferredValue = function (value, serverValues) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n else {\n util_1.assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\n};\n/**\n * Recursively replace all deferred values and priorities in the tree with the\n * specified generated replacement values.\n * @param {!SparseSnapshotTree} tree\n * @param {!Object} serverValues\n * @return {!SparseSnapshotTree}\n */\nexports.resolveDeferredValueTree = function (tree, serverValues) {\n var resolvedTree = new SparseSnapshotTree_1.SparseSnapshotTree();\n tree.forEachTree(new Path_1.Path(''), function (path, node) {\n resolvedTree.remember(path, exports.resolveDeferredValueSnapshot(node, serverValues));\n });\n return resolvedTree;\n};\n/**\n * Recursively replace all deferred values and priorities in the node with the\n * specified generated replacement values. If there are no server values in the node,\n * it'll be returned as-is.\n * @param {!Node} node\n * @param {!Object} serverValues\n * @return {!Node}\n */\nexports.resolveDeferredValueSnapshot = function (node, serverValues) {\n var rawPri = node.getPriority().val();\n var priority = exports.resolveDeferredValue(rawPri, serverValues);\n var newNode;\n if (node.isLeafNode()) {\n var leafNode = node;\n var value = exports.resolveDeferredValue(leafNode.getValue(), serverValues);\n if (value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()) {\n return new LeafNode_1.LeafNode(value, nodeFromJSON_1.nodeFromJSON(priority));\n }\n else {\n return node;\n }\n }\n else {\n var childrenNode = node;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode_1.LeafNode(priority));\n }\n childrenNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var newChildNode = exports.resolveDeferredValueSnapshot(childNode, serverValues);\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n//# sourceMappingURL=ServerValues.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/ServerValues.js\n// module id = 43\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"./util/Path\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar CountedSet_1 = require(\"./util/CountedSet\");\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nvar SparseSnapshotTree = /** @class */ (function () {\n function SparseSnapshotTree() {\n /**\n * @private\n * @type {Node}\n */\n this.value_ = null;\n /**\n * @private\n * @type {CountedSet}\n */\n this.children_ = null;\n }\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {?Node} The retrieved node, or null.\n */\n SparseSnapshotTree.prototype.find = function (path) {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n }\n else if (!path.isEmpty() && this.children_ != null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var childTree = this.children_.get(childKey);\n return childTree.find(path);\n }\n else {\n return null;\n }\n }\n else {\n return null;\n }\n };\n /**\n * Stores the given node at the specified path. If there is already a node\n * at a shallower path, it merges the new data into that snapshot node.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @param {!Node} data The new data, or null.\n */\n SparseSnapshotTree.prototype.remember = function (path, data) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n }\n else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n }\n else {\n if (this.children_ == null) {\n this.children_ = new CountedSet_1.CountedSet();\n }\n var childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n var child = this.children_.get(childKey);\n path = path.popFront();\n child.remember(path, data);\n }\n };\n /**\n * Purge the data at path from the cache.\n *\n * @param {!Path} path Path to look up snapshot for.\n * @return {boolean} True if this node should now be removed.\n */\n SparseSnapshotTree.prototype.forget = function (path) {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\n }\n else {\n if (this.value_ !== null) {\n if (this.value_.isLeafNode()) {\n // We're trying to forget a node that doesn't exist\n return false;\n }\n else {\n var value = this.value_;\n this.value_ = null;\n var self_1 = this;\n value.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, tree) {\n self_1.remember(new Path_1.Path(key), tree);\n });\n return this.forget(path);\n }\n }\n else if (this.children_ !== null) {\n var childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n var safeToRemove = this.children_.get(childKey).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n }\n else {\n return false;\n }\n }\n else {\n return true;\n }\n }\n };\n /**\n * Recursively iterates through all of the stored tree and calls the\n * callback on each one.\n *\n * @param {!Path} prefixPath Path to look up node for.\n * @param {!Function} func The function to invoke for each tree.\n */\n SparseSnapshotTree.prototype.forEachTree = function (prefixPath, func) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n }\n else {\n this.forEachChild(function (key, tree) {\n var path = new Path_1.Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\n }\n };\n /**\n * Iterates through each immediate child and triggers the callback.\n *\n * @param {!Function} func The function to invoke for each child.\n */\n SparseSnapshotTree.prototype.forEachChild = function (func) {\n if (this.children_ !== null) {\n this.children_.each(function (key, tree) {\n func(key, tree);\n });\n }\n };\n return SparseSnapshotTree;\n}());\nexports.SparseSnapshotTree = SparseSnapshotTree;\n\n//# sourceMappingURL=SparseSnapshotTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SparseSnapshotTree.js\n// module id = 44\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nvar CountedSet = /** @class */ (function () {\n function CountedSet() {\n this.set = {};\n }\n /**\n * @param {!K} item\n * @param {V} val\n */\n CountedSet.prototype.add = function (item, val) {\n this.set[item] = val !== null ? val : true;\n };\n /**\n * @param {!K} key\n * @return {boolean}\n */\n CountedSet.prototype.contains = function (key) {\n return util_1.contains(this.set, key);\n };\n /**\n * @param {!K} item\n * @return {V}\n */\n CountedSet.prototype.get = function (item) {\n return this.contains(item) ? this.set[item] : undefined;\n };\n /**\n * @param {!K} item\n */\n CountedSet.prototype.remove = function (item) {\n delete this.set[item];\n };\n /**\n * Deletes everything in the set\n */\n CountedSet.prototype.clear = function () {\n this.set = {};\n };\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n CountedSet.prototype.isEmpty = function () {\n return util_1.isEmpty(this.set);\n };\n /**\n * @return {number} The number of items in the set\n */\n CountedSet.prototype.count = function () {\n return util_1.getCount(this.set);\n };\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n CountedSet.prototype.each = function (fn) {\n util_1.forEach(this.set, function (k, v) { return fn(k, v); });\n };\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n CountedSet.prototype.keys = function () {\n var keys = [];\n util_1.forEach(this.set, function (k) {\n keys.push(k);\n });\n return keys;\n };\n return CountedSet;\n}());\nexports.CountedSet = CountedSet;\n\n//# sourceMappingURL=CountedSet.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/CountedSet.js\n// module id = 45\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Path_1 = require(\"../util/Path\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nvar Overwrite = /** @class */ (function () {\n function Overwrite(source, path, snap) {\n this.source = source;\n this.path = path;\n this.snap = snap;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.OVERWRITE;\n }\n Overwrite.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new Overwrite(this.source, Path_1.Path.Empty, this.snap.getImmediateChild(childName));\n }\n else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n };\n return Overwrite;\n}());\nexports.Overwrite = Overwrite;\n\n//# sourceMappingURL=Overwrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Overwrite.js\n// module id = 46\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./view/CacheNode\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar ViewCache_1 = require(\"./view/ViewCache\");\nvar View_1 = require(\"./view/View\");\nvar __referenceConstructor;\n/**\n * SyncPoint represents a single location in a SyncTree with 1 or more event registrations, meaning we need to\n * maintain 1 or more Views at this location to cache server data and raise appropriate events for server changes\n * and user writes (set, transaction, update).\n *\n * It's responsible for:\n * - Maintaining the set of 1 or more views necessary at this location (a SyncPoint with 0 views should be removed).\n * - Proxying user / server operations to the views as appropriate (i.e. applyServerOverwrite,\n * applyUserOverwrite, etc.)\n */\nvar SyncPoint = /** @class */ (function () {\n function SyncPoint() {\n /**\n * The Views being tracked at this location in the tree, stored as a map where the key is a\n * queryId and the value is the View for that query.\n *\n * NOTE: This list will be quite small (usually 1, but perhaps 2 or 3; any more is an odd use case).\n *\n * @type {!Object.}\n * @private\n */\n this.views_ = {};\n }\n Object.defineProperty(SyncPoint, \"__referenceConstructor\", {\n get: function () {\n util_1.assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n },\n set: function (val) {\n util_1.assert(!__referenceConstructor, '__referenceConstructor has already been defined');\n __referenceConstructor = val;\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.isEmpty = function () {\n return util_2.isEmpty(this.views_);\n };\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n SyncPoint.prototype.applyOperation = function (operation, writesCache, optCompleteServerCache) {\n var queryId = operation.source.queryId;\n if (queryId !== null) {\n var view = util_2.safeGet(this.views_, queryId);\n util_1.assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(operation, writesCache, optCompleteServerCache);\n }\n else {\n var events_1 = [];\n util_2.forEach(this.views_, function (key, view) {\n events_1 = events_1.concat(view.applyOperation(operation, writesCache, optCompleteServerCache));\n });\n return events_1;\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache Complete server cache, if we have it.\n * @param {boolean} serverCacheComplete\n * @return {!Array.} Events to raise.\n */\n SyncPoint.prototype.addEventRegistration = function (query, eventRegistration, writesCache, serverCache, serverCacheComplete) {\n var queryId = query.queryIdentifier();\n var view = util_2.safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n var eventCache = writesCache.calcCompleteEventCache(serverCacheComplete ? serverCache : null);\n var eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n }\n else if (serverCache instanceof ChildrenNode_1.ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n }\n else {\n eventCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n var viewCache = new ViewCache_1.ViewCache(new CacheNode_1.CacheNode(\n /** @type {!Node} */ (eventCache), eventCacheComplete, false), new CacheNode_1.CacheNode(\n /** @type {!Node} */ (serverCache), serverCacheComplete, false));\n view = new View_1.View(query, viewCache);\n this.views_[queryId] = view;\n }\n // This is guaranteed to exist now, we just created anything that was missing\n view.addEventRegistration(eventRegistration);\n return view.getInitialEvents(eventRegistration);\n };\n /**\n * Remove event callback(s). Return cancelEvents if a cancelError is specified.\n *\n * If query is the default query, we'll check all views for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified view(s).\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {{removed:!Array., events:!Array.}} removed queries and any cancel events\n */\n SyncPoint.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var queryId = query.queryIdentifier();\n var removed = [];\n var cancelEvents = [];\n var hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n var self_1 = this;\n util_2.forEach(this.views_, function (viewQueryId, view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete self_1.views_[viewQueryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n }\n else {\n // remove the callback from the specific view.\n var view = util_2.safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(view.removeEventRegistration(eventRegistration, cancelError));\n if (view.isEmpty()) {\n delete this.views_[queryId];\n // We'll deal with complete views later.\n if (!view\n .getQuery()\n .getQueryParams()\n .loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(new SyncPoint.__referenceConstructor(query.repo, query.path));\n }\n return { removed: removed, events: cancelEvents };\n };\n /**\n * @return {!Array.}\n */\n SyncPoint.prototype.getQueryViews = function () {\n var _this = this;\n var values = Object.keys(this.views_).map(function (key) { return _this.views_[key]; });\n return values.filter(function (view) {\n return !view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n };\n /**\n *\n * @param {!Path} path The path to the desired complete snapshot\n * @return {?Node} A complete cache, if it exists\n */\n SyncPoint.prototype.getCompleteServerCache = function (path) {\n var serverCache = null;\n util_2.forEach(this.views_, function (key, view) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n };\n /**\n * @param {!Query} query\n * @return {?View}\n */\n SyncPoint.prototype.viewForQuery = function (query) {\n var params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n }\n else {\n var queryId = query.queryIdentifier();\n return util_2.safeGet(this.views_, queryId);\n }\n };\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n SyncPoint.prototype.viewExistsForQuery = function (query) {\n return this.viewForQuery(query) != null;\n };\n /**\n * @return {boolean}\n */\n SyncPoint.prototype.hasCompleteView = function () {\n return this.getCompleteView() != null;\n };\n /**\n * @return {?View}\n */\n SyncPoint.prototype.getCompleteView = function () {\n var completeView = util_2.findValue(this.views_, function (view) {\n return view\n .getQuery()\n .getQueryParams()\n .loadsAllData();\n });\n return completeView || null;\n };\n return SyncPoint;\n}());\nexports.SyncPoint = SyncPoint;\n\n//# sourceMappingURL=SyncPoint.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncPoint.js\n// module id = 47\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * Stores the data we have cached for a view.\n *\n * serverSnap is the cached server data, eventSnap is the cached event data (server data plus any local writes).\n *\n * @constructor\n */\nvar ViewCache = /** @class */ (function () {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n function ViewCache(eventCache_, serverCache_) {\n this.eventCache_ = eventCache_;\n this.serverCache_ = serverCache_;\n }\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateEventSnap = function (eventSnap, complete, filtered) {\n return new ViewCache(new CacheNode_1.CacheNode(eventSnap, complete, filtered), this.serverCache_);\n };\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n ViewCache.prototype.updateServerSnap = function (serverSnap, complete, filtered) {\n return new ViewCache(this.eventCache_, new CacheNode_1.CacheNode(serverSnap, complete, filtered));\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getEventCache = function () {\n return this.eventCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteEventSnap = function () {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n };\n /**\n * @return {!CacheNode}\n */\n ViewCache.prototype.getServerCache = function () {\n return this.serverCache_;\n };\n /**\n * @return {?Node}\n */\n ViewCache.prototype.getCompleteServerSnap = function () {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n };\n /**\n * @const\n * @type {ViewCache}\n */\n ViewCache.Empty = new ViewCache(new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false), new CacheNode_1.CacheNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, \n /*fullyInitialized=*/ false, \n /*filtered=*/ false));\n return ViewCache;\n}());\nexports.ViewCache = ViewCache;\n\n//# sourceMappingURL=ViewCache.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewCache.js\n// module id = 48\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nvar StatsListener = /** @class */ (function () {\n function StatsListener(collection_) {\n this.collection_ = collection_;\n this.last_ = null;\n }\n StatsListener.prototype.get = function () {\n var newStats = this.collection_.get();\n var delta = util_1.clone(newStats);\n if (this.last_) {\n util_1.forEach(this.last_, function (stat, value) {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n return delta;\n };\n return StatsListener;\n}());\nexports.StatsListener = StatsListener;\n\n//# sourceMappingURL=StatsListener.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsListener.js\n// module id = 49\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"./util/util\");\nvar Path_1 = require(\"./util/Path\");\nvar VisibilityMonitor_1 = require(\"./util/VisibilityMonitor\");\nvar OnlineMonitor_1 = require(\"./util/OnlineMonitor\");\nvar util_5 = require(\"@firebase/util\");\nvar Connection_1 = require(\"../realtime/Connection\");\nvar util_6 = require(\"@firebase/util\");\nvar util_7 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\n *\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\n * in quotes to make sure the closure compiler does not minify them.\n */\nvar PersistentConnection = /** @class */ (function (_super) {\n __extends(PersistentConnection, _super);\n /**\n * @implements {ServerActions}\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param onConnectStatus_\n * @param onServerInfoUpdate_\n * @param authTokenProvider_\n * @param authOverride_\n */\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_;\n // Used for diagnostic logging.\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = util_4.logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n _this.visible_ = false;\n // Before we get connected, we keep a queue of pending messages to send.\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n _this.realtime_ = null;\n /** @private {string|null} */\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n if (authOverride_ && !util_7.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n _this.scheduleConnect_(0);\n VisibilityMonitor_1.VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor_1.OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n return _this;\n }\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = { r: curReqNum, a: action, b: body };\n this.log_(util_2.stringify(msg));\n util_3.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util_3.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'q';\n // Only bother to send query if it's non-default.\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n req['h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message['d'];\n var status = message['s'];\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId];\n // only trigger actions if the listen hasn't been removed and readded\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util_1.contains(payload, 'w')) {\n var warnings = util_1.safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\n var indexPath = query.path.toString();\n util_4.warn(\"Using an unspecified index. Your data will be downloaded and \" +\n (\"filtered on the client. Consider adding \" + indexSpec + \" at \") +\n (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\n }\n else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () { });\n }\n }\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\n * @param {!string} credential\n * @private\n */\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || util_5.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\n * a auth revoked (the connection is closed).\n */\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util_5.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = { cred: token_1 };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n }\n else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res['s'];\n var data = res['d'] || 'error';\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n }\n else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util_3.assert(query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = { /*path*/ p: pathString };\n var action = 'n';\n // Only bother sending queryId if it's non-default.\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n this.sendRequest(action, req);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n }\n else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response['s'], response['d']);\n }, Math.floor(0));\n }\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n if (hash !== undefined)\n request['h'] = hash;\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n if (this.connected_) {\n this.sendPut_(index);\n }\n else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--;\n // Clean up array occasionally.\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n if (onComplete)\n onComplete(message['s'], message['d']);\n });\n };\n /**\n * @inheritDoc\n */\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this;\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n var request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n this.sendRequest(/*stats*/ 's', request, function (result) {\n var status = result['s'];\n if (status !== 'ok') {\n var errorReason = result['d'];\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\n * @param {*} message\n * @private\n */\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util_2.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message['b']);\n }\n }\n else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n }\n else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge*/ false, body['t']);\n else if (action === 'm')\n this.onDataUpdate_(body['p'], body['d'], \n /*isMerge=*/ true, body['t']);\n else if (action === 'c')\n this.onListenRevoked_(body['p'], body['q']);\n else if (action === 'ac')\n this.onAuthRevoked_(body['s'], body['d']);\n else if (action === 'sd')\n this.onSecurityDebugPacket_(body);\n else\n util_4.error('Unrecognized action received from server: ' +\n util_2.stringify(action) +\n '\\nAre you using the latest client?');\n };\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n util_3.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\n // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\n * @param {boolean} visible\n * @private\n */\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n };\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n }\n else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n this.onConnectStatus_(false);\n };\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n var closeFn_1 = function () {\n if (connection_1) {\n connection_1.close();\n }\n else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n var sendRequestFn = function (msg) {\n util_3.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n // First fetch auth token, and establish connection after fetching the token was successful\n this.authTokenProvider_\n .getToken(forceRefresh)\n .then(function (result) {\n if (!canceled_1) {\n util_4.log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection_1.Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1, \n /* onKill= */ function (reason) {\n util_4.warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n }\n else {\n util_4.log('getToken() completed but was canceled');\n }\n })\n .then(null, function (error) {\n self_1.log_('Failed to get token: ' + error);\n if (!canceled_1) {\n if (util_6.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n util_4.warn(error);\n }\n closeFn_1();\n }\n });\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.interrupt = function (reason) {\n util_4.log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\n }\n else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\n * @param {string} reason\n */\n PersistentConnection.prototype.resume = function (reason) {\n util_4.log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (util_1.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n };\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete)\n put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0)\n this.outstandingPuts_ = [];\n };\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n if (!query) {\n queryId = 'default';\n }\n else {\n queryId = query.map(function (q) { return util_4.ObjectToUniqueKey(q); }).join('$');\n }\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete)\n listen.onComplete('permission_denied');\n };\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path_1.Path(pathString).toString(); // normalize path.\n var listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (util_1.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n }\n else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n };\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n util_4.log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n // Notify the auth token provider that the token is invalid, which will log\n // a warning\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n }\n else {\n if ('msg' in body && typeof console !== 'undefined') {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this;\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n util_1.forEach(this.listens_, function (pathString, queries) {\n util_1.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i])\n this.sendPut_(i);\n }\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\n * Sends client stats for first connection\n * @private\n */\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n if (util_6.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n }\n else if (util_6.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n stats['sdk.' + clientName + '.' + app_1.default.SDK_VERSION.replace(/\\./g, '-')] = 1;\n if (util_7.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n }\n else if (util_7.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n };\n /**\n * @return {boolean}\n * @private\n */\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor_1.OnlineMonitor.getInstance().currentlyOnline();\n return util_1.isEmpty(this.interruptReasons_) && online;\n };\n /**\n * @private\n */\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions_1.ServerActions));\nexports.PersistentConnection = PersistentConnection;\n\n//# sourceMappingURL=PersistentConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/PersistentConnection.js\n// module id = 50\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Base class to be used if you want to emit events. Call the constructor with\n * the set of allowed event names.\n */\nvar EventEmitter = /** @class */ (function () {\n /**\n * @param {!Array.} allowedEvents_\n */\n function EventEmitter(allowedEvents_) {\n this.allowedEvents_ = allowedEvents_;\n this.listeners_ = {};\n util_1.assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, 'Requires a non-empty array');\n }\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n EventEmitter.prototype.trigger = function (eventType) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n var listeners = this.listeners_[eventType].slice();\n for (var i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n };\n EventEmitter.prototype.on = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback: callback, context: context });\n var eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n };\n EventEmitter.prototype.off = function (eventType, callback, context) {\n this.validateEventType_(eventType);\n var listeners = this.listeners_[eventType] || [];\n for (var i = 0; i < listeners.length; i++) {\n if (listeners[i].callback === callback &&\n (!context || context === listeners[i].context)) {\n listeners.splice(i, 1);\n return;\n }\n }\n };\n EventEmitter.prototype.validateEventType_ = function (eventType) {\n util_1.assert(this.allowedEvents_.find(function (et) {\n return et === eventType;\n }), 'Unknown event: ' + eventType);\n };\n return EventEmitter;\n}());\nexports.EventEmitter = EventEmitter;\n\n//# sourceMappingURL=EventEmitter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/EventEmitter.js\n// module id = 51\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar Constants_1 = require(\"./Constants\");\nvar TransportManager_1 = require(\"./TransportManager\");\n// Abort upgrade attempt if it takes longer than 60s.\nvar UPGRADE_TIMEOUT = 60000;\n// For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\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)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\n * Creates a new real-time connection to the server using whichever method works\n * best in the current browser.\n *\n * @constructor\n */\nvar Connection = /** @class */ (function () {\n /**\n * @param {!string} id - an id for this connection\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0 /* CONNECTING */;\n this.log_ = util_1.logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager_1.TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\n * Starts a connection attempt\n * @private\n */\n Connection.prototype.start_ = function () {\n var _this = this;\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\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.\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\n * still have the context of your originating frame.\n */\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = util_1.setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n if (!_this.isHealthy_) {\n if (_this.conn_ &&\n _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' +\n _this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.');\n _this.isHealthy_ = true;\n _this.conn_.markConnectionHealthy();\n }\n else if (_this.conn_ &&\n _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' +\n _this.conn_.bytesSent +\n ' bytes. Leaving connection alive.');\n // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n }\n else {\n _this.log_('Closing unhealthy connection after timeout.');\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\n * @return {!string}\n * @private\n */\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n }\n else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n _this.onSecondaryConnectionLost_();\n }\n else {\n _this.log_('closing an old connection');\n }\n };\n };\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n return function (message) {\n if (_this.state_ != 2 /* DISCONNECTED */) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n }\n else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n }\n else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n };\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n };\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n }\n else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close();\n // If we were already using this connection for something, than we need to fully close\n if (this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_) {\n this.close();\n }\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n }\n else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n }\n else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n }\n else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start();\n // send ack\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({ t: 'c', d: { t: SWITCH_ACK, d: {} } });\n // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n this.log_('Ending transmission on primary');\n this.conn_.send({ t: 'c', d: { t: END_TRANSMISSION, d: {} } });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = util_1.requireKey('t', parsedData);\n var data = util_1.requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n }\n else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_();\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n };\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = util_1.requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n }\n else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n }\n else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n }\n else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n }\n else if (cmd === CONTROL_ERROR) {\n util_1.error('Server Error: ' + payload);\n }\n else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n }\n else {\n util_1.error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host);\n // if we've already closed the connection, then don't bother trying to progress further\n if (this.state_ == 0 /* CONNECTING */) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (Constants_1.PROTOCOL_VERSION !== version) {\n util_1.warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n };\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId);\n // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n this.secondaryResponsesRequired_ =\n conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n util_1.setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host);\n // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n if (this.state_ === 1 /* CONNECTED */) {\n this.close();\n }\n else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1 /* CONNECTED */;\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\n // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n }\n else {\n util_1.setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1 /* CONNECTED */) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n };\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\n *\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\n * we should flush the host cache\n * @private\n */\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null;\n // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n if (!everConnected && this.state_ === 0 /* CONNECTING */) {\n this.log_('Realtime connection failed.');\n // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n if (this.repoInfo_.isCacheableHost()) {\n storage_1.PersistentStorage.remove('host:' + this.repoInfo_.host);\n // reset the internal host to what we would show the user, i.e. .firebaseio.com\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n }\n else if (this.state_ === 1 /* CONNECTED */) {\n this.log_('Realtime connection lost.');\n }\n this.close();\n };\n /**\n *\n * @param {string} reason\n * @private\n */\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\n // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n this.onDisconnect_ = null;\n this.close();\n };\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1 /* CONNECTED */) {\n throw 'Connection is not connected';\n }\n else {\n this.tx_.send(data);\n }\n };\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n Connection.prototype.close = function () {\n if (this.state_ !== 2 /* DISCONNECTED */) {\n this.log_('Closing realtime connection.');\n this.state_ = 2 /* DISCONNECTED */;\n this.closeConnections_();\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n *\n * @private\n */\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n return Connection;\n}());\nexports.Connection = Connection;\n\n//# sourceMappingURL=Connection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/Connection.js\n// module id = 52\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../core/util/util\");\nvar CountedSet_1 = require(\"../core/util/CountedSet\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar PacketReceiver_1 = require(\"./polling/PacketReceiver\");\nvar Constants_1 = require(\"./Constants\");\nvar util_2 = require(\"@firebase/util\");\nvar util_3 = require(\"@firebase/util\");\n// URL query parameters associated with longpolling\nexports.FIREBASE_LONGPOLL_START_PARAM = 'start';\nexports.FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexports.FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexports.FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexports.FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexports.FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexports.FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexports.FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n//Data size constants.\n//TODO: Perf: the maximum length actually differs from browser to browser.\n// We should check what browser we're on and set accordingly.\nvar MAX_URL_DATA_SIZE = 1870;\nvar SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nvar MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n/**\n * Keepalive period\n * send a fresh request at minimum every 25 seconds. Opera has a maximum request\n * length of 30 seconds that we can't exceed.\n * @const\n * @type {number}\n */\nvar KEEPALIVE_REQUEST_INTERVAL = 25000;\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nvar LP_CONNECT_TIMEOUT = 30000;\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nvar BrowserPollConnection = /** @class */ (function () {\n /**\n * @param {string} connId An identifier for this connection, used for logging\n * @param {RepoInfo} repoInfo The info for the endpoint to send data to.\n * @param {string=} transportSessionId Optional transportSessionid if we are reconnecting for an existing\n * transport session\n * @param {string=} lastSessionId Optional lastSessionId if the PersistentConnection has already created a\n * connection previously\n */\n function BrowserPollConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.repoInfo = repoInfo;\n this.transportSessionId = transportSessionId;\n this.lastSessionId = lastSessionId;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.everConnected_ = false;\n this.log_ = util_1.logWrapper(connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.urlFn = function (params) {\n return repoInfo.connectionURL(Constants_1.LONG_POLLING, params);\n };\n }\n /**\n *\n * @param {function(Object)} onMessage Callback when messages arrive\n * @param {function()} onDisconnect Callback with connection lost.\n */\n BrowserPollConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver_1.PacketReceiver(onMessage);\n this.isClosed_ = false;\n this.connectTimeoutTimer_ = setTimeout(function () {\n _this.log_('Timed out trying to connect.');\n // Make sure we clear the host cache\n _this.onClosed_();\n _this.connectTimeoutTimer_ = null;\n }, Math.floor(LP_CONNECT_TIMEOUT));\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n util_1.executeWhenDOMReady(function () {\n if (_this.isClosed_)\n return;\n //Set up a callback that gets triggered once a connection is set up.\n _this.scriptTagHolder = new FirebaseIFrameScriptHolder(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var command = args[0], arg1 = args[1], arg2 = args[2], arg3 = args[3], arg4 = args[4];\n _this.incrementIncomingBytes_(args);\n if (!_this.scriptTagHolder)\n return; // we closed the connection.\n if (_this.connectTimeoutTimer_) {\n clearTimeout(_this.connectTimeoutTimer_);\n _this.connectTimeoutTimer_ = null;\n }\n _this.everConnected_ = true;\n if (command == exports.FIREBASE_LONGPOLL_START_PARAM) {\n _this.id = arg1;\n _this.password = arg2;\n }\n else if (command === exports.FIREBASE_LONGPOLL_CLOSE_COMMAND) {\n // Don't clear the host cache. We got a response from the server, so we know it's reachable\n if (arg1) {\n // We aren't expecting any more data (other than what the server's already in the process of sending us\n // through our already open polls), so don't send any more.\n _this.scriptTagHolder.sendNewPolls = false;\n // arg1 in this case is the last response number sent by the server. We should try to receive\n // all of the responses up to this one before closing\n _this.myPacketOrderer.closeAfter(arg1, function () {\n _this.onClosed_();\n });\n }\n else {\n _this.onClosed_();\n }\n }\n else {\n throw new Error('Unrecognized command received: ' + command);\n }\n }, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var pN = args[0], data = args[1];\n _this.incrementIncomingBytes_(args);\n _this.myPacketOrderer.handleResponse(pN, data);\n }, function () {\n _this.onClosed_();\n }, _this.urlFn);\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 100000000);\n if (_this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[exports.FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = _this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (_this.transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = _this.transportSessionId;\n }\n if (_this.lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = _this.lastSessionId;\n }\n if (!util_3.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n var connectURL = _this.urlFn(urlParams);\n _this.log_('Connecting via long-poll to ' + connectURL);\n _this.scriptTagHolder.addTag(connectURL, function () {\n /* do nothing */\n });\n });\n };\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n BrowserPollConnection.prototype.start = function () {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n };\n /**\n * Forces long polling to be considered as a potential transport\n */\n BrowserPollConnection.forceAllow = function () {\n BrowserPollConnection.forceAllow_ = true;\n };\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n BrowserPollConnection.forceDisallow = function () {\n BrowserPollConnection.forceDisallow_ = true;\n };\n // Static method, use string literal so it can be accessed in a generic way\n BrowserPollConnection.isAvailable = function () {\n // NOTE: In React-Native there's normally no 'document', but if you debug a React-Native app in\n // the Chrome debugger, 'document' is defined, but document.createElement is null (2015/06/08).\n return (BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !util_1.isChromeExtensionContentScript() &&\n !util_1.isWindowsStoreApp() &&\n !util_3.isNodeSdk()));\n };\n /**\n * No-op for polling\n */\n BrowserPollConnection.prototype.markConnectionHealthy = function () { };\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n BrowserPollConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\n //remove the disconnect frame, which will trigger an XHR call to the server to tell it we're leaving.\n if (this.myDisconnFrame) {\n document.body.removeChild(this.myDisconnFrame);\n this.myDisconnFrame = null;\n }\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n };\n /**\n * Triggered when this transport is closed\n * @private\n */\n BrowserPollConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\n }\n };\n /**\n * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server\n * that we've left.\n */\n BrowserPollConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\n };\n /**\n * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then\n * broken into chunks (since URLs have a small maximum length).\n * @param {!Object} data The JSON data to transmit.\n */\n BrowserPollConnection.prototype.send = function (data) {\n var dataStr = util_2.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //first, lets get the base64-encoded data\n var base64data = util_2.base64Encode(dataStr);\n //We can only fit a certain amount in each URL, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_1.splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n //Enqueue each segment for transmission. We assign each chunk a sequential ID and a total number\n //of segments so that we can reassemble the packet on the server.\n for (var i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i]);\n this.curSegmentNum++;\n }\n };\n /**\n * This is how we notify the server that we're leaving.\n * We aren't able to send requests with DHTML on a window close event, but we can\n * trigger XHR requests in some browsers (everything but Opera basically).\n * @param {!string} id\n * @param {!string} pw\n */\n BrowserPollConnection.prototype.addDisconnectPingFrame = function (id, pw) {\n if (util_3.isNodeSdk())\n return;\n this.myDisconnFrame = document.createElement('iframe');\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n document.body.appendChild(this.myDisconnFrame);\n };\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n BrowserPollConnection.prototype.incrementIncomingBytes_ = function (args) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n var bytesReceived = util_2.stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n };\n return BrowserPollConnection;\n}());\nexports.BrowserPollConnection = BrowserPollConnection;\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nvar FirebaseIFrameScriptHolder = /** @class */ (function () {\n /**\n * @param commandCB - The callback to be called when control commands are recevied from the server.\n * @param onMessageCB - The callback to be triggered when responses arrive from the server.\n * @param onDisconnect - The callback to be triggered when this tag holder is closed\n * @param urlFn - A function that provides the URL of the endpoint to send data to.\n */\n function FirebaseIFrameScriptHolder(commandCB, onMessageCB, onDisconnect, urlFn) {\n this.onDisconnect = onDisconnect;\n this.urlFn = urlFn;\n //We maintain a count of all of the outstanding requests, because if we have too many active at once it can cause\n //problems in some browsers.\n /**\n * @type {CountedSet.}\n */\n this.outstandingRequests = new CountedSet_1.CountedSet();\n //A queue of the pending segments waiting for transmission to the server.\n this.pendingSegs = [];\n //A serial number. We use this for two things:\n // 1) A way to ensure the browser doesn't cache responses to polls\n // 2) A way to make the server aware when long-polls arrive in a different order than we started them. The\n // server needs to release both polls in this case or it will cause problems in Opera since Opera can only execute\n // JSONP code in the order it was added to the iframe.\n this.currentSerial = Math.floor(Math.random() * 100000000);\n // This gets set to false when we're \"closing down\" the connection (e.g. we're switching transports but there's still\n // incoming data from the server that we're waiting for).\n this.sendNewPolls = true;\n if (!util_3.isNodeSdk()) {\n //Each script holder registers a couple of uniquely named callbacks with the window. These are called from the\n //iframes where we put the long-polling script tags. We have two callbacks:\n // 1) Command Callback - Triggered for control issues, like starting a connection.\n // 2) Message Callback - Triggered when new data arrives.\n this.uniqueCallbackIdentifier = util_1.LUIDGenerator();\n window[exports.FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;\n window[exports.FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n // Set the iframe's contents.\n var script = '';\n // if we set a javascript url, it's IE and we need to set the document domain. The javascript url is sufficient\n // for ie9, but ie8 needs to do it again in the document itself.\n if (this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:') {\n var currentDomain = document.domain;\n script = '';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n }\n catch (e) {\n util_1.log('frame writing exception');\n if (e.stack) {\n util_1.log(e.stack);\n }\n util_1.log(e);\n }\n }\n else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\n * actually use.\n * @private\n * @return {Element}\n */\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none';\n // This is necessary in order to initialize the document inside the iframe\n if (document.body) {\n document.body.appendChild(iframe);\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n util_1.log('No IE domain setting required');\n }\n }\n catch (e) {\n var domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\n }\n }\n else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n }\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n }\n else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n }\n else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this;\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n if (util_3.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n }\n // Protect from being called recursively.\n var onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\n * @param {!string} id - The ID of this connection\n * @param {!string} pw - The password for this connection\n */\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n while (this.newRequest_()) { }\n };\n /**\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\n * too many outstanding requests and we are still alive.\n *\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\n * needed.\n */\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[exports.FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[exports.FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[exports.FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n var curDataString = '';\n var i = 0;\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n exports.FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n exports.FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n }\n else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n }\n else {\n return false;\n }\n };\n /**\n * Queue a packet for transmission to the server.\n * @param segnum - A sequential id for this packet segment used for reassembly\n * @param totalsegs - The total number of segments in this packet\n * @param data - The data for this segment.\n */\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\n * Add a script tag for a regular long-poll request.\n * @param {!string} url - The URL of the script tag.\n * @param {!number} serial - The serial number of the request.\n * @private\n */\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this;\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n var doNewRequest = function () {\n _this.outstandingRequests.remove(serial);\n _this.newRequest_();\n };\n // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n var readyStateCB = function () {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n this.addTag(url, readyStateCB);\n };\n /**\n * Add an arbitrary script tag to the iframe.\n * @param {!string} url - The URL for the script tag source.\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (util_3.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n }\n else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls)\n return;\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n loadCB();\n }\n };\n newScript_1.onerror = function () {\n util_1.log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n _this.close();\n };\n _this.myIFrame.doc.body.appendChild(newScript_1);\n }\n catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}());\nexports.FirebaseIFrameScriptHolder = FirebaseIFrameScriptHolder;\n\n//# sourceMappingURL=BrowserPollConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/BrowserPollConnection.js\n// module id = 53\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../core/util/util\");\nvar StatsManager_1 = require(\"../core/stats/StatsManager\");\nvar Constants_1 = require(\"./Constants\");\nvar util_3 = require(\"@firebase/util\");\nvar storage_1 = require(\"../core/storage/storage\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n}\nelse if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\nexports.setWebSocketImpl = setWebSocketImpl;\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nvar WebSocketConnection = /** @class */ (function () {\n /**\n * @param {string} connId identifier for this transport\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = util_2.logWrapper(this.connId);\n this.stats_ = StatsManager_1.StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\n * session\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\n * @return {string} connection url\n * @private\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[Constants_1.VERSION_PARAM] = Constants_1.PROTOCOL_VERSION;\n if (!util_5.isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(Constants_1.FORGE_DOMAIN) !== -1) {\n urlParams[Constants_1.REFERER_PARAM] = Constants_1.FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[Constants_1.TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[Constants_1.LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(Constants_1.WEBSOCKET, urlParams);\n };\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n storage_1.PersistentStorage.set('previous_websocket_failure', true);\n try {\n if (util_5.isNodeSdk()) {\n var device = util_3.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + Constants_1.PROTOCOL_VERSION + \"/\" + app_1.default.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n };\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n }\n else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n }\n catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n _this.everConnected_ = true;\n };\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n _this.mySock = null;\n _this.onClosed_();\n };\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n var error = e.message || e.data;\n if (error) {\n _this.log_(error);\n }\n _this.onClosed_();\n };\n };\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n WebSocketConnection.prototype.start = function () { };\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n return (!isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_);\n };\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return (storage_1.PersistentStorage.isInMemoryStorage ||\n storage_1.PersistentStorage.get('previous_websocket_failure') === true);\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n storage_1.PersistentStorage.remove('previous_websocket_failure');\n };\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util_4.jsonEval(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\n * @param {!String} data\n * @return {?String} Any remaining data to be process, or null if there is none\n * @private\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util_1.assert(this.frames === null, 'We already have a frame buffer');\n // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n if (data.length <= 6) {\n var frameCount = Number(data);\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null)\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n }\n else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util_4.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n var dataSegs = util_2.splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n //Send the actual data in segments.\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n // since this is an internal close, trigger the close listener\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\n * the last activity.\n */\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n }\n catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}());\nexports.WebSocketConnection = WebSocketConnection;\n\n//# sourceMappingURL=WebSocketConnection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/WebSocketConnection.js\n// module id = 54\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Interface defining the set of actions that can be performed against the Firebase server\n * (basically corresponds to our wire protocol).\n *\n * @interface\n */\nvar ServerActions = /** @class */ (function () {\n function ServerActions() {\n }\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) { };\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n ServerActions.prototype.refreshAuthToken = function (token) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) { };\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) { };\n /**\n * @param {Object.} stats\n */\n ServerActions.prototype.reportStats = function (stats) { };\n return ServerActions;\n}());\nexports.ServerActions = ServerActions;\n\n//# sourceMappingURL=ServerActions.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ServerActions.js\n// module id = 55\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./IndexedFilter\");\nvar PriorityIndex_1 = require(\"../../snap/indexes/PriorityIndex\");\nvar Node_1 = require(\"../../../core/snap/Node\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\n/**\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar RangedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter_1.IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\n * @return {!NamedNode}\n */\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n RangedFilter.prototype.matches = function (node) {\n return (this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n var filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new Node_1.NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\n * @inheritDoc\n */\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n }\n else {\n return params.getIndex().minPost();\n }\n };\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n }\n else {\n return params.getIndex().maxPost();\n }\n };\n return RangedFilter;\n}());\nexports.RangedFilter = RangedFilter;\n\n//# sourceMappingURL=RangedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/RangedFilter.js\n// module id = 56\n// module chunks = 0","/**\n * Copyright 2017 Google Inc.\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\nmodule.exports = require('@firebase/database');\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ./database/index.js\n// module id = 78\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar app_1 = require(\"@firebase/app\");\nvar Database_1 = require(\"./src/api/Database\");\nexports.Database = Database_1.Database;\nvar Query_1 = require(\"./src/api/Query\");\nexports.Query = Query_1.Query;\nvar Reference_1 = require(\"./src/api/Reference\");\nexports.Reference = Reference_1.Reference;\nvar util_1 = require(\"./src/core/util/util\");\nexports.enableLogging = util_1.enableLogging;\nvar RepoManager_1 = require(\"./src/core/RepoManager\");\nvar INTERNAL = require(\"./src/api/internal\");\nvar TEST_ACCESS = require(\"./src/api/test_access\");\nvar util_2 = require(\"@firebase/util\");\nvar ServerValue = Database_1.Database.ServerValue;\nexports.ServerValue = ServerValue;\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) { return RepoManager_1.RepoManager.getInstance().databaseFromApp(app, url); }, \n // firebase.database namespace properties\n {\n Reference: Reference_1.Reference,\n Query: Query_1.Query,\n Database: Database_1.Database,\n enableLogging: util_1.enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n if (util_2.isNodeSdk()) {\n module.exports = namespace;\n }\n}\nexports.registerDatabase = registerDatabase;\nregisterDatabase(app_1.default);\nvar DataSnapshot_1 = require(\"./src/api/DataSnapshot\");\nexports.DataSnapshot = DataSnapshot_1.DataSnapshot;\nvar onDisconnect_1 = require(\"./src/api/onDisconnect\");\nexports.OnDisconnect = onDisconnect_1.OnDisconnect;\n\n//# sourceMappingURL=index.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/index.js\n// module id = 79\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Wraps a DOM Storage object and:\n * - automatically encode objects as JSON strings before storing them to allow us to store arbitrary types.\n * - prefixes names with \"firebase:\" to avoid collisions with app data.\n *\n * We automatically (see storage.js) create two such wrappers, one for sessionStorage,\n * and one for localStorage.\n *\n * @constructor\n */\nvar DOMStorageWrapper = /** @class */ (function () {\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n function DOMStorageWrapper(domStorage_) {\n this.domStorage_ = domStorage_;\n // Use a prefix to avoid collisions with other stuff saved by the app.\n this.prefix_ = 'firebase:';\n }\n /**\n * @param {string} key The key to save the value under\n * @param {?Object} value The value being stored, or null to remove the key.\n */\n DOMStorageWrapper.prototype.set = function (key, value) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n else {\n this.domStorage_.setItem(this.prefixedName_(key), util_1.stringify(value));\n }\n };\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n DOMStorageWrapper.prototype.get = function (key) {\n var storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n }\n else {\n return util_1.jsonEval(storedVal);\n }\n };\n /**\n * @param {string} key\n */\n DOMStorageWrapper.prototype.remove = function (key) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n };\n /**\n * @param {string} name\n * @return {string}\n */\n DOMStorageWrapper.prototype.prefixedName_ = function (name) {\n return this.prefix_ + name;\n };\n DOMStorageWrapper.prototype.toString = function () {\n return this.domStorage_.toString();\n };\n return DOMStorageWrapper;\n}());\nexports.DOMStorageWrapper = DOMStorageWrapper;\n\n//# sourceMappingURL=DOMStorageWrapper.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/DOMStorageWrapper.js\n// module id = 80\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * An in-memory storage implementation that matches the API of DOMStorageWrapper\n * (TODO: create interface for both to implement).\n *\n * @constructor\n */\nvar MemoryStorage = /** @class */ (function () {\n function MemoryStorage() {\n this.cache_ = {};\n this.isInMemoryStorage = true;\n }\n MemoryStorage.prototype.set = function (key, value) {\n if (value == null) {\n delete this.cache_[key];\n }\n else {\n this.cache_[key] = value;\n }\n };\n MemoryStorage.prototype.get = function (key) {\n if (util_1.contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n };\n MemoryStorage.prototype.remove = function (key) {\n delete this.cache_[key];\n };\n return MemoryStorage;\n}());\nexports.MemoryStorage = MemoryStorage;\n\n//# sourceMappingURL=MemoryStorage.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/storage/MemoryStorage.js\n// module id = 81\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar TransactionResult = /** @class */ (function () {\n /**\n * A type for the resolve value of Firebase.transaction.\n * @constructor\n * @dict\n * @param {boolean} committed\n * @param {DataSnapshot} snapshot\n */\n function TransactionResult(committed, snapshot) {\n this.committed = committed;\n this.snapshot = snapshot;\n }\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n TransactionResult.prototype.toJSON = function () {\n util_1.validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n };\n return TransactionResult;\n}());\nexports.TransactionResult = TransactionResult;\n\n//# sourceMappingURL=TransactionResult.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/TransactionResult.js\n// module id = 82\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Fancy ID generator that creates 20-character string identifiers with the\n * following properties:\n *\n * 1. They're based on timestamp so that they sort *after* any existing ids.\n * 2. They contain 72-bits of random data after the timestamp so that IDs won't\n * collide with other clients' IDs.\n * 3. They sort *lexicographically* (so the timestamp is converted to characters\n * that will sort properly).\n * 4. They're monotonically increasing. Even if you generate more than one in\n * the same timestamp, the latter ones will sort after the former ones. We do\n * this by using the previous random bits but \"incrementing\" them by 1 (only\n * in the case of a timestamp collision).\n */\nexports.nextPushId = (function () {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n var PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n var lastPushTime = 0;\n // We generate 72-bits of randomness which get turned into 12 characters and\n // appended to the timestamp to prevent collisions with other clients. We\n // store the last characters we generated because in the event of a collision,\n // we'll use those same characters except \"incremented\" by one.\n var lastRandChars = [];\n return function (now) {\n var duplicateTime = now === lastPushTime;\n lastPushTime = now;\n var i;\n var timeStampChars = new Array(8);\n for (i = 7; i >= 0; i--) {\n timeStampChars[i] = PUSH_CHARS.charAt(now % 64);\n // NOTE: Can't use << here because javascript will convert to int and lose\n // the upper bits.\n now = Math.floor(now / 64);\n }\n util_1.assert(now === 0, 'Cannot push at time == 0');\n var id = timeStampChars.join('');\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\n }\n }\n else {\n // If the timestamp hasn't changed since last push, use the same random\n // number, except incremented by 1.\n for (i = 11; i >= 0 && lastRandChars[i] === 63; i--) {\n lastRandChars[i] = 0;\n }\n lastRandChars[i]++;\n }\n for (i = 0; i < 12; i++) {\n id += PUSH_CHARS.charAt(lastRandChars[i]);\n }\n util_1.assert(id.length === 20, 'nextPushId: Length should be 20.');\n return id;\n };\n})();\n\n//# sourceMappingURL=NextPushId.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/NextPushId.js\n// module id = 83\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar DataSnapshot_1 = require(\"../../api/DataSnapshot\");\nvar Event_1 = require(\"./Event\");\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Represents registration for 'value' events.\n */\nvar ValueEventRegistration = /** @class */ (function () {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n function ValueEventRegistration(callback_, cancelCallback_, context_) {\n this.callback_ = callback_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.respondsTo = function (eventType) {\n return eventType === 'value';\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createEvent = function (change, query) {\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent('value', this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, query.getRef(), index));\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_1 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_1.call(ctx, eventData.error);\n };\n }\n else {\n var cb_1 = this.callback_;\n return function () {\n cb_1.call(ctx, eventData.snapshot);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.matches = function (other) {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n }\n else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n }\n else {\n return (other.callback_ === this.callback_ && other.context_ === this.context_);\n }\n };\n /**\n * @inheritDoc\n */\n ValueEventRegistration.prototype.hasAnyCallback = function () {\n return this.callback_ !== null;\n };\n return ValueEventRegistration;\n}());\nexports.ValueEventRegistration = ValueEventRegistration;\n/**\n * Represents the registration of 1 or more child_xxx events.\n *\n * Currently, it is always exactly 1 child_xxx event, but the idea is we might let you\n * register a group of callbacks together in the future.\n *\n * @constructor\n * @implements {EventRegistration}\n */\nvar ChildEventRegistration = /** @class */ (function () {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n function ChildEventRegistration(callbacks_, cancelCallback_, context_) {\n this.callbacks_ = callbacks_;\n this.cancelCallback_ = cancelCallback_;\n this.context_ = context_;\n }\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.respondsTo = function (eventType) {\n var eventToCheck = eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return util_1.contains(this.callbacks_, eventToCheck);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createCancelEvent = function (error, path) {\n if (this.cancelCallback_) {\n return new Event_1.CancelEvent(this, error, path);\n }\n else {\n return null;\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.createEvent = function (change, query) {\n util_2.assert(change.childName != null, 'Child events should have a childName.');\n var ref = query.getRef().child(/** @type {!string} */ (change.childName));\n var index = query.getQueryParams().getIndex();\n return new Event_1.DataEvent(change.type, this, new DataSnapshot_1.DataSnapshot(change.snapshotNode, ref, index), change.prevName);\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.getEventRunner = function (eventData) {\n var ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n util_2.assert(this.cancelCallback_, 'Raising a cancel event on a listener with no cancel callback');\n var cancelCB_2 = this.cancelCallback_;\n return function () {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB_2.call(ctx, eventData.error);\n };\n }\n else {\n var cb_2 = this.callbacks_[eventData.eventType];\n return function () {\n cb_2.call(ctx, eventData.snapshot, eventData.prevName);\n };\n }\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.matches = function (other) {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n }\n else if (this.context_ === other.context_) {\n var otherCount = util_1.getCount(other.callbacks_);\n var thisCount = util_1.getCount(this.callbacks_);\n if (otherCount === thisCount) {\n // If count is 1, do an exact match on eventType, if either is defined but null, it's a match.\n // If event types don't match, not a match\n // If count is not 1, exact match across all\n if (otherCount === 1) {\n var otherKey /** @type {!string} */ = util_1.getAnyKey(other.callbacks_);\n var thisKey /** @type {!string} */ = util_1.getAnyKey(this.callbacks_);\n return (thisKey === otherKey &&\n (!other.callbacks_[otherKey] ||\n !this.callbacks_[thisKey] ||\n other.callbacks_[otherKey] === this.callbacks_[thisKey]));\n }\n else {\n // Exact match on each key.\n return util_1.every(this.callbacks_, function (eventType, cb) { return other.callbacks_[eventType] === cb; });\n }\n }\n }\n }\n return false;\n };\n /**\n * @inheritDoc\n */\n ChildEventRegistration.prototype.hasAnyCallback = function () {\n return this.callbacks_ !== null;\n };\n return ChildEventRegistration;\n}());\nexports.ChildEventRegistration = ChildEventRegistration;\n\n//# sourceMappingURL=EventRegistration.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventRegistration.js\n// module id = 84\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nvar DataEvent = /** @class */ (function () {\n /**\n * @param {!string} eventType One of: value, child_added, child_changed, child_moved, child_removed\n * @param {!EventRegistration} eventRegistration The function to call to with the event data. User provided\n * @param {!DataSnapshot} snapshot The data backing the event\n * @param {?string=} prevName Optional, the name of the previous child for child_* events.\n */\n function DataEvent(eventType, eventRegistration, snapshot, prevName) {\n this.eventType = eventType;\n this.eventRegistration = eventRegistration;\n this.snapshot = snapshot;\n this.prevName = prevName;\n }\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getPath = function () {\n var ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n }\n else {\n return ref.getParent().path;\n }\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventType = function () {\n return this.eventType;\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n DataEvent.prototype.toString = function () {\n return (this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n util_1.stringify(this.snapshot.exportVal()));\n };\n return DataEvent;\n}());\nexports.DataEvent = DataEvent;\nvar CancelEvent = /** @class */ (function () {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n function CancelEvent(eventRegistration, error, path) {\n this.eventRegistration = eventRegistration;\n this.error = error;\n this.path = path;\n }\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getPath = function () {\n return this.path;\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventType = function () {\n return 'cancel';\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.getEventRunner = function () {\n return this.eventRegistration.getEventRunner(this);\n };\n /**\n * @inheritDoc\n */\n CancelEvent.prototype.toString = function () {\n return this.path.toString() + ':cancel';\n };\n return CancelEvent;\n}());\nexports.CancelEvent = CancelEvent;\n\n//# sourceMappingURL=Event.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/Event.js\n// module id = 85\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar AckUserWrite_1 = require(\"./operation/AckUserWrite\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar util_3 = require(\"@firebase/util\");\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar ListenComplete_1 = require(\"./operation/ListenComplete\");\nvar Merge_1 = require(\"./operation/Merge\");\nvar Operation_1 = require(\"./operation/Operation\");\nvar Overwrite_1 = require(\"./operation/Overwrite\");\nvar Path_1 = require(\"./util/Path\");\nvar SyncPoint_1 = require(\"./SyncPoint\");\nvar WriteTree_1 = require(\"./WriteTree\");\n/**\n * SyncTree is the central class for managing event callback registration, data caching, views\n * (query processing), and event generation. There are typically two SyncTree instances for\n * each Repo, one for the normal Firebase data, and one for the .info data.\n *\n * It has a number of responsibilities, including:\n * - Tracking all user event callbacks (registered via addEventRegistration() and removeEventRegistration()).\n * - Applying and caching data changes for user set(), transaction(), and update() calls\n * (applyUserOverwrite(), applyUserMerge()).\n * - Applying and caching data changes for server data changes (applyServerOverwrite(),\n * applyServerMerge()).\n * - Generating user-facing events for server and user changes (all of the apply* methods\n * return the set of events that need to be raised as a result).\n * - Maintaining the appropriate set of server listens to ensure we are always subscribed\n * to the correct set of paths and queries to satisfy the current set of user event\n * callbacks (listens are started/stopped using the provided listenProvider).\n *\n * NOTE: Although SyncTree tracks event callbacks and calculates events to raise, the actual\n * events are returned to the caller rather than raised synchronously.\n *\n * @constructor\n */\nvar SyncTree = /** @class */ (function () {\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n function SyncTree(listenProvider_) {\n this.listenProvider_ = listenProvider_;\n /**\n * Tree of SyncPoints. There's a SyncPoint at any location that has 1 or more views.\n * @type {!ImmutableTree.}\n * @private\n */\n this.syncPointTree_ = ImmutableTree_1.ImmutableTree.Empty;\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n * @type {!WriteTree}\n * @private\n */\n this.pendingWriteTree_ = new WriteTree_1.WriteTree();\n this.tagToQueryMap_ = {};\n this.queryToTagMap_ = {};\n }\n /**\n * Apply the data changes for a user-generated set() or transaction() call.\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @param {number} writeId\n * @param {boolean=} visible\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserOverwrite = function (path, newData, writeId, visible) {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n if (!visible) {\n return [];\n }\n else {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.User, path, newData));\n }\n };\n /**\n * Apply the data from a user-generated update() call\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyUserMerge = function (path, changedChildren, writeId) {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.User, path, changeTree));\n };\n /**\n * Acknowledge a pending user write that was previously registered with applyUserOverwrite() or applyUserMerge().\n *\n * @param {!number} writeId\n * @param {boolean=} revert True if the given write failed and needs to be reverted\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.ackUserWrite = function (writeId, revert) {\n if (revert === void 0) { revert = false; }\n var write = this.pendingWriteTree_.getWrite(writeId);\n var needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n }\n else {\n var affectedTree_1 = ImmutableTree_1.ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree_1 = affectedTree_1.set(Path_1.Path.Empty, true);\n }\n else {\n util_3.forEach(write.children, function (pathString, node) {\n affectedTree_1 = affectedTree_1.set(new Path_1.Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(new AckUserWrite_1.AckUserWrite(write.path, affectedTree_1, revert));\n }\n };\n /**\n * Apply new server data for the specified path..\n *\n * @param {!Path} path\n * @param {!Node} newData\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerOverwrite = function (path, newData) {\n return this.applyOperationToSyncPoints_(new Overwrite_1.Overwrite(Operation_1.OperationSource.Server, path, newData));\n };\n /**\n * Apply new server data to be merged in at the specified path.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyServerMerge = function (path, changedChildren) {\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n return this.applyOperationToSyncPoints_(new Merge_1.Merge(Operation_1.OperationSource.Server, path, changeTree));\n };\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyListenComplete = function (path) {\n return this.applyOperationToSyncPoints_(new ListenComplete_1.ListenComplete(Operation_1.OperationSource.Server, path));\n };\n /**\n * Apply new server data for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryOverwrite = function (path, snap, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new Overwrite_1.Overwrite(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, snap);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // Query must have been removed already\n return [];\n }\n };\n /**\n * Apply server data to be merged in for the specified tagged query.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedQueryMerge = function (path, changedChildren, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var changeTree = ImmutableTree_1.ImmutableTree.fromObject(changedChildren);\n var op = new Merge_1.Merge(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath, changeTree);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Apply a listen complete for a tagged query\n *\n * @param {!Path} path\n * @param {!number} tag\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.applyTaggedListenComplete = function (path, tag) {\n var queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n var r = SyncTree.parseQueryKey_(queryKey);\n var queryPath = r.path, queryId = r.queryId;\n var relativePath = Path_1.Path.relativePath(queryPath, path);\n var op = new ListenComplete_1.ListenComplete(Operation_1.OperationSource.forServerTaggedQuery(queryId), relativePath);\n return this.applyTaggedOperation_(queryPath, op);\n }\n else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\n };\n /**\n * Add an event callback for the specified query.\n *\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n * @return {!Array.} Events to raise.\n */\n SyncTree.prototype.addEventRegistration = function (query, eventRegistration) {\n var path = query.path;\n var serverCache = null;\n var foundAncestorDefaultView = false;\n // Any covering writes will necessarily be at the root, so really all we need to find is the server cache.\n // Consider optimizing this once there's a better understanding of what actual behavior will be.\n this.syncPointTree_.foreachOnPath(path, function (pathToSyncPoint, sp) {\n var relativePath = Path_1.Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n var syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint_1.SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n }\n else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n }\n else {\n serverCacheComplete = false;\n serverCache = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function (childName, childSyncPoint) {\n var completeCache = childSyncPoint.getCompleteServerCache(Path_1.Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(childName, completeCache);\n }\n });\n }\n var viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n var queryKey = SyncTree.makeQueryKey_(query);\n util_1.assert(!(queryKey in this.queryToTagMap_), 'View does not exist, but we have a tag');\n var tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n var writesCache = this.pendingWriteTree_.childWrites(path);\n var events = syncPoint.addEventRegistration(query, eventRegistration, writesCache, serverCache, serverCacheComplete);\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n var view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n };\n /**\n * Remove event callback(s).\n *\n * If query is the default query, we'll check all queries for the specified eventRegistration.\n * If eventRegistration is null, we'll remove all callbacks for the specified query/queries.\n *\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration If null, all callbacks are removed.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n SyncTree.prototype.removeEventRegistration = function (query, eventRegistration, cancelError) {\n var _this = this;\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n var path = query.path;\n var maybeSyncPoint = this.syncPointTree_.get(path);\n var cancelEvents = [];\n // A removal on a default query affects all queries at that location. A removal on an indexed query, even one without\n // other query constraints, does *not* affect all queries at that location. So this check must be for 'default', and\n // not loadsAllData().\n if (maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n var removedAndEvents = maybeSyncPoint.removeEventRegistration(query, eventRegistration, cancelError);\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n var removed = removedAndEvents.removed;\n cancelEvents = removedAndEvents.events;\n // We may have just removed one of many listeners and can short-circuit this whole process\n // We may also not have removed a default listener, in which case all of the descendant listeners should already be\n // properly set up.\n //\n // Since indexed queries can shadow if they don't have other query constraints, check for loadsAllData(), instead of\n // queryId === 'default'\n var removingDefault = -1 !==\n removed.findIndex(function (query) {\n return query.getQueryParams().loadsAllData();\n });\n var covered = this.syncPointTree_.findOnPath(path, function (relativePath, parentSyncPoint) {\n return parentSyncPoint.hasCompleteView();\n });\n if (removingDefault && !covered) {\n var subtree = this.syncPointTree_.subtree(path);\n // There are potentially child listeners. Determine what if any listens we need to send before executing the\n // removal\n if (!subtree.isEmpty()) {\n // We need to fold over our subtree and collect the listeners to send\n var newViews = this.collectDistinctViewsForSubTree_(subtree);\n // Ok, we've collected all the listens we need. Set them up.\n for (var i = 0; i < newViews.length; ++i) {\n var view = newViews[i], newQuery = view.getQuery();\n var listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(SyncTree.queryForListening_(newQuery), this.tagForQuery_(newQuery), listener.hashFn, listener.onComplete);\n }\n }\n else {\n // There's nothing below us, so nothing we need to start listening on\n }\n }\n // If we removed anything and we're not covered by a higher up listen, we need to stop listening on this query\n // The above block has us covered in terms of making sure we're set up on listens lower in the tree.\n // Also, note that if we have a cancelError, it's already been removed at the provider level.\n if (!covered && removed.length > 0 && !cancelError) {\n // If we removed a default, then we weren't listening on any of the other queries here. Just cancel the one\n // default. Otherwise, we need to iterate through and cancel each individual query\n if (removingDefault) {\n // We don't tag default listeners\n var defaultTag = null;\n this.listenProvider_.stopListening(SyncTree.queryForListening_(query), defaultTag);\n }\n else {\n removed.forEach(function (queryToRemove) {\n var tagToRemove = _this.queryToTagMap_[SyncTree.makeQueryKey_(queryToRemove)];\n _this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToRemove), tagToRemove);\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n }\n else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n };\n /**\n * Returns a complete cache, if we have one, of the data at a particular path. The location must have a listener above\n * it, but as this is only used by transaction code, that should always be the case anyways.\n *\n * Note: this method will *include* hidden writes from transaction with applyLocally set to false.\n * @param {!Path} path The path to the data we want\n * @param {Array.=} writeIdsToExclude A specific set to be excluded\n * @return {?Node}\n */\n SyncTree.prototype.calcCompleteEventCache = function (path, writeIdsToExclude) {\n var includeHiddenSets = true;\n var writeTree = this.pendingWriteTree_;\n var serverCache = this.syncPointTree_.findOnPath(path, function (pathSoFar, syncPoint) {\n var relativePath = Path_1.Path.relativePath(pathSoFar, path);\n var serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(path, serverCache, writeIdsToExclude, includeHiddenSets);\n };\n /**\n * This collapses multiple unfiltered views into a single view, since we only need a single\n * listener for them.\n *\n * @param {!ImmutableTree.} subtree\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.collectDistinctViewsForSubTree_ = function (subtree) {\n return subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n var completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n }\n else {\n // No complete view here, flatten any deeper listens into an array\n var views_1 = [];\n if (maybeChildSyncPoint) {\n views_1 = maybeChildSyncPoint.getQueryViews();\n }\n util_3.forEach(childMap, function (key, childViews) {\n views_1 = views_1.concat(childViews);\n });\n return views_1;\n }\n });\n };\n /**\n * @param {!Array.} queries\n * @private\n */\n SyncTree.prototype.removeTags_ = function (queries) {\n for (var j = 0; j < queries.length; ++j) {\n var removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n var removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n var removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\n }\n };\n /**\n * Normalizes a query to a query we send the server for listening\n * @param {!Query} query\n * @return {!Query} The normalized query\n * @private\n */\n SyncTree.queryForListening_ = function (query) {\n if (query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()) {\n // We treat queries that load all data as default queries\n // Cast is necessary because ref() technically returns Firebase which is actually fb.api.Firebase which inherits\n // from Query\n return /** @type {!Query} */ query.getRef();\n }\n else {\n return query;\n }\n };\n /**\n * For a given new listen, manage the de-duplication of outstanding subscriptions.\n *\n * @param {!Query} query\n * @param {!View} view\n * @return {!Array.} This method can return events to support synchronous data sources\n * @private\n */\n SyncTree.prototype.setupListener_ = function (query, view) {\n var path = query.path;\n var tag = this.tagForQuery_(query);\n var listener = this.createListenerForView_(view);\n var events = this.listenProvider_.startListening(SyncTree.queryForListening_(query), tag, listener.hashFn, listener.onComplete);\n var subtree = this.syncPointTree_.subtree(path);\n // The root of this subtree has our query. We're here because we definitely need to send a listen for that, but we\n // may need to shadow other listens as well.\n if (tag) {\n util_1.assert(!subtree.value.hasCompleteView(), \"If we're adding a query, it shouldn't be shadowed\");\n }\n else {\n // Shadow everything at or below this location, this is a default listener.\n var queriesToStop = subtree.fold(function (relativePath, maybeChildSyncPoint, childMap) {\n if (!relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n }\n else {\n // No default listener here, flatten any deeper queries into an array\n var queries_1 = [];\n if (maybeChildSyncPoint) {\n queries_1 = queries_1.concat(maybeChildSyncPoint.getQueryViews().map(function (view) { return view.getQuery(); }));\n }\n util_3.forEach(childMap, function (key, childQueries) {\n queries_1 = queries_1.concat(childQueries);\n });\n return queries_1;\n }\n });\n for (var i = 0; i < queriesToStop.length; ++i) {\n var queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(SyncTree.queryForListening_(queryToStop), this.tagForQuery_(queryToStop));\n }\n }\n return events;\n };\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n SyncTree.prototype.createListenerForView_ = function (view) {\n var _this = this;\n var query = view.getQuery();\n var tag = this.tagForQuery_(query);\n return {\n hashFn: function () {\n var cache = view.getServerCache() || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: function (status) {\n if (status === 'ok') {\n if (tag) {\n return _this.applyTaggedListenComplete(query.path, tag);\n }\n else {\n return _this.applyListenComplete(query.path);\n }\n }\n else {\n // If a listen failed, kill all of the listeners here, not just the one that triggered the error.\n // Note that this may need to be scoped to just this listener if we change permissions on filtered children\n var error = util_2.errorForServerCode(status, query);\n return _this.removeEventRegistration(query, \n /*eventRegistration*/ null, error);\n }\n }\n };\n };\n /**\n * Given a query, computes a \"queryKey\" suitable for use in our queryToTagMap_.\n * @private\n * @param {!Query} query\n * @return {string}\n */\n SyncTree.makeQueryKey_ = function (query) {\n return query.path.toString() + '$' + query.queryIdentifier();\n };\n /**\n * Given a queryKey (created by makeQueryKey), parse it back into a path and queryId.\n * @private\n * @param {!string} queryKey\n * @return {{queryId: !string, path: !Path}}\n */\n SyncTree.parseQueryKey_ = function (queryKey) {\n var splitIndex = queryKey.indexOf('$');\n util_1.assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, 'Bad queryKey.');\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path_1.Path(queryKey.substr(0, splitIndex))\n };\n };\n /**\n * Return the query associated with the given tag, if we have one\n * @param {!number} tag\n * @return {?string}\n * @private\n */\n SyncTree.prototype.queryKeyForTag_ = function (tag) {\n return this.tagToQueryMap_['_' + tag];\n };\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n SyncTree.prototype.tagForQuery_ = function (query) {\n var queryKey = SyncTree.makeQueryKey_(query);\n return util_3.safeGet(this.queryToTagMap_, queryKey);\n };\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n SyncTree.getNextQueryTag_ = function () {\n return SyncTree.nextQueryTag_++;\n };\n /**\n * A helper method to apply tagged operations\n *\n * @param {!Path} queryPath\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyTaggedOperation_ = function (queryPath, operation) {\n var syncPoint = this.syncPointTree_.get(queryPath);\n util_1.assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n var writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(operation, writesCache, \n /*serverCache=*/ null);\n };\n /**\n * A helper method that visits all descendant and ancestor SyncPoints, applying the operation.\n *\n * NOTES:\n * - Descendant SyncPoints will be visited first (since we raise events depth-first).\n \n * - We call applyOperation() on each SyncPoint passing three things:\n * 1. A version of the Operation that has been made relative to the SyncPoint location.\n * 2. A WriteTreeRef of any writes we have cached at the SyncPoint location.\n * 3. A snapshot Node with cached server data, if we have it.\n \n * - We concatenate all of the events returned by each SyncPoint and return the result.\n *\n * @param {!Operation} operation\n * @return {!Array.}\n * @private\n */\n SyncTree.prototype.applyOperationToSyncPoints_ = function (operation) {\n return this.applyOperationHelper_(operation, this.syncPointTree_, \n /*serverCache=*/ null, this.pendingWriteTree_.childWrites(Path_1.Path.Empty));\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);\n }\n else {\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n var childName = operation.path.getFront();\n var childOperation = operation.operationForChild(childName);\n var childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n events = events.concat(this.applyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n }\n };\n /**\n * Recursive helper for applyOperationToSyncPoints_\n *\n * @private\n * @param {!Operation} operation\n * @param {ImmutableTree.} syncPointTree\n * @param {?Node} serverCache\n * @param {!WriteTreeRef} writesCache\n * @return {!Array.}\n */\n SyncTree.prototype.applyOperationDescendantsHelper_ = function (operation, syncPointTree, serverCache, writesCache) {\n var _this = this;\n var syncPoint = syncPointTree.get(Path_1.Path.Empty);\n // If we don't have cached server data, see if we can get it from this SyncPoint.\n if (serverCache == null && syncPoint != null) {\n serverCache = syncPoint.getCompleteServerCache(Path_1.Path.Empty);\n }\n var events = [];\n syncPointTree.children.inorderTraversal(function (childName, childTree) {\n var childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n var childWritesCache = writesCache.child(childName);\n var childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(_this.applyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));\n }\n });\n if (syncPoint) {\n events = events.concat(syncPoint.applyOperation(operation, writesCache, serverCache));\n }\n return events;\n };\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n SyncTree.nextQueryTag_ = 1;\n return SyncTree;\n}());\nexports.SyncTree = SyncTree;\n\n//# sourceMappingURL=SyncTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SyncTree.js\n// module id = 86\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\nvar AckUserWrite = /** @class */ (function () {\n /**\n *\n * @param {!Path} path\n * @param {!ImmutableTree} affectedTree A tree containing true for each affected path. Affected paths can't overlap.\n * @param {!boolean} revert\n */\n function AckUserWrite(\n /**@inheritDoc */ path, \n /**@inheritDoc */ affectedTree, \n /**@inheritDoc */ revert) {\n this.path = path;\n this.affectedTree = affectedTree;\n this.revert = revert;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.ACK_USER_WRITE;\n /** @inheritDoc */\n this.source = Operation_1.OperationSource.User;\n }\n /**\n * @inheritDoc\n */\n AckUserWrite.prototype.operationForChild = function (childName) {\n if (!this.path.isEmpty()) {\n util_1.assert(this.path.getFront() === childName, 'operationForChild called for unrelated child.');\n return new AckUserWrite(this.path.popFront(), this.affectedTree, this.revert);\n }\n else if (this.affectedTree.value != null) {\n util_1.assert(this.affectedTree.children.isEmpty(), 'affectedTree should not have overlapping affected paths.');\n // All child locations are affected as well; just return same operation.\n return this;\n }\n else {\n var childTree = this.affectedTree.subtree(new Path_1.Path(childName));\n return new AckUserWrite(Path_1.Path.Empty, childTree, this.revert);\n }\n };\n return AckUserWrite;\n}());\nexports.AckUserWrite = AckUserWrite;\n\n//# sourceMappingURL=AckUserWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/AckUserWrite.js\n// module id = 87\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Path_1 = require(\"../util/Path\");\nvar Operation_1 = require(\"./Operation\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nvar ListenComplete = /** @class */ (function () {\n function ListenComplete(source, path) {\n this.source = source;\n this.path = path;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.LISTEN_COMPLETE;\n }\n ListenComplete.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path_1.Path.Empty);\n }\n else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n };\n return ListenComplete;\n}());\nexports.ListenComplete = ListenComplete;\n\n//# sourceMappingURL=ListenComplete.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/ListenComplete.js\n// module id = 88\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"./Operation\");\nvar Overwrite_1 = require(\"./Overwrite\");\nvar Path_1 = require(\"../util/Path\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nvar Merge = /** @class */ (function () {\n function Merge(\n /**@inheritDoc */ source, \n /**@inheritDoc */ path, \n /**@inheritDoc */ children) {\n this.source = source;\n this.path = path;\n this.children = children;\n /** @inheritDoc */\n this.type = Operation_1.OperationType.MERGE;\n }\n /**\n * @inheritDoc\n */\n Merge.prototype.operationForChild = function (childName) {\n if (this.path.isEmpty()) {\n var childTree = this.children.subtree(new Path_1.Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\n }\n else if (childTree.value) {\n // We have a snapshot for the child in question. This becomes an overwrite of the child.\n return new Overwrite_1.Overwrite(this.source, Path_1.Path.Empty, childTree.value);\n }\n else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path_1.Path.Empty, childTree);\n }\n }\n else {\n util_1.assert(this.path.getFront() === childName, \"Can't get a merge for a child not on the path of the operation\");\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n };\n /**\n * @inheritDoc\n */\n Merge.prototype.toString = function () {\n return ('Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')');\n };\n return Merge;\n}());\nexports.Merge = Merge;\n\n//# sourceMappingURL=Merge.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/operation/Merge.js\n// module id = 89\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar ViewProcessor_1 = require(\"./ViewProcessor\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar CacheNode_1 = require(\"./CacheNode\");\nvar ViewCache_1 = require(\"./ViewCache\");\nvar EventGenerator_1 = require(\"./EventGenerator\");\nvar util_1 = require(\"@firebase/util\");\nvar Operation_1 = require(\"../operation/Operation\");\nvar Change_1 = require(\"./Change\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\n/**\n * A view represents a specific location and query that has 1 or more event registrations.\n *\n * It does several things:\n * - Maintains the list of event registrations for this location/query.\n * - Maintains a cache of the data visible for this location/query.\n * - Applies new operations (via applyOperation), updates the cache, and based on the event\n * registrations returns the set of events to be raised.\n * @constructor\n */\nvar View = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n function View(query_, initialViewCache) {\n this.query_ = query_;\n this.eventRegistrations_ = [];\n var params = this.query_.getQueryParams();\n var indexFilter = new IndexedFilter_1.IndexedFilter(params.getIndex());\n var filter = params.getNodeFilter();\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor_1.ViewProcessor(filter);\n var initialServerCache = initialViewCache.getServerCache();\n var initialEventCache = initialViewCache.getEventCache();\n // Don't filter server node with other filter than index, wait for tagged listen\n var serverSnap = indexFilter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);\n var eventSnap = filter.updateFullNode(ChildrenNode_1.ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);\n var newServerCache = new CacheNode_1.CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());\n var newEventCache = new CacheNode_1.CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache_1.ViewCache(newEventCache, newServerCache);\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator_1.EventGenerator(this.query_);\n }\n /**\n * @return {!Query}\n */\n View.prototype.getQuery = function () {\n return this.query_;\n };\n /**\n * @return {?Node}\n */\n View.prototype.getServerCache = function () {\n return this.viewCache_.getServerCache().getNode();\n };\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n View.prototype.getCompleteServerCache = function (path) {\n var cache = this.viewCache_.getCompleteServerSnap();\n if (cache) {\n // If this isn't a \"loadsAllData\" view, then cache isn't actually a complete cache and\n // we need to see if it contains the child we're interested in.\n if (this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())) {\n return cache.getChild(path);\n }\n }\n return null;\n };\n /**\n * @return {boolean}\n */\n View.prototype.isEmpty = function () {\n return this.eventRegistrations_.length === 0;\n };\n /**\n * @param {!EventRegistration} eventRegistration\n */\n View.prototype.addEventRegistration = function (eventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n };\n /**\n * @param {?EventRegistration} eventRegistration If null, remove all callbacks.\n * @param {Error=} cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return {!Array.} Cancel events, if cancelError was provided.\n */\n View.prototype.removeEventRegistration = function (eventRegistration, cancelError) {\n var cancelEvents = [];\n if (cancelError) {\n util_1.assert(eventRegistration == null, 'A cancel should cancel all event registrations.');\n var path_1 = this.query_.path;\n this.eventRegistrations_.forEach(function (registration) {\n cancelError /** @type {!Error} */ = cancelError;\n var maybeEvent = registration.createCancelEvent(cancelError, path_1);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n if (eventRegistration) {\n var remaining = [];\n for (var i = 0; i < this.eventRegistrations_.length; ++i) {\n var existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\n }\n else if (eventRegistration.hasAnyCallback()) {\n // We're removing just this one\n remaining = remaining.concat(this.eventRegistrations_.slice(i + 1));\n break;\n }\n }\n this.eventRegistrations_ = remaining;\n }\n else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n };\n /**\n * Applies the given Operation, updates our cache, and returns the appropriate events.\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @return {!Array.}\n */\n View.prototype.applyOperation = function (operation, writesCache, completeServerCache) {\n if (operation.type === Operation_1.OperationType.MERGE &&\n operation.source.queryId !== null) {\n util_1.assert(this.viewCache_.getCompleteServerSnap(), 'We should always have a full cache before handling merges');\n util_1.assert(this.viewCache_.getCompleteEventSnap(), 'Missing event cache, even though we have a server cache');\n }\n var oldViewCache = this.viewCache_;\n var result = this.processor_.applyOperation(oldViewCache, operation, writesCache, completeServerCache);\n this.processor_.assertIndexed(result.viewCache);\n util_1.assert(result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(), 'Once a server snap is complete, it should never go back');\n this.viewCache_ = result.viewCache;\n return this.generateEventsForChanges_(result.changes, result.viewCache.getEventCache().getNode(), null);\n };\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n View.prototype.getInitialEvents = function (registration) {\n var eventSnap = this.viewCache_.getEventCache();\n var initialChanges = [];\n if (!eventSnap.getNode().isLeafNode()) {\n var eventNode = eventSnap.getNode();\n eventNode.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (key, childNode) {\n initialChanges.push(Change_1.Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change_1.Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(initialChanges, eventSnap.getNode(), registration);\n };\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n View.prototype.generateEventsForChanges_ = function (changes, eventCache, eventRegistration) {\n var registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(changes, eventCache, registrations);\n };\n return View;\n}());\nexports.View = View;\n\n//# sourceMappingURL=View.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/View.js\n// module id = 90\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Operation_1 = require(\"../operation/Operation\");\nvar util_1 = require(\"@firebase/util\");\nvar ChildChangeAccumulator_1 = require(\"./ChildChangeAccumulator\");\nvar Change_1 = require(\"./Change\");\nvar ChildrenNode_1 = require(\"../snap/ChildrenNode\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar ImmutableTree_1 = require(\"../util/ImmutableTree\");\nvar Path_1 = require(\"../util/Path\");\nvar CompleteChildSource_1 = require(\"./CompleteChildSource\");\n/**\n * @constructor\n * @struct\n */\nvar ProcessorResult = /** @class */ (function () {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n function ProcessorResult(viewCache, changes) {\n this.viewCache = viewCache;\n this.changes = changes;\n }\n return ProcessorResult;\n}());\nexports.ProcessorResult = ProcessorResult;\n/**\n * @constructor\n */\nvar ViewProcessor = /** @class */ (function () {\n /**\n * @param {!NodeFilter} filter_\n */\n function ViewProcessor(filter_) {\n this.filter_ = filter_;\n }\n /**\n * @param {!ViewCache} viewCache\n */\n ViewProcessor.prototype.assertIndexed = function (viewCache) {\n util_1.assert(viewCache\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Event snap not indexed');\n util_1.assert(viewCache\n .getServerCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()), 'Server snap not indexed');\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n ViewProcessor.prototype.applyOperation = function (oldViewCache, operation, writesCache, completeCache) {\n var accumulator = new ChildChangeAccumulator_1.ChildChangeAccumulator();\n var newViewCache, filterServerNode;\n if (operation.type === Operation_1.OperationType.OVERWRITE) {\n var overwrite = operation;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(overwrite.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered and the\n // update is not at the root in which case it is ok (and necessary) to mark the node unfiltered\n // again\n filterServerNode =\n overwrite.source.tagged ||\n (oldViewCache.getServerCache().isFiltered() &&\n !overwrite.path.isEmpty());\n newViewCache = this.applyServerOverwrite_(oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.MERGE) {\n var merge = operation;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);\n }\n else {\n util_1.assert(merge.source.fromServer, 'Unknown source.');\n // We filter the node if it's a tagged update or the node has been previously filtered\n filterServerNode =\n merge.source.tagged || oldViewCache.getServerCache().isFiltered();\n newViewCache = this.applyServerMerge_(oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.ACK_USER_WRITE) {\n var ackUserWrite = operation;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);\n }\n else {\n newViewCache = this.revertUserWrite_(oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);\n }\n }\n else if (operation.type === Operation_1.OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(oldViewCache, operation.path, writesCache, accumulator);\n }\n else {\n throw util_1.assertionError('Unknown operation type: ' + operation.type);\n }\n var changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n ViewProcessor.maybeAddValueEvent_ = function (oldViewCache, newViewCache, accumulator) {\n var eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n var isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n var oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap\n .getNode()\n .equals(/** @type {!Node} */ (oldCompleteSnap))) ||\n !eventSnap\n .getNode()\n .getPriority()\n .equals(oldCompleteSnap.getPriority())) {\n accumulator.push(Change_1.Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()));\n }\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} changePath\n * @param {!WriteTreeRef} writesCache\n * @param {!CompleteChildSource} source\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.generateEventCacheAfterServerEvent_ = function (viewCache, changePath, writesCache, source, accumulator) {\n var oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n }\n else {\n var newEventCache = void 0, serverNode = void 0;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n util_1.assert(viewCache.getServerCache().isFullyInitialized(), 'If change path is empty, we must have complete server data');\n if (viewCache.getServerCache().isFiltered()) {\n // We need to special case this, because we need to only apply writes to complete children, or\n // we might end up raising events for incomplete children. If the server data is filtered deep\n // writes cannot be guaranteed to be complete\n var serverCache = viewCache.getCompleteServerSnap();\n var completeChildren = serverCache instanceof ChildrenNode_1.ChildrenNode\n ? serverCache\n : ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var completeEventChildren = writesCache.calcCompleteEventChildren(completeChildren);\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeEventChildren, accumulator);\n }\n else {\n var completeNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n newEventCache = this.filter_.updateFullNode(viewCache.getEventCache().getNode(), completeNode, accumulator);\n }\n }\n else {\n var childKey = changePath.getFront();\n if (childKey == '.priority') {\n util_1.assert(changePath.getLength() == 1, \"Can't have a priority with additional path components\");\n var oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n var updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventNode, serverNode);\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(oldEventNode, updatedPriority);\n }\n else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n }\n else {\n var childChangePath = changePath.popFront();\n // update child\n var newEventChild = void 0;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n var eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(changePath, oldEventSnap.getNode(), serverNode);\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n }\n else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n }\n else {\n newEventChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);\n }\n else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized() || changePath.isEmpty(), this.filter_.filtersNodes());\n }\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {\n var oldServerSnap = oldViewCache.getServerCache();\n var newServerCache;\n var serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);\n }\n else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {\n // we want to filter the server node, but we didn't filter the server node yet, so simulate a full update\n var newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);\n }\n else {\n var childKey = changePath.getFront();\n if (!oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n var childChangePath = changePath.popFront();\n var childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n var newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);\n }\n else {\n newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, null);\n }\n }\n var newViewCache = oldViewCache.updateServerSnap(newServerCache, oldServerSnap.isFullyInitialized() || changePath.isEmpty(), serverFilter.filtersNodes());\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, newViewCache, completeCache);\n return this.generateEventCacheAfterServerEvent_(newViewCache, changePath, writesCache, source, accumulator);\n };\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Path} changePath\n * @param {!Node} changedSnap\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserOverwrite_ = function (oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {\n var oldEventSnap = oldViewCache.getEventCache();\n var newViewCache, newEventCache;\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(oldViewCache.getEventCache().getNode(), changedSnap, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, true, this.filter_.filtersNodes());\n }\n else {\n var childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(oldViewCache.getEventCache().getNode(), changedSnap);\n newViewCache = oldViewCache.updateEventSnap(newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());\n }\n else {\n var childChangePath = changePath.popFront();\n var oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n var newChild = void 0;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n }\n else {\n var childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()) {\n // This is a priority update on an empty node. If this node exists on the server, the\n // server will send down the priority in the update, so ignore for now\n newChild = childNode;\n }\n else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n }\n else {\n // There is no complete child node available\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n var newEventSnap = this.filter_.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);\n newViewCache = oldViewCache.updateEventSnap(newEventSnap, oldEventSnap.isFullyInitialized(), this.filter_.filtersNodes());\n }\n else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n ViewProcessor.cacheHasChild_ = function (viewCache, childKey) {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyUserMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, accumulator) {\n var _this = this;\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n changedChildren.foreach(function (relativePath, childNode) {\n var writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = _this.applyUserOverwrite_(curViewCache, writePath, childNode, writesCache, serverCache, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n ViewProcessor.prototype.applyMerge_ = function (node, merge) {\n merge.foreach(function (relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!ImmutableTree.} changedChildren\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} serverCache\n * @param {boolean} filterServerNode\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.applyServerMerge_ = function (viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {\n var _this = this;\n // If we don't have a cache yet, this merge was intended for a previously listen in the same location. Ignore it and\n // wait for the complete data update coming soon.\n if (viewCache\n .getServerCache()\n .getNode()\n .isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()) {\n return viewCache;\n }\n // HACK: In the case of a limit query, there may be some changes that bump things out of the\n // window leaving room for new items. It's important we process these changes first, so we\n // iterate the changes twice, first processing any that affect items currently in view.\n // TODO: I consider an item \"in view\" if cacheHasChild is true, which checks both the server\n // and event snap. I'm not sure if this will result in edge cases when a child is in one but\n // not the other.\n var curViewCache = viewCache;\n var viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n }\n else {\n viewMergeTree = ImmutableTree_1.ImmutableTree.Empty.setTree(path, changedChildren);\n }\n var serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal(function (childKey, childTree) {\n if (serverNode.hasChild(childKey)) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n viewMergeTree.children.inorderTraversal(function (childKey, childMergeTree) {\n var isUnknownDeepMerge = !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n var serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n var newChild = _this.applyMerge_(serverChild, childMergeTree);\n curViewCache = _this.applyServerOverwrite_(curViewCache, new Path_1.Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);\n }\n });\n return curViewCache;\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} ackPath\n * @param {!ImmutableTree} affectedTree\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.ackUserWrite_ = function (viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n // Only filter server node if it is currently filtered\n var filterServerNode = viewCache.getServerCache().isFiltered();\n // Essentially we'll just get our existing server cache for the affected paths and re-apply it as a server update\n // now that it won't be shadowed.\n var serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if ((ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)) {\n return this.applyServerOverwrite_(viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);\n }\n else if (ackPath.isEmpty()) {\n // This is a goofy edge case where we are acking data at this location but don't have full data. We\n // should just re-apply whatever we have in our cache as a merge.\n var changedChildren_1 = ImmutableTree_1.ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KeyIndex_1.KEY_INDEX, function (name, node) {\n changedChildren_1 = changedChildren_1.set(new Path_1.Path(name), node);\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_1, writesCache, completeCache, filterServerNode, accumulator);\n }\n else {\n return viewCache;\n }\n }\n else {\n // This is a merge.\n var changedChildren_2 = ImmutableTree_1.ImmutableTree.Empty;\n affectedTree.foreach(function (mergePath, value) {\n var serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren_2 = changedChildren_2.set(mergePath, serverCache.getNode().getChild(serverCachePath));\n }\n });\n return this.applyServerMerge_(viewCache, ackPath, changedChildren_2, writesCache, completeCache, filterServerNode, accumulator);\n }\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.listenComplete_ = function (viewCache, path, writesCache, accumulator) {\n var oldServerNode = viewCache.getServerCache();\n var newViewCache = viewCache.updateServerSnap(oldServerNode.getNode(), oldServerNode.isFullyInitialized() || path.isEmpty(), oldServerNode.isFiltered());\n return this.generateEventCacheAfterServerEvent_(newViewCache, path, writesCache, CompleteChildSource_1.NO_COMPLETE_CHILD_SOURCE, accumulator);\n };\n /**\n * @param {!ViewCache} viewCache\n * @param {!Path} path\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeServerCache\n * @param {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n ViewProcessor.prototype.revertUserWrite_ = function (viewCache, path, writesCache, completeServerCache, accumulator) {\n var complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n }\n else {\n var source = new CompleteChildSource_1.WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);\n var oldEventCache = viewCache.getEventCache().getNode();\n var newEventCache = void 0;\n if (path.isEmpty() || path.getFront() === '.priority') {\n var newNode = void 0;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n }\n else {\n var serverChildren = viewCache.getServerCache().getNode();\n util_1.assert(serverChildren instanceof ChildrenNode_1.ChildrenNode, 'serverChildren would be complete if leaf node');\n newNode = writesCache.calcCompleteEventChildren(serverChildren);\n }\n newNode = newNode;\n newEventCache = this.filter_.updateFullNode(oldEventCache, newNode, accumulator);\n }\n else {\n var childKey = path.getFront();\n var newChild = writesCache.calcCompleteChild(childKey, viewCache.getServerCache());\n if (newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, newChild, path.popFront(), source, accumulator);\n }\n else if (viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(oldEventCache, childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE, path.popFront(), source, accumulator);\n }\n else {\n newEventCache = oldEventCache;\n }\n if (newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(viewCache.getCompleteServerSnap());\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(newEventCache, complete, accumulator);\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path_1.Path.Empty) != null;\n return viewCache.updateEventSnap(newEventCache, complete, this.filter_.filtersNodes());\n }\n };\n return ViewProcessor;\n}());\nexports.ViewProcessor = ViewProcessor;\n\n//# sourceMappingURL=ViewProcessor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ViewProcessor.js\n// module id = 91\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"./Change\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * @constructor\n */\nvar ChildChangeAccumulator = /** @class */ (function () {\n function ChildChangeAccumulator() {\n this.changeMap_ = {};\n }\n /**\n * @param {!Change} change\n */\n ChildChangeAccumulator.prototype.trackChildChange = function (change) {\n var type = change.type;\n var childKey /** @type {!string} */ = change.childName;\n util_2.assert(type == Change_1.Change.CHILD_ADDED ||\n type == Change_1.Change.CHILD_CHANGED ||\n type == Change_1.Change.CHILD_REMOVED, 'Only child changes supported for tracking');\n util_2.assert(childKey !== '.priority', 'Only non-priority child changes can be tracked.');\n var oldChange = util_1.safeGet(this.changeMap_, childKey);\n if (oldChange) {\n var oldType = oldChange.type;\n if (type == Change_1.Change.CHILD_ADDED && oldType == Change_1.Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n delete this.changeMap_[childKey];\n }\n else if (type == Change_1.Change.CHILD_REMOVED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childRemovedChange(childKey, oldChange.oldSnap);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_ADDED) {\n this.changeMap_[childKey] = Change_1.Change.childAddedChange(childKey, change.snapshotNode);\n }\n else if (type == Change_1.Change.CHILD_CHANGED &&\n oldType == Change_1.Change.CHILD_CHANGED) {\n this.changeMap_[childKey] = Change_1.Change.childChangedChange(childKey, change.snapshotNode, oldChange.oldSnap);\n }\n else {\n throw util_2.assertionError('Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange);\n }\n }\n else {\n this.changeMap_[childKey] = change;\n }\n };\n /**\n * @return {!Array.}\n */\n ChildChangeAccumulator.prototype.getChanges = function () {\n return util_1.getValues(this.changeMap_);\n };\n return ChildChangeAccumulator;\n}());\nexports.ChildChangeAccumulator = ChildChangeAccumulator;\n\n//# sourceMappingURL=ChildChangeAccumulator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/ChildChangeAccumulator.js\n// module id = 92\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar CacheNode_1 = require(\"./CacheNode\");\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nvar NoCompleteChildSource_ = /** @class */ (function () {\n function NoCompleteChildSource_() {\n }\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getCompleteChild = function (childKey) {\n return null;\n };\n /**\n * @inheritDoc\n */\n NoCompleteChildSource_.prototype.getChildAfterChild = function (index, child, reverse) {\n return null;\n };\n return NoCompleteChildSource_;\n}());\nexports.NoCompleteChildSource_ = NoCompleteChildSource_;\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexports.NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n/**\n * An implementation of CompleteChildSource that uses a WriteTree in addition to any other server data or\n * old event caches available to calculate complete children.\n *\n *\n * @implements CompleteChildSource\n */\nvar WriteTreeCompleteChildSource = /** @class */ (function () {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n function WriteTreeCompleteChildSource(writes_, viewCache_, optCompleteServerCache_) {\n if (optCompleteServerCache_ === void 0) { optCompleteServerCache_ = null; }\n this.writes_ = writes_;\n this.viewCache_ = viewCache_;\n this.optCompleteServerCache_ = optCompleteServerCache_;\n }\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getCompleteChild = function (childKey) {\n var node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n }\n else {\n var serverNode = this.optCompleteServerCache_ != null\n ? new CacheNode_1.CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n };\n /**\n * @inheritDoc\n */\n WriteTreeCompleteChildSource.prototype.getChildAfterChild = function (index, child, reverse) {\n var completeServerData = this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n var nodes = this.writes_.calcIndexedSlice(completeServerData, child, 1, reverse, index);\n if (nodes.length === 0) {\n return null;\n }\n else {\n return nodes[0];\n }\n };\n return WriteTreeCompleteChildSource;\n}());\nexports.WriteTreeCompleteChildSource = WriteTreeCompleteChildSource;\n\n//# sourceMappingURL=CompleteChildSource.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/CompleteChildSource.js\n// module id = 93\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar Node_1 = require(\"../snap/Node\");\nvar Change_1 = require(\"./Change\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * An EventGenerator is used to convert \"raw\" changes (Change) as computed by the\n * CacheDiffer into actual events (Event) that can be raised. See generateEventsForChanges()\n * for details.\n *\n * @constructor\n */\nvar EventGenerator = /** @class */ (function () {\n /**\n *\n * @param {!Query} query_\n */\n function EventGenerator(query_) {\n this.query_ = query_;\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\n /**\n * Given a set of raw changes (no moved events and prevName not specified yet), and a set of\n * EventRegistrations that should be notified of these changes, generate the actual events to be raised.\n *\n * Notes:\n * - child_moved events will be synthesized at this time for any child_changed events that affect\n * our index.\n * - prevName will be calculated based on the index ordering.\n *\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {!Array.} eventRegistrations\n * @return {!Array.}\n */\n EventGenerator.prototype.generateEventsForChanges = function (changes, eventCache, eventRegistrations) {\n var _this = this;\n var events = [];\n var moves = [];\n changes.forEach(function (change) {\n if (change.type === Change_1.Change.CHILD_CHANGED &&\n _this.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {\n moves.push(Change_1.Change.childMovedChange(change.childName, change.snapshotNode));\n }\n });\n this.generateEventsForType_(events, Change_1.Change.CHILD_REMOVED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_ADDED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_MOVED, moves, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.CHILD_CHANGED, changes, eventRegistrations, eventCache);\n this.generateEventsForType_(events, Change_1.Change.VALUE, changes, eventRegistrations, eventCache);\n return events;\n };\n /**\n * Given changes of a single change type, generate the corresponding events.\n *\n * @param {!Array.} events\n * @param {!string} eventType\n * @param {!Array.} changes\n * @param {!Array.} registrations\n * @param {!Node} eventCache\n * @private\n */\n EventGenerator.prototype.generateEventsForType_ = function (events, eventType, changes, registrations, eventCache) {\n var _this = this;\n var filteredChanges = changes.filter(function (change) { return change.type === eventType; });\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(function (change) {\n var materializedChange = _this.materializeSingleChange_(change, eventCache);\n registrations.forEach(function (registration) {\n if (registration.respondsTo(change.type)) {\n events.push(registration.createEvent(materializedChange, _this.query_));\n }\n });\n });\n };\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n EventGenerator.prototype.materializeSingleChange_ = function (change, eventCache) {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n }\n else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName, change.snapshotNode, this.index_);\n return change;\n }\n };\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n EventGenerator.prototype.compareChanges_ = function (a, b) {\n if (a.childName == null || b.childName == null) {\n throw util_1.assertionError('Should only compare child_ events.');\n }\n var aWrapped = new Node_1.NamedNode(a.childName, a.snapshotNode);\n var bWrapped = new Node_1.NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n };\n return EventGenerator;\n}());\nexports.EventGenerator = EventGenerator;\n\n//# sourceMappingURL=EventGenerator.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventGenerator.js\n// module id = 94\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\nvar Path_1 = require(\"./util/Path\");\nvar CompoundWrite_1 = require(\"./CompoundWrite\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * WriteTree tracks all pending user-initiated writes and has methods to calculate the result of merging them\n * with underlying server data (to create \"event cache\" data). Pending writes are added with addOverwrite()\n * and addMerge(), and removed with removeWrite().\n *\n * @constructor\n */\nvar WriteTree = /** @class */ (function () {\n function WriteTree() {\n /**\n * A tree tracking the result of applying all visible writes. This does not include transactions with\n * applyLocally=false or writes that are completely shadowed by other writes.\n *\n * @type {!CompoundWrite}\n * @private\n */\n this.visibleWrites_ = CompoundWrite_1.CompoundWrite.Empty;\n /**\n * A list of all pending writes, regardless of visibility and shadowed-ness. Used to calculate arbitrary\n * sets of the changed data, such as hidden writes (from transactions) or changes with certain writes excluded (also\n * used by transactions).\n *\n * @type {!Array.}\n * @private\n */\n this.allWrites_ = [];\n this.lastWriteId_ = -1;\n }\n /**\n * Create a new WriteTreeRef for the given path. For use with a new sync point at the given path.\n *\n * @param {!Path} path\n * @return {!WriteTreeRef}\n */\n WriteTree.prototype.childWrites = function (path) {\n return new WriteTreeRef(path, this);\n };\n /**\n * Record a new overwrite from user code.\n *\n * @param {!Path} path\n * @param {!Node} snap\n * @param {!number} writeId\n * @param {boolean=} visible This is set to false by some transactions. It should be excluded from event caches\n */\n WriteTree.prototype.addOverwrite = function (path, snap, writeId, visible) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older write on top of newer ones');\n if (visible === undefined) {\n visible = true;\n }\n this.allWrites_.push({\n path: path,\n snap: snap,\n writeId: writeId,\n visible: visible\n });\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n };\n /**\n * Record a new merge from user code.\n *\n * @param {!Path} path\n * @param {!Object.} changedChildren\n * @param {!number} writeId\n */\n WriteTree.prototype.addMerge = function (path, changedChildren, writeId) {\n util_2.assert(writeId > this.lastWriteId_, 'Stacking an older merge on top of newer ones');\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n };\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n WriteTree.prototype.getWrite = function (writeId) {\n for (var i = 0; i < this.allWrites_.length; i++) {\n var record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n };\n /**\n * Remove a write (either an overwrite or merge) that has been successfully acknowledge by the server. Recalculates\n * the tree if necessary. We return true if it may have been visible, meaning views need to reevaluate.\n *\n * @param {!number} writeId\n * @return {boolean} true if the write may have been visible (meaning we'll need to reevaluate / raise\n * events as a result).\n */\n WriteTree.prototype.removeWrite = function (writeId) {\n // Note: disabling this check. It could be a transaction that preempted another transaction, and thus was applied\n // out of order.\n //const validClear = revert || this.allWrites_.length === 0 || writeId <= this.allWrites_[0].writeId;\n //assert(validClear, \"Either we don't have this write, or it's the first one in the queue\");\n var _this = this;\n var idx = this.allWrites_.findIndex(function (s) {\n return s.writeId === writeId;\n });\n util_2.assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n var writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n var removedWriteWasVisible = writeToRemove.visible;\n var removedWriteOverlapsWithOtherWrites = false;\n var i = this.allWrites_.length - 1;\n while (removedWriteWasVisible && i >= 0) {\n var currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\n }\n else if (writeToRemove.path.contains(currentWrite.path)) {\n // Either we're covering some writes or they're covering part of us (depending on which came first).\n removedWriteOverlapsWithOtherWrites = true;\n }\n }\n i--;\n }\n if (!removedWriteWasVisible) {\n return false;\n }\n else if (removedWriteOverlapsWithOtherWrites) {\n // There's some shadowing going on. Just rebuild the visible writes from scratch.\n this.resetTree_();\n return true;\n }\n else {\n // There's no shadowing. We can safely just remove the write(s) from visibleWrites.\n if (writeToRemove.snap) {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(writeToRemove.path);\n }\n else {\n var children = writeToRemove.children;\n util_1.forEach(children, function (childName) {\n _this.visibleWrites_ = _this.visibleWrites_.removeWrite(writeToRemove.path.child(childName));\n });\n }\n return true;\n }\n };\n /**\n * Return a complete snapshot for the given path if there's visible write data at that path, else null.\n * No server data is considered.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.getCompleteWriteData = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * Given optional, underlying server data, and an optional set of constraints (exclude some sets, include hidden\n * writes), attempt to calculate a complete snapshot for the given path\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude An optional set to be excluded\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteEventCache = function (treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n var shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n var subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n }\n else if (completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path_1.Path.Empty)) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n }\n else {\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n }\n else {\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n }\n else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (!includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path_1.Path.Empty)) {\n return null;\n }\n else {\n var filter = function (write) {\n return ((write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path)));\n };\n var mergeAtPath = WriteTree.layerTree_(this.allWrites_, filter, treePath);\n var layeredCache = completeServerCache || ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\n }\n }\n };\n /**\n * With optional, underlying server data, attempt to return a children node of children that we have complete data for.\n * Used when creating new views, to pre-fill their complete event children snapshot.\n *\n * @param {!Path} treePath\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTree.prototype.calcCompleteEventChildren = function (treePath, completeServerChildren) {\n var completeChildren = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n var topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childSnap) {\n completeChildren = completeChildren.updateImmediateChild(childName, childSnap);\n });\n }\n return completeChildren;\n }\n else if (completeServerChildren) {\n // Layer any children we have on top of this\n // We know we don't have a top-level set, so just enumerate existing children\n var merge_1 = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n var node = merge_1\n .childCompoundWrite(new Path_1.Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(childName, node);\n });\n // Add any complete children we have from the set\n merge_1.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n else {\n // We don't have anything to layer on top of. Layer on any children we have\n // Note that we can return an empty snap if we have a defined delete\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function (namedNode) {\n completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);\n });\n return completeChildren;\n }\n };\n /**\n * Given that the underlying server data has updated, determine what, if anything, needs to be\n * applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events\n *\n * Either existingEventSnap or existingServerSnap must exist\n *\n * @param {!Path} treePath\n * @param {!Path} childPath\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcEventCacheAfterServerOverwrite = function (treePath, childPath, existingEventSnap, existingServerSnap) {\n util_2.assert(existingEventSnap || existingServerSnap, 'Either existingEventSnap or existingServerSnap must exist');\n var path = treePath.child(childPath);\n if (this.visibleWrites_.hasCompleteWrite(path)) {\n // At this point we can probably guarantee that we're in case 2, meaning no events\n // May need to check visibility while doing the findRootMostValueAndPath call\n return null;\n }\n else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\n }\n else {\n // This could be more efficient if the serverNode + updates doesn't change the eventSnap\n // However this is tricky to find out, since user updates don't necessary change the server\n // snap, e.g. priority updates on empty nodes, or deep deletes. Another special case is if the server\n // adds nodes, but doesn't change any existing writes. It is therefore not enough to\n // only check if the updates change the serverNode.\n // Maybe check if the merge tree contains these special cases and only do a full overwrite in that case?\n return childMerge.apply(existingServerSnap.getChild(childPath));\n }\n }\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!Path} treePath\n * @param {!string} childKey\n * @param {!CacheNode} existingServerSnap\n * @return {?Node}\n */\n WriteTree.prototype.calcCompleteChild = function (treePath, childKey, existingServerSnap) {\n var path = treePath.child(childKey);\n var shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n }\n else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n var childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(existingServerSnap.getNode().getImmediateChild(childKey));\n }\n else {\n return null;\n }\n }\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTree.prototype.shadowingWrite = function (path) {\n return this.visibleWrites_.getCompleteNode(path);\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window.\n *\n * @param {!Path} treePath\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTree.prototype.calcIndexedSlice = function (treePath, completeServerData, startPost, count, reverse, index) {\n var toIterate;\n var merge = this.visibleWrites_.childCompoundWrite(treePath);\n var shadowingNode = merge.getCompleteNode(Path_1.Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n }\n else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n }\n else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n var nodes = [];\n var cmp = index.getCompare();\n var iter = reverse\n ? toIterate.getReverseIteratorFrom(startPost, index)\n : toIterate.getIteratorFrom(startPost, index);\n var next = iter.getNext();\n while (next && nodes.length < count) {\n if (cmp(next, startPost) !== 0) {\n nodes.push(next);\n }\n next = iter.getNext();\n }\n return nodes;\n }\n else {\n return [];\n }\n };\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n WriteTree.prototype.recordContainsPath_ = function (writeRecord, path) {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n }\n else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!util_1.findKey(writeRecord.children, function (childSnap, childName) {\n return writeRecord.path.child(childName).contains(path);\n });\n }\n };\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\n * @private\n */\n WriteTree.prototype.resetTree_ = function () {\n this.visibleWrites_ = WriteTree.layerTree_(this.allWrites_, WriteTree.DefaultFilter_, Path_1.Path.Empty);\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n }\n else {\n this.lastWriteId_ = -1;\n }\n };\n /**\n * The default filter used when constructing the tree. Keep everything that's visible.\n *\n * @param {!WriteRecord} write\n * @return {boolean}\n * @private\n */\n WriteTree.DefaultFilter_ = function (write) {\n return write.visible;\n };\n /**\n * Static method. Given an array of WriteRecords, a filter for which ones to include, and a path, construct the tree of\n * event data at that path.\n *\n * @param {!Array.} writes\n * @param {!function(!WriteRecord):boolean} filter\n * @param {!Path} treeRoot\n * @return {!CompoundWrite}\n * @private\n */\n WriteTree.layerTree_ = function (writes, filter, treeRoot) {\n var compoundWrite = CompoundWrite_1.CompoundWrite.Empty;\n for (var i = 0; i < writes.length; ++i) {\n var write = writes[i];\n // Theory, a later set will either:\n // a) abort a relevant transaction, so no need to worry about excluding it from calculating that transaction\n // b) not be relevant to a transaction (separate branch), so again will not affect the data for that transaction\n if (filter(write)) {\n var writePath = write.path;\n var relativePath = void 0;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, write.snap.getChild(relativePath));\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path_1.Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(relativePath, write.children);\n }\n else if (writePath.contains(treeRoot)) {\n relativePath = Path_1.Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(Path_1.Path.Empty, write.children);\n }\n else {\n var child = util_1.safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n var deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path_1.Path.Empty, deepNode);\n }\n }\n }\n else {\n // There is no overlap between root path and write path, ignore write\n }\n }\n else {\n throw util_2.assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n };\n return WriteTree;\n}());\nexports.WriteTree = WriteTree;\n/**\n * A WriteTreeRef wraps a WriteTree and a path, for convenient access to a particular subtree. All of the methods\n * just proxy to the underlying WriteTree.\n *\n * @constructor\n */\nvar WriteTreeRef = /** @class */ (function () {\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n function WriteTreeRef(path, writeTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\n /**\n * If possible, returns a complete event cache, using the underlying server data if possible. In addition, can be used\n * to get a cache that includes hidden writes, and excludes arbitrary writes. Note that customizing the returned node\n * can lead to a more expensive calculation.\n *\n * @param {?Node} completeServerCache\n * @param {Array.=} writeIdsToExclude Optional writes to exclude.\n * @param {boolean=} includeHiddenWrites Defaults to false, whether or not to layer on writes with visible set to false\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteEventCache = function (completeServerCache, writeIdsToExclude, includeHiddenWrites) {\n return this.writeTree_.calcCompleteEventCache(this.treePath_, completeServerCache, writeIdsToExclude, includeHiddenWrites);\n };\n /**\n * If possible, returns a children node containing all of the complete children we have data for. The returned data is a\n * mix of the given server data and write data.\n *\n * @param {?ChildrenNode} completeServerChildren\n * @return {!ChildrenNode}\n */\n WriteTreeRef.prototype.calcCompleteEventChildren = function (completeServerChildren) {\n return this.writeTree_.calcCompleteEventChildren(this.treePath_, completeServerChildren);\n };\n /**\n * Given that either the underlying server data has updated or the outstanding writes have updated, determine what,\n * if anything, needs to be applied to the event cache.\n *\n * Possibilities:\n *\n * 1. No writes are shadowing. Events should be raised, the snap to be applied comes from the server data\n *\n * 2. Some write is completely shadowing. No events to be raised\n *\n * 3. Is partially shadowed. Events should be raised\n *\n * Either existingEventSnap or existingServerSnap must exist, this is validated via an assert\n *\n * @param {!Path} path\n * @param {?Node} existingEventSnap\n * @param {?Node} existingServerSnap\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcEventCacheAfterServerOverwrite = function (path, existingEventSnap, existingServerSnap) {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(this.treePath_, path, existingEventSnap, existingServerSnap);\n };\n /**\n * Returns a node if there is a complete overwrite for this path. More specifically, if there is a write at\n * a higher path, this will return the child of that write relative to the write and this path.\n * Returns null if there is no write at this path.\n *\n * @param {!Path} path\n * @return {?Node}\n */\n WriteTreeRef.prototype.shadowingWrite = function (path) {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n };\n /**\n * This method is used when processing child remove events on a query. If we can, we pull in children that were outside\n * the window, but may now be in the window\n *\n * @param {?Node} completeServerData\n * @param {!NamedNode} startPost\n * @param {!number} count\n * @param {boolean} reverse\n * @param {!Index} index\n * @return {!Array.}\n */\n WriteTreeRef.prototype.calcIndexedSlice = function (completeServerData, startPost, count, reverse, index) {\n return this.writeTree_.calcIndexedSlice(this.treePath_, completeServerData, startPost, count, reverse, index);\n };\n /**\n * Returns a complete child for a given server snap after applying all user writes or null if there is no\n * complete child for this ChildKey.\n *\n * @param {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n WriteTreeRef.prototype.calcCompleteChild = function (childKey, existingServerCache) {\n return this.writeTree_.calcCompleteChild(this.treePath_, childKey, existingServerCache);\n };\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n WriteTreeRef.prototype.child = function (childName) {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n };\n return WriteTreeRef;\n}());\nexports.WriteTreeRef = WriteTreeRef;\n\n//# sourceMappingURL=WriteTree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/WriteTree.js\n// module id = 95\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ImmutableTree_1 = require(\"./util/ImmutableTree\");\nvar Path_1 = require(\"./util/Path\");\nvar util_1 = require(\"@firebase/util\");\nvar Node_1 = require(\"./snap/Node\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * This class holds a collection of writes that can be applied to nodes in unison. It abstracts away the logic with\n * dealing with priority writes and multiple nested writes. At any given path there is only allowed to be one write\n * modifying that path. Any write to an existing path or shadowing an existing path will modify that existing write\n * to reflect the write added.\n *\n * @constructor\n * @param {!ImmutableTree.} writeTree\n */\nvar CompoundWrite = /** @class */ (function () {\n function CompoundWrite(writeTree_) {\n this.writeTree_ = writeTree_;\n }\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrite = function (path, node) {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(node));\n }\n else {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n var rootMostPath = rootmost.path;\n var value = rootmost.value;\n var relativePath = Path_1.Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n }\n else {\n var subtree = new ImmutableTree_1.ImmutableTree(node);\n var newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n };\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.addWrites = function (path, updates) {\n var newWrite = this;\n util_1.forEach(updates, function (childKey, node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n };\n /**\n * Will remove a write at the given path and deeper paths. This will not modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param {!Path} path The path at which a write and all deeper writes should be removed\n * @return {!CompoundWrite} The new CompoundWrite with the removed path\n */\n CompoundWrite.prototype.removeWrite = function (path) {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n }\n else {\n var newWriteTree = this.writeTree_.setTree(path, ImmutableTree_1.ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\n };\n /**\n * Returns whether this CompoundWrite will fully overwrite a node at a given location and can therefore be\n * considered \"complete\".\n *\n * @param {!Path} path The path to check for\n * @return {boolean} Whether there is a complete write at that path\n */\n CompoundWrite.prototype.hasCompleteWrite = function (path) {\n return this.getCompleteNode(path) != null;\n };\n /**\n * Returns a node for a path if and only if the node is a \"complete\" overwrite at that path. This will not aggregate\n * writes from deeper paths, but will return child nodes from a more shallow path.\n *\n * @param {!Path} path The path to get a complete write\n * @return {?Node} The node if complete at that path, or null otherwise.\n */\n CompoundWrite.prototype.getCompleteNode = function (path) {\n var rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path_1.Path.relativePath(rootmost.path, path));\n }\n else {\n return null;\n }\n };\n /**\n * Returns all children that are guaranteed to be a complete overwrite.\n *\n * @return {!Array.} A list of all complete children.\n */\n CompoundWrite.prototype.getCompleteChildren = function () {\n var children = [];\n var node = this.writeTree_.value;\n if (node != null) {\n // If it's a leaf node, it has no children; so nothing to do.\n if (!node.isLeafNode()) {\n node.forEachChild(PriorityIndex_1.PRIORITY_INDEX, function (childName, childNode) {\n children.push(new Node_1.NamedNode(childName, childNode));\n });\n }\n }\n else {\n this.writeTree_.children.inorderTraversal(function (childName, childTree) {\n if (childTree.value != null) {\n children.push(new Node_1.NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n };\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n CompoundWrite.prototype.childCompoundWrite = function (path) {\n if (path.isEmpty()) {\n return this;\n }\n else {\n var shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree_1.ImmutableTree(shadowingNode));\n }\n else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\n }\n };\n /**\n * Returns true if this CompoundWrite is empty and therefore does not modify any nodes.\n * @return {boolean} Whether this CompoundWrite is empty\n */\n CompoundWrite.prototype.isEmpty = function () {\n return this.writeTree_.isEmpty();\n };\n /**\n * Applies this CompoundWrite to a node. The node is returned with all writes from this CompoundWrite applied to the\n * node\n * @param {!Node} node The node to apply this CompoundWrite to\n * @return {!Node} The node with all writes applied\n */\n CompoundWrite.prototype.apply = function (node) {\n return CompoundWrite.applySubtreeWrite_(Path_1.Path.Empty, this.writeTree_, node);\n };\n /**\n * @type {!CompoundWrite}\n */\n CompoundWrite.Empty = new CompoundWrite(new ImmutableTree_1.ImmutableTree(null));\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n CompoundWrite.applySubtreeWrite_ = function (relativePath, writeTree, node) {\n if (writeTree.value != null) {\n // Since there a write is always a leaf, we're done here\n return node.updateChild(relativePath, writeTree.value);\n }\n else {\n var priorityWrite_1 = null;\n writeTree.children.inorderTraversal(function (childKey, childTree) {\n if (childKey === '.priority') {\n // Apply priorities at the end so we don't update priorities for either empty nodes or forget\n // to apply priorities to empty nodes that are later filled\n util_2.assert(childTree.value !== null, 'Priority writes must always be leaf nodes');\n priorityWrite_1 = childTree.value;\n }\n else {\n node = CompoundWrite.applySubtreeWrite_(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite_1 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite_1);\n }\n return node;\n }\n };\n return CompoundWrite;\n}());\nexports.CompoundWrite = CompoundWrite;\n\n//# sourceMappingURL=CompoundWrite.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/CompoundWrite.js\n// module id = 96\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nvar SnapshotHolder = /** @class */ (function () {\n function SnapshotHolder() {\n this.rootNode_ = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n SnapshotHolder.prototype.getNode = function (path) {\n return this.rootNode_.getChild(path);\n };\n SnapshotHolder.prototype.updateSnapshot = function (path, newSnapshotNode) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n };\n return SnapshotHolder;\n}());\nexports.SnapshotHolder = SnapshotHolder;\n\n//# sourceMappingURL=SnapshotHolder.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/SnapshotHolder.js\n// module id = 97\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"./util/util\");\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nvar AuthTokenProvider = /** @class */ (function () {\n /**\n * @param {!FirebaseApp} app_\n */\n function AuthTokenProvider(app_) {\n this.app_ = app_;\n }\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n AuthTokenProvider.prototype.getToken = function (forceRefresh) {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(null, \n // .catch\n function (error) {\n // TODO: Need to figure out all the cases this is raised and whether\n // this makes sense.\n if (error && error.code === 'auth/token-not-initialized') {\n util_1.log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n }\n else {\n return Promise.reject(error);\n }\n });\n };\n AuthTokenProvider.prototype.addTokenChangeListener = function (listener) {\n // TODO: We might want to wrap the listener and call it with no args to\n // avoid a leaky abstraction, but that makes removing the listener harder.\n this.app_['INTERNAL']['addAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.removeTokenChangeListener = function (listener) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n };\n AuthTokenProvider.prototype.notifyForInvalidToken = function () {\n var errorMessage = 'Provided authentication credentials for the app named \"' +\n this.app_.name +\n '\" are invalid. This usually indicates your app was not ' +\n 'initialized correctly. ';\n if ('credential' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"credential\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else if ('serviceAccount' in this.app_.options) {\n errorMessage +=\n 'Make sure the \"serviceAccount\" property provided to initializeApp() ' +\n 'is authorized to access the specified \"databaseURL\" and is from the correct ' +\n 'project.';\n }\n else {\n errorMessage +=\n 'Make sure the \"apiKey\" and \"databaseURL\" properties provided to ' +\n 'initializeApp() match the values provided for your app at ' +\n 'https://console.firebase.google.com/.';\n }\n util_1.warn(errorMessage);\n };\n return AuthTokenProvider;\n}());\nexports.AuthTokenProvider = AuthTokenProvider;\n\n//# sourceMappingURL=AuthTokenProvider.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/AuthTokenProvider.js\n// module id = 98\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nvar StatsCollection = /** @class */ (function () {\n function StatsCollection() {\n this.counters_ = {};\n }\n StatsCollection.prototype.incrementCounter = function (name, amount) {\n if (amount === void 0) { amount = 1; }\n if (!util_2.contains(this.counters_, name))\n this.counters_[name] = 0;\n this.counters_[name] += amount;\n };\n StatsCollection.prototype.get = function () {\n return util_1.deepCopy(this.counters_);\n };\n return StatsCollection;\n}());\nexports.StatsCollection = StatsCollection;\n\n//# sourceMappingURL=StatsCollection.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsCollection.js\n// module id = 99\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar StatsListener_1 = require(\"./StatsListener\");\n// Assuming some apps may have a short amount of time on page, and a bulk of firebase operations probably\n// happen on page load, we try to report our first set of stats pretty quickly, but we wait at least 10\n// seconds to try to ensure the Firebase connection is established / settled.\nvar FIRST_STATS_MIN_TIME = 10 * 1000;\nvar FIRST_STATS_MAX_TIME = 30 * 1000;\n// We'll continue to report stats on average every 5 minutes.\nvar REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n/**\n * @constructor\n */\nvar StatsReporter = /** @class */ (function () {\n /**\n * @param collection\n * @param server_\n */\n function StatsReporter(collection, server_) {\n this.server_ = server_;\n this.statsToReport_ = {};\n this.statsListener_ = new StatsListener_1.StatsListener(collection);\n var timeout = FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n StatsReporter.prototype.includeStat = function (stat) {\n this.statsToReport_[stat] = true;\n };\n StatsReporter.prototype.reportStats_ = function () {\n var _this = this;\n var stats = this.statsListener_.get();\n var reportedStats = {};\n var haveStatsToReport = false;\n util_1.forEach(stats, function (stat, value) {\n if (value > 0 && util_1.contains(_this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n // queue our next run.\n util_2.setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));\n };\n return StatsReporter;\n}());\nexports.StatsReporter = StatsReporter;\n\n//# sourceMappingURL=StatsReporter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/stats/StatsReporter.js\n// module id = 100\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../util/util\");\n/**\n * The event queue serves a few purposes:\n * 1. It ensures we maintain event order in the face of event callbacks doing operations that result in more\n * events being queued.\n * 2. raiseQueuedEvents() handles being called reentrantly nicely. That is, if in the course of raising events,\n * raiseQueuedEvents() is called again, the \"inner\" call will pick up raising events where the \"outer\" call\n * left off, ensuring that the events are still raised synchronously and in order.\n * 3. You can use raiseEventsAtPath and raiseEventsForChangedPath to ensure only relevant previously-queued\n * events are raised synchronously.\n *\n * NOTE: This can all go away if/when we move to async events.\n *\n * @constructor\n */\nvar EventQueue = /** @class */ (function () {\n function EventQueue() {\n /**\n * @private\n * @type {!Array.}\n */\n this.eventLists_ = [];\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n this.recursionDepth_ = 0;\n }\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n EventQueue.prototype.queueEvents = function (eventDataList) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n var currList = null;\n for (var i = 0; i < eventDataList.length; i++) {\n var eventData = eventDataList[i];\n var eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones)\n * for the specified path.\n *\n * It is assumed that the new events are all for the specified path.\n *\n * @param {!Path} path The path to raise events for.\n * @param {!Array.} eventDataList The new events to raise.\n */\n EventQueue.prototype.raiseEventsAtPath = function (path, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.equals(path);\n });\n };\n /**\n * Queues the specified events and synchronously raises all events (including previously queued ones) for\n * locations related to the specified change path (i.e. all ancestors and descendants).\n *\n * It is assumed that the new events are all related (ancestor or descendant) to the specified path.\n *\n * @param {!Path} changedPath The path to raise events for.\n * @param {!Array.} eventDataList The events to raise\n */\n EventQueue.prototype.raiseEventsForChangedPath = function (changedPath, eventDataList) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_(function (eventPath) {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n };\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n EventQueue.prototype.raiseQueuedEventsMatchingPredicate_ = function (predicate) {\n this.recursionDepth_++;\n var sentAll = true;\n for (var i = 0; i < this.eventLists_.length; i++) {\n var eventList = this.eventLists_[i];\n if (eventList) {\n var eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n }\n else {\n sentAll = false;\n }\n }\n }\n if (sentAll) {\n this.eventLists_ = [];\n }\n this.recursionDepth_--;\n };\n return EventQueue;\n}());\nexports.EventQueue = EventQueue;\n/**\n * @param {!Path} path\n * @constructor\n */\nvar EventList = /** @class */ (function () {\n function EventList(path_) {\n this.path_ = path_;\n /**\n * @type {!Array.}\n * @private\n */\n this.events_ = [];\n }\n /**\n * @param {!Event} eventData\n */\n EventList.prototype.add = function (eventData) {\n this.events_.push(eventData);\n };\n /**\n * Iterates through the list and raises each event\n */\n EventList.prototype.raise = function () {\n for (var i = 0; i < this.events_.length; i++) {\n var eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n var eventFn = eventData.getEventRunner();\n if (util_1.logger) {\n util_1.log('event: ' + eventData.toString());\n }\n util_1.exceptionGuard(eventFn);\n }\n }\n };\n /**\n * @return {!Path}\n */\n EventList.prototype.getPath = function () {\n return this.path_;\n };\n return EventList;\n}());\nexports.EventList = EventList;\n\n//# sourceMappingURL=EventQueue.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/EventQueue.js\n// module id = 101\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_1 = require(\"@firebase/util\");\n/**\n * @extends {EventEmitter}\n */\nvar VisibilityMonitor = /** @class */ (function (_super) {\n __extends(VisibilityMonitor, _super);\n function VisibilityMonitor() {\n var _this = _super.call(this, ['visible']) || this;\n var hidden;\n var visibilityChange;\n if (typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined') {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n }\n else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n }\n else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n }\n else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\n }\n // Initially, we always assume we are visible. This ensures that in browsers\n // without page visibility support or in cases where we are never visible\n // (e.g. chrome extension), we act as if we are visible, i.e. don't delay\n // reconnects\n _this.visible_ = true;\n if (visibilityChange) {\n document.addEventListener(visibilityChange, function () {\n var visible = !document[hidden];\n if (visible !== _this.visible_) {\n _this.visible_ = visible;\n _this.trigger('visible', visible);\n }\n }, false);\n }\n return _this;\n }\n VisibilityMonitor.getInstance = function () {\n return new VisibilityMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n VisibilityMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n };\n return VisibilityMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.VisibilityMonitor = VisibilityMonitor;\n\n//# sourceMappingURL=VisibilityMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/VisibilityMonitor.js\n// module id = 102\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar EventEmitter_1 = require(\"./EventEmitter\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Monitors online state (as reported by window.online/offline events).\n *\n * The expectation is that this could have many false positives (thinks we are online\n * when we're not), but no false negatives. So we can safely use it to determine when\n * we definitely cannot reach the internet.\n *\n * @extends {EventEmitter}\n */\nvar OnlineMonitor = /** @class */ (function (_super) {\n __extends(OnlineMonitor, _super);\n function OnlineMonitor() {\n var _this = _super.call(this, ['online']) || this;\n _this.online_ = true;\n // We've had repeated complaints that Cordova apps can get stuck \"offline\", e.g.\n // https://forum.ionicframework.com/t/firebase-connection-is-lost-and-never-come-back/43810\n // It would seem that the 'online' event does not always fire consistently. So we disable it\n // for Cordova.\n if (typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !util_2.isMobileCordova()) {\n window.addEventListener('online', function () {\n if (!_this.online_) {\n _this.online_ = true;\n _this.trigger('online', true);\n }\n }, false);\n window.addEventListener('offline', function () {\n if (_this.online_) {\n _this.online_ = false;\n _this.trigger('online', false);\n }\n }, false);\n }\n return _this;\n }\n OnlineMonitor.getInstance = function () {\n return new OnlineMonitor();\n };\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n OnlineMonitor.prototype.getInitialEvent = function (eventType) {\n util_1.assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n };\n /**\n * @return {boolean}\n */\n OnlineMonitor.prototype.currentlyOnline = function () {\n return this.online_;\n };\n return OnlineMonitor;\n}(EventEmitter_1.EventEmitter));\nexports.OnlineMonitor = OnlineMonitor;\n\n//# sourceMappingURL=OnlineMonitor.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/OnlineMonitor.js\n// module id = 103\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar BrowserPollConnection_1 = require(\"./BrowserPollConnection\");\nvar WebSocketConnection_1 = require(\"./WebSocketConnection\");\nvar util_1 = require(\"../core/util/util\");\n/**\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\n * lifecycle.\n *\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\n * they are available.\n * @constructor\n */\nvar TransportManager = /** @class */ (function () {\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\n * @const\n * @type {!Array.}\n */\n get: function () {\n return [BrowserPollConnection_1.BrowserPollConnection, WebSocketConnection_1.WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection_1.WebSocketConnection && WebSocketConnection_1.WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection_1.WebSocketConnection.previouslyFailed();\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n util_1.warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection_1.WebSocketConnection];\n }\n else {\n var transports_1 = (this.transports_ = []);\n util_1.each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\n * initial transport to use\n */\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n }\n else {\n throw new Error('No transports available');\n }\n };\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n }\n else {\n return null;\n }\n };\n return TransportManager;\n}());\nexports.TransportManager = TransportManager;\n\n//# sourceMappingURL=TransportManager.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/TransportManager.js\n// module id = 104\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"../../core/util/util\");\n/**\n * This class ensures the packets from the server arrive in order\n * This class takes data from the server and ensures it gets passed into the callbacks in order.\n * @constructor\n */\nvar PacketReceiver = /** @class */ (function () {\n /**\n * @param onMessage_\n */\n function PacketReceiver(onMessage_) {\n this.onMessage_ = onMessage_;\n this.pendingResponses = [];\n this.currentResponseNum = 0;\n this.closeAfterResponse = -1;\n this.onClose = null;\n }\n PacketReceiver.prototype.closeAfter = function (responseNum, callback) {\n this.closeAfterResponse = responseNum;\n this.onClose = callback;\n if (this.closeAfterResponse < this.currentResponseNum) {\n this.onClose();\n this.onClose = null;\n }\n };\n /**\n * Each message from the server comes with a response number, and an array of data. The responseNumber\n * allows us to ensure that we process them in the right order, since we can't be guaranteed that all\n * browsers will respond in the same order as the requests we sent\n * @param {number} requestNum\n * @param {Array} data\n */\n PacketReceiver.prototype.handleResponse = function (requestNum, data) {\n var _this = this;\n this.pendingResponses[requestNum] = data;\n var _loop_1 = function () {\n var toProcess = this_1.pendingResponses[this_1.currentResponseNum];\n delete this_1.pendingResponses[this_1.currentResponseNum];\n var _loop_2 = function (i) {\n if (toProcess[i]) {\n util_1.exceptionGuard(function () {\n _this.onMessage_(toProcess[i]);\n });\n }\n };\n for (var i = 0; i < toProcess.length; ++i) {\n _loop_2(i);\n }\n if (this_1.currentResponseNum === this_1.closeAfterResponse) {\n if (this_1.onClose) {\n this_1.onClose();\n this_1.onClose = null;\n }\n return \"break\";\n }\n this_1.currentResponseNum++;\n };\n var this_1 = this;\n while (this.pendingResponses[this.currentResponseNum]) {\n var state_1 = _loop_1();\n if (state_1 === \"break\")\n break;\n }\n };\n return PacketReceiver;\n}());\nexports.PacketReceiver = PacketReceiver;\n\n//# sourceMappingURL=PacketReceiver.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/realtime/polling/PacketReceiver.js\n// module id = 105\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"./util/util\");\nvar util_3 = require(\"@firebase/util\");\nvar util_4 = require(\"@firebase/util\");\nvar util_5 = require(\"@firebase/util\");\nvar ServerActions_1 = require(\"./ServerActions\");\n/**\n * An implementation of ServerActions that communicates with the server via REST requests.\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\n * persistent connection (using WebSockets or long-polling)\n */\nvar ReadonlyRestClient = /** @class */ (function (_super) {\n __extends(ReadonlyRestClient, _super);\n /**\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\n * @param {AuthTokenProvider} authTokenProvider_\n * @implements {ServerActions}\n */\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n _this.log_ = util_2.logWrapper('p:rest:');\n /**\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\n * that's been removed. :-/\n *\n * @private {!Object.}\n */\n _this.listens_ = {};\n return _this;\n }\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n }\n else {\n util_1.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier());\n // Mark this listener so we can tell if it's removed.\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error, result) {\n var data = result;\n if (error === 404) {\n data = null;\n error = null;\n }\n if (error === null) {\n _this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n if (util_4.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n if (!error) {\n status_1 = 'ok';\n }\n else if (error == 401) {\n status_1 = 'permission_denied';\n }\n else {\n status_1 = 'rest_error:' + error;\n }\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {\n // no-op since we just always call getToken.\n };\n /**\n * Performs a REST request to the given path, with the provided query string parameters,\n * and any auth credentials we have.\n *\n * @param {!string} pathString\n * @param {!Object.} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n if (queryStringParameters === void 0) { queryStringParameters = {}; }\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') +\n _this.repoInfo_.host +\n pathString +\n '?' +\n util_5.querystring(queryStringParameters);\n _this.log_('Sending REST request for ' + url);\n var xhr = new XMLHttpRequest();\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n var res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util_3.jsonEval(xhr.responseText);\n }\n catch (e) {\n util_2.warn('Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText);\n }\n callback(null, res);\n }\n else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n util_2.warn('Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status);\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n };\n return ReadonlyRestClient;\n}(ServerActions_1.ServerActions));\nexports.ReadonlyRestClient = ReadonlyRestClient;\n\n//# sourceMappingURL=ReadonlyRestClient.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/ReadonlyRestClient.js\n// module id = 106\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar util_2 = require(\"../util/util\");\nvar KeyIndex_1 = require(\"../snap/indexes/KeyIndex\");\nvar PriorityIndex_1 = require(\"../snap/indexes/PriorityIndex\");\nvar ValueIndex_1 = require(\"../snap/indexes/ValueIndex\");\nvar PathIndex_1 = require(\"../snap/indexes/PathIndex\");\nvar IndexedFilter_1 = require(\"./filter/IndexedFilter\");\nvar LimitedFilter_1 = require(\"./filter/LimitedFilter\");\nvar RangedFilter_1 = require(\"./filter/RangedFilter\");\nvar util_3 = require(\"@firebase/util\");\n/**\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\n * user-facing API level, so it is not done here.\n * @constructor\n */\nvar QueryParams = /** @class */ (function () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PriorityIndex_1.PRIORITY_INDEX;\n }\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\n * @return {boolean} True if it would return from left.\n */\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n }\n else {\n return (this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT);\n }\n };\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n QueryParams.prototype.getIndexStartValue = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\n * Only valid to call if hasStart() returns true.\n * Returns the starting key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexStartName = function () {\n util_1.assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n }\n else {\n return util_2.MIN_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n QueryParams.prototype.getIndexEndValue = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\n * Only valid to call if hasEnd() returns true.\n * Returns the end key name for the range defined by these query parameters\n * @return {!string}\n */\n QueryParams.prototype.getIndexEndName = function () {\n util_1.assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n }\n else {\n return util_2.MAX_NAME;\n }\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n QueryParams.prototype.getLimit = function () {\n util_1.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\n * @return {!Index}\n */\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @return {!QueryParams}\n * @private\n */\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexStartValue_ = indexValue;\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n }\n else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n };\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n newParams.indexEndValue_ = indexValue;\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n }\n else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n };\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\n * @return {!Object}\n */\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n }\n else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n }\n // For now, priority index is the default, so we only specify if it's some other index\n if (this.index_ !== PriorityIndex_1.PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\n * @return {boolean}\n */\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PriorityIndex_1.PRIORITY_INDEX;\n };\n /**\n * @return {!NodeFilter}\n */\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter_1.IndexedFilter(this.getIndex());\n }\n else if (this.hasLimit()) {\n return new LimitedFilter_1.LimitedFilter(this);\n }\n else {\n return new RangedFilter_1.RangedFilter(this);\n }\n };\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n if (this.isDefault()) {\n return qs;\n }\n var orderBy;\n if (this.index_ === PriorityIndex_1.PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n }\n else if (this.index_ === ValueIndex_1.VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n }\n else if (this.index_ === KeyIndex_1.KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n }\n else {\n util_1.assert(this.index_ instanceof PathIndex_1.PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = util_3.stringify(orderBy);\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util_3.stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util_3.stringify(this.indexStartName_);\n }\n }\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util_3.stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util_3.stringify(this.indexEndName_);\n }\n }\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n }\n else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n return qs;\n };\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}());\nexports.QueryParams = QueryParams;\n\n//# sourceMappingURL=QueryParams.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/QueryParams.js\n// module id = 107\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RangedFilter_1 = require(\"./RangedFilter\");\nvar ChildrenNode_1 = require(\"../../snap/ChildrenNode\");\nvar Node_1 = require(\"../../snap/Node\");\nvar util_1 = require(\"@firebase/util\");\nvar Change_1 = require(\"../Change\");\n/**\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\n *\n * @constructor\n * @implements {NodeFilter}\n */\nvar LimitedFilter = /** @class */ (function () {\n /**\n * @param {!QueryParams} params\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter_1.RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new Node_1.NamedNode(key, newChild))) {\n newChild = ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n }\n else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n }\n else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n }\n else {\n if (this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode_1.ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n var iterator = void 0;\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n }\n else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n var count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n }\n else {\n inRange =\n this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n }\n else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n }\n else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCompare_1(b, a); };\n }\n else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n var count = 0;\n var foundStartPost = false;\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n }\n else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\n * @inheritDoc\n */\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\n * @param {!Node} snap\n * @param {string} childKey\n * @param {!Node} childSnap\n * @param {!CompleteChildSource} source\n * @param {?ChildChangeAccumulator} changeAccumulator\n * @return {!Node}\n * @private\n */\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n cmp = function (a, b) { return indexCmp_1(b, a); };\n }\n else {\n cmp = this.index_.getCompare();\n }\n var oldEventCache = snap;\n util_1.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new Node_1.NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n while (nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n }\n else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(childKey, oldChildSnap));\n }\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(nextChild.name, nextChild.node));\n }\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n }\n else {\n return newEventCache;\n }\n }\n }\n else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n }\n else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change_1.Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change_1.Change.childAddedChange(childKey, childSnap));\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n }\n else {\n return snap;\n }\n }\n else {\n return snap;\n }\n };\n return LimitedFilter;\n}());\nexports.LimitedFilter = LimitedFilter;\n\n//# sourceMappingURL=LimitedFilter.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/view/filter/LimitedFilter.js\n// module id = 108\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Reference_1 = require(\"../api/Reference\");\nvar DataSnapshot_1 = require(\"../api/DataSnapshot\");\nvar Path_1 = require(\"./util/Path\");\nvar Tree_1 = require(\"./util/Tree\");\nvar PriorityIndex_1 = require(\"./snap/indexes/PriorityIndex\");\nvar util_2 = require(\"./util/util\");\nvar ServerValues_1 = require(\"./util/ServerValues\");\nvar validation_1 = require(\"./util/validation\");\nvar util_3 = require(\"@firebase/util\");\nvar nodeFromJSON_1 = require(\"./snap/nodeFromJSON\");\nvar ChildrenNode_1 = require(\"./snap/ChildrenNode\");\nvar Repo_1 = require(\"./Repo\");\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n/**\n * @enum {number}\n */\nvar TransactionStatus;\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\";\n // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\";\n // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\";\n // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\";\n // Temporary state used to mark transactions that need to be aborted.\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus = exports.TransactionStatus || (exports.TransactionStatus = {}));\n/**\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\n * @type {number}\n * @const\n * @private\n */\nRepo_1.Repo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\n * Setup the transaction data structures\n * @private\n */\nRepo_1.Repo.prototype.transactions_init_ = function () {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.>}\n * @private\n */\n this.transactionQueueTree_ = new Tree_1.Tree();\n};\n/**\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\n *\n * @param {!Path} path Path at which to do transaction.\n * @param {function(*):*} transactionUpdate Update callback.\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\n */\nRepo_1.Repo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path);\n // Add a watch to make sure we get server updates.\n var valueCallback = function () { };\n var watchRef = new Reference_1.Reference(this, path);\n watchRef.on('value', valueCallback);\n var unwatcher = function () {\n watchRef.off('value', valueCallback);\n };\n // Initialize transaction.\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: util_2.LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n };\n // Run transaction initially.\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot_1.DataSnapshot(transaction.currentInputSnapshot, new Reference_1.Reference(this, transaction.path), PriorityIndex_1.PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n }\n else {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path);\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue);\n // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n var priorityForNode = void 0;\n if (typeof newVal === 'object' &&\n newVal !== null &&\n util_3.contains(newVal, '.priority')) {\n priorityForNode = util_3.safeGet(newVal, '.priority');\n util_1.assert(validation_1.isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.');\n }\n else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON_1.nodeFromJSON(newVal, priorityForNode);\n var newNode = ServerValues_1.resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\nRepo_1.Repo.prototype.getLatestState_ = function (path, excludeSets) {\n return (this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode_1.ChildrenNode.EMPTY_NODE);\n};\n/**\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\n * complete.\n *\n * Externally it's called with no arguments, but it calls itself recursively with a particular\n * transactionQueueTree node to recurse through the tree.\n *\n * @param {Tree.>=} node transactionQueueTree node to start at.\n * @private\n */\nRepo_1.Repo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n if (node === void 0) { node = this.transactionQueueTree_; }\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util_1.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) { return transaction.status === TransactionStatus.RUN; });\n // If they're all run (and not sent), we can send them. Else, we must wait.\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n }\n else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\n *\n * @param {!Path} path The location of the queue.\n * @param {!Array.} queue Queue of transactions under the specified location.\n * @private\n */\nRepo_1.Repo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this;\n // Mark transactions as sent and increment retry count!\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util_1.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path_1.Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(relativePath /**@type {!Node} */, txn.currentOutputSnapshotRaw);\n }\n var dataToSend = snapToSend.val(true);\n var pathToSend = path;\n // Send the put.\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n var events = [];\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference_1.Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot_1.DataSnapshot(node, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n queue[i].unwatcher();\n }\n // Now remove the completed transactions.\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path));\n // There may be pending transactions that we can now send.\n _this.sendReadyTransactions_();\n _this.eventQueue_.raiseEventsForChangedPath(path, events);\n // Finally, trigger onComplete callbacks.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else\n queue[i].status = TransactionStatus.RUN;\n }\n }\n else {\n util_2.warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\n * Finds all transactions dependent on the data at changedPath and reruns them.\n *\n * Should be called any time cached data changes.\n *\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\n * be raised for.\n *\n * @param {!Path} changedPath The path in mergedData that changed.\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\n *\n * @param {Array.} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\nRepo_1.Repo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n var events = [];\n // Ignore all of the sets we're going to re-run.\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path_1.Path.relativePath(path, transaction.path);\n var abortTransaction = false, abortReason = void 0;\n util_1.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo_1.Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validation_1.validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON_1.nodeFromJSON(newData);\n var hasExplicitPriority = typeof newData === 'object' &&\n newData != null &&\n util_3.contains(newData, '.priority');\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = ServerValues_1.resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_();\n // Mutates setsToIgnore in place\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n }\n else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference_1.Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n var lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot_1.DataSnapshot(lastInput, ref, PriorityIndex_1.PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n }\n else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n }\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n // Now fire callbacks, now that we're in a good, known state.\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\n/**\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\n * the node for the given path if there are no pending transactions on any ancestor.\n *\n * @param {!Path} path The location to start at.\n * @return {!Tree.>} The rootmost node with a transaction.\n * @private\n */\nRepo_1.Repo.prototype.getAncestorTransactionNode_ = function (path) {\n var front;\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n var transactionNode = this.transactionQueueTree_;\n while ((front = path.getFront()) !== null &&\n transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n return transactionNode;\n};\n/**\n * Builds the queue of all transactions at or below the specified transactionNode.\n *\n * @param {!Tree.>} transactionNode\n * @return {Array.} The generated queue.\n * @private\n */\nRepo_1.Repo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\nRepo_1.Repo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n var nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\nRepo_1.Repo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n var queue = node.getValue();\n if (queue) {\n var to = 0;\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\n * since we consider them incompatible with transactions.\n *\n * @param {!Path} path Path for which we want to abort related transactions.\n * @return {!Path}\n * @private\n */\nRepo_1.Repo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\nRepo_1.Repo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n var events = [];\n var lastSent = -1;\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n }\n else if (queue[i].status === TransactionStatus.SENT) {\n util_1.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i;\n // Mark transaction for abort when it comes back.\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n }\n else {\n util_1.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort');\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n }\n else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (var i = 0; i < callbacks.length; i++) {\n util_2.exceptionGuard(callbacks[i]);\n }\n }\n};\n\n//# sourceMappingURL=Repo_transaction.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/Repo_transaction.js\n// module id = 109\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar util_1 = require(\"@firebase/util\");\nvar Path_1 = require(\"./Path\");\nvar util_2 = require(\"@firebase/util\");\n/**\n * Node in a Tree.\n */\nvar TreeNode = /** @class */ (function () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n return TreeNode;\n}());\nexports.TreeNode = TreeNode;\n/**\n * A light-weight tree, traversable by path. Nodes can have both values and children.\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\n * children.\n */\nvar Tree = /** @class */ (function () {\n /**\n * @template T\n * @param {string=} name_ Optional name of the node.\n * @param {Tree=} parent_ Optional parent node.\n * @param {TreeNode=} node_ Optional node to wrap.\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) { name_ = ''; }\n if (parent_ === void 0) { parent_ = null; }\n if (node_ === void 0) { node_ = new TreeNode(); }\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\n * Returns a sub-Tree for the given path.\n *\n * @param {!(string|Path)} pathObj Path to look up.\n * @return {!Tree.} Tree for path.\n */\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path_1.Path ? pathObj : new Path_1.Path(pathObj);\n var child = this, next;\n while ((next = path.getFront()) !== null) {\n var childNode = util_2.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n return child;\n };\n /**\n * Returns the data associated with this tree node.\n *\n * @return {?T} The data or null if no data exists.\n */\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n Tree.prototype.setValue = function (value) {\n util_1.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\n * @return {boolean} Whether the tree has any children.\n */\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\n * Calls action for each child of this tree node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n util_2.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\n * Does a depth-first traversal of this node's descendants, calling action for each one.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\n * false.\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\n * parent.\n */\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst)\n action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n if (includeSelf && childrenFirst)\n action(this);\n };\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.)} action Action to be called on each parent; return\n * true to abort.\n * @param {boolean=} includeSelf Whether to call action on this node as well.\n * @return {boolean} true if the action callback returned true.\n */\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n node = node.parent();\n }\n return false;\n };\n /**\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\n * is found, action is called on it and traversal does not continue inside the node.\n * Action is *not* called on this node.\n *\n * @param {function(!Tree.)} action Action to be called for each child.\n */\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null)\n action(child);\n else\n child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n Tree.prototype.path = function () {\n return new Path_1.Path(this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_);\n };\n /**\n * @return {string} The name of the tree node.\n */\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null)\n this.parent_.updateChild_(this.name_, this);\n };\n /**\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\n *\n * @param {string} childName The name of the child to update.\n * @param {!Tree.} child The child to update.\n * @private\n */\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util_2.contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n }\n else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n return Tree;\n}());\nexports.Tree = Tree;\n\n//# sourceMappingURL=Tree.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/core/util/Tree.js\n// module id = 110\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar WebSocketConnection_1 = require(\"../realtime/WebSocketConnection\");\nvar BrowserPollConnection_1 = require(\"../realtime/BrowserPollConnection\");\n/**\n * INTERNAL methods for internal-use only (tests, etc.).\n *\n * Customers shouldn't use these or else should be aware that they could break at any time.\n *\n * @const\n */\nexports.forceLongPolling = function () {\n WebSocketConnection_1.WebSocketConnection.forceDisallow();\n BrowserPollConnection_1.BrowserPollConnection.forceAllow();\n};\nexports.forceWebSockets = function () {\n BrowserPollConnection_1.BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\nexports.isWebSocketsAvailable = function () {\n return WebSocketConnection_1.WebSocketConnection['isAvailable']();\n};\nexports.setSecurityDebugCallback = function (ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nexports.stats = function (ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nexports.statsIncrementCounter = function (ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nexports.dataUpdateCount = function (ref) {\n return ref.repo.dataUpdateCount;\n};\nexports.interceptServerData = function (ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n//# sourceMappingURL=internal.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/internal.js\n// module id = 111\n// module chunks = 0","\"use strict\";\n/**\n * Copyright 2017 Google Inc.\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 */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar RepoInfo_1 = require(\"../core/RepoInfo\");\nvar PersistentConnection_1 = require(\"../core/PersistentConnection\");\nvar RepoManager_1 = require(\"../core/RepoManager\");\nvar Connection_1 = require(\"../realtime/Connection\");\nexports.DataConnection = PersistentConnection_1.PersistentConnection;\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\nPersistentConnection_1.PersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\nPersistentConnection_1.PersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nexports.RealTimeConnection = Connection_1.Connection;\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexports.hijackHash = function (newHash) {\n var oldPut = PersistentConnection_1.PersistentConnection.prototype.put;\n PersistentConnection_1.PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n return function () {\n PersistentConnection_1.PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexports.ConnectionTarget = RepoInfo_1.RepoInfo;\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexports.queryIdentifier = function (query) {\n return query.queryIdentifier();\n};\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexports.listens = function (firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexports.forceRestClient = function (forceRestClient) {\n RepoManager_1.RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n//# sourceMappingURL=test_access.js.map\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// ../database/dist/cjs/src/api/test_access.js\n// module id = 112\n// module chunks = 0"],"sourceRoot":""}