{"version":3,"sources":["webpack:///firebase-app.js","webpack:/webpack/bootstrap 6cb149ba8cc0d40c95b7","webpack:///src/app/errors.ts","webpack:///src/utils/promise.ts","webpack:///src/app/subscribe.ts","webpack:///src/utils/globalScope.ts","webpack:///(webpack)/buildin/global.js","webpack:///node_modules/process/browser.js","webpack:///src/utils/deep_copy.ts","webpack:///src/utils/shims.ts","webpack:///node_modules/promise-polyfill/promise.js","webpack:///node_modules/timers-browserify/main.js","webpack:///node_modules/setimmediate/setImmediate.js","webpack:///src/app/firebase_app.ts","webpack:///src/app.ts","firebase-auth.js","webpack:///firebase-database.js","webpack:///src/utils/assert.ts","webpack:///src/utils/crypt.ts","webpack:///src/utils/hash.ts","webpack:///src/utils/Sha1.ts","webpack:///src/database/core/util/util.ts","webpack:///src/utils/obj.ts","webpack:///src/database/core/util/Path.ts","webpack:///src/database/core/snap/indexes/PriorityIndex.ts","webpack:///src/database/core/snap/ChildrenNode.ts","webpack:///src/database/core/snap/Node.ts","webpack:///src/utils/json.ts","webpack:///src/utils/validation.ts","webpack:///src/database/core/util/validation.ts","webpack:///src/database/core/operation/Operation.ts","webpack:///src/utils/environment.ts","webpack:///src/database/core/view/Change.ts","webpack:///src/database/core/snap/indexes/KeyIndex.ts","webpack:///src/database/core/snap/nodeFromJSON.ts","webpack:///src/utils/constants.ts","webpack:///src/database/core/storage/DOMStorageWrapper.ts","webpack:///src/database/core/storage/MemoryStorage.ts","webpack:///src/database/core/storage/storage.ts","webpack:///src/database/realtime/Constants.ts","webpack:///src/database/core/snap/indexes/Index.ts","webpack:///src/database/core/snap/LeafNode.ts","webpack:///src/database/core/util/SortedMap.ts","webpack:///src/database/core/operation/AckUserWrite.ts","webpack:///src/database/core/operation/ListenComplete.ts","webpack:///src/database/core/operation/Overwrite.ts","webpack:///src/database/core/operation/Merge.ts","webpack:///src/database/core/CompoundWrite.ts","webpack:///src/database/core/WriteTree.ts","webpack:///src/database/core/SyncTree.ts","webpack:///src/database/core/SnapshotHolder.ts","webpack:///src/database/core/AuthTokenProvider.ts","webpack:///src/database/core/stats/StatsListener.ts","webpack:///src/database/core/stats/StatsReporter.ts","webpack:///src/database/core/view/EventQueue.ts","webpack:///src/utils/util.ts","webpack:///src/database/core/ReadonlyRestClient.ts","webpack:///src/database/core/Repo.ts","webpack:///src/utils/utf8.ts","webpack:///src/database/api/onDisconnect.ts","webpack:///src/database/api/TransactionResult.ts","webpack:///src/database/core/util/NextPushId.ts","webpack:///src/database/core/view/filter/RangedFilter.ts","webpack:///src/database/core/view/filter/LimitedFilter.ts","webpack:///src/database/core/view/QueryParams.ts","webpack:///src/database/api/Reference.ts","webpack:///src/database/core/util/ImmutableTree.ts","webpack:///src/database/core/view/filter/IndexedFilter.ts","webpack:///src/database/core/stats/StatsCollection.ts","webpack:///src/database/core/stats/StatsManager.ts","webpack:///src/database/core/Repo_transaction.ts","webpack:///src/database/core/util/Tree.ts","webpack:///src/database/core/RepoManager.ts","webpack:///src/database/api/Database.ts","webpack:///src/database/core/util/libs/parser.ts","webpack:///src/database/core/RepoInfo.ts","webpack:///src/database/core/view/Event.ts","webpack:///src/database/core/view/EventRegistration.ts","webpack:///src/database/api/Query.ts","webpack:///src/database/core/snap/snap.ts","webpack:///src/database/core/snap/indexes/ValueIndex.ts","webpack:///src/database/core/snap/IndexMap.ts","webpack:///src/database/core/snap/childSet.ts","webpack:///src/database/core/snap/comparators.ts","webpack:///src/database/core/snap/indexes/PathIndex.ts","webpack:///src/database/api/DataSnapshot.ts","webpack:///src/database/core/util/ServerValues.ts","webpack:///src/database/core/SparseSnapshotTree.ts","webpack:///src/database/core/util/CountedSet.ts","webpack:///src/database/core/view/CacheNode.ts","webpack:///src/database/core/view/ViewCache.ts","webpack:///src/database/core/view/ChildChangeAccumulator.ts","webpack:///src/database/core/view/CompleteChildSource.ts","webpack:///src/database/core/view/ViewProcessor.ts","webpack:///src/database/core/view/EventGenerator.ts","webpack:///src/database/core/view/View.ts","webpack:///src/database/core/SyncPoint.ts","webpack:///src/database/core/util/EventEmitter.ts","webpack:///src/database/core/util/VisibilityMonitor.ts","webpack:///src/database/core/util/OnlineMonitor.ts","webpack:///src/utils/jwt.ts","webpack:///src/database/core/PersistentConnection.ts","webpack:///src/database/realtime/TransportManager.ts","webpack:///src/database/realtime/Connection.ts","webpack:///src/database/realtime/polling/PacketReceiver.ts","webpack:///src/database/realtime/BrowserPollConnection.ts","webpack:///src/database/realtime/WebSocketConnection.ts","webpack:///src/database/core/ServerActions.ts","webpack:///src/database.ts","webpack:///(webpack)/buildin/harmony-module.js","webpack:///src/database/api/internal.ts","webpack:///src/database/api/test_access.ts","webpack:///firebase-messaging.js","webpack:///src/messaging/helpers/array-buffer-to-base64.ts","webpack:///src/messaging.ts","webpack:///src/messaging/models/errors.ts","webpack:///src/messaging/models/fcm-details.ts","webpack:///src/messaging/models/token-manager.ts","webpack:///src/messaging/controllers/controller-interface.ts","webpack:///src/messaging/models/worker-page-message.ts","webpack:///src/messaging/models/default-sw.ts","webpack:///src/messaging/controllers/window-controller.ts","webpack:///src/messaging/controllers/sw-controller.ts","webpack:///firebase-storage.js","webpack:///src/storage/implementation/error.ts","webpack:///src/storage/implementation/string.ts","webpack:///src/storage/implementation/taskenums.ts","webpack:///src/storage/implementation/object.ts","webpack:///src/storage/implementation/promise_external.ts","webpack:///src/storage/implementation/type.ts","webpack:///src/storage/implementation/json.ts","webpack:///src/storage/implementation/path.ts","webpack:///src/storage/implementation/url.ts","webpack:///src/storage/implementation/metadata.ts","webpack:///src/storage/implementation/args.ts","webpack:///src/storage/implementation/fs.ts","webpack:///src/storage/implementation/array.ts","webpack:///src/storage/implementation/requests.ts","webpack:///src/storage/implementation/async.ts","webpack:///src/storage/implementation/backoff.ts","webpack:///src/storage/implementation/request.ts","webpack:///src/storage.ts","webpack:///src/storage/implementation/constants.ts","webpack:///src/storage/implementation/xhrio.ts","webpack:///src/storage/implementation/xhrio_network.ts","webpack:///src/storage/implementation/xhriopool.ts","webpack:///src/storage/implementation/location.ts","webpack:///src/storage/implementation/blob.ts","webpack:///src/storage/implementation/requestinfo.ts","webpack:///src/storage/implementation/observer.ts","webpack:///src/storage/tasksnapshot.ts","webpack:///src/storage/task.ts","webpack:///src/storage/reference.ts","webpack:///src/storage/implementation/failrequest.ts","webpack:///src/storage/implementation/requestmap.ts","webpack:///src/storage/implementation/authwrapper.ts","webpack:///src/storage/service.ts"],"names":["firebase","window","self","modules","__webpack_require__","moduleId","installedModules","exports","module","i","l","call","parentJsonpFunction","chunkIds","moreModules","executeModules","chunkId","result","resolves","length","installedChunks","push","Object","prototype","hasOwnProperty","shift","s","4","e","onScriptComplete","script","onerror","onload","clearTimeout","timeout","chunk","Error","undefined","installedChunkData","Promise","resolve","promise","reject","head","document","getElementsByTagName","createElement","type","charset","async","nc","setAttribute","src","p","setTimeout","appendChild","m","c","d","name","getter","o","defineProperty","configurable","enumerable","get","n","__esModule","object","property","oe","err","console","error","24","__webpack_exports__","ErrorFactory","ERROR_NAME","captureStackTrace","FirebaseError","code","message","this","create","err_1","apply","arguments","stack","constructor","service","serviceName","errors","pattern","data","template","fullCode","replace","match","key","value","prop","slice","3","PromiseImpl","Deferred","attachDummyErrorHandler","__WEBPACK_IMPORTED_MODULE_0__utils_globalScope__","wrapCallback","opt_nodeCallback","meta","opt_value","catch","31","createSubscribe","executor","onNoObservers","proxy","ObserverProxy","subscribe","bind","implementsAnyMethods","obj","methods","_typeof","_i","methods_1","method","noop","__WEBPACK_IMPORTED_MODULE_0__utils_promise__","Symbol","iterator","_this","observers","unsubscribes","observerCount","task","finalized","then","next","forEachObserver","observer","close","complete","nextOrObserver","unsub","unsubscribeOne","finalError","fn","sendOne","32","global","globalScope","scope","Function","33","g","eval","34","defaultSetTimout","defaultClearTimeout","runTimeout","fun","cachedSetTimeout","runClearTimeout","marker","cachedClearTimeout","cleanUpNextTick","draining","currentQueue","queue","concat","queueIndex","drainQueue","len","run","Item","array","process","nextTick","args","Array","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","35","deepCopy","deepExtend","target","source","Date","dateValue","getTime","patchProperty","56","findIndex","predicate","TypeError","thisArg","k","kValue","find","57","setImmediate","root","_state","_handled","_value","_deferreds","doResolve","handle","deferred","_immediateFn","cb","onFulfilled","onRejected","ret","newValue","finale","_unhandledRejectionFn","Handler","done","reason","ex","setTimeoutFunc","prom","all","arr","res","val","remaining","race","values","warn","_setImmediateFn","_setUnhandledRejectionFn","58","Timeout","id","clearFn","_id","_clearFn","setInterval","clearInterval","unref","ref","enroll","item","msecs","_idleTimeoutId","_idleTimeout","unenroll","_unrefActive","active","_onTimeout","clearImmediate","59","callback","tasksByHandle","nextHandle","registerImmediate","runIfPresent","currentlyRunningATask","doc","attachTo","getPrototypeOf","toString","postMessage","importScripts","postMessageIsAsynchronous","oldOnMessage","onmessage","messagePrefix","Math","random","onGlobalMessage","event","indexOf","addEventListener","attachEvent","MessageChannel","channel","port1","port2","html","documentElement","onreadystatechange","removeChild","9","createFirebaseNamespace","removeApp","callAppHooks","apps_","app","DEFAULT_ENTRY_NAME","contains","initializeApp","options","firebase_app_FirebaseAppImpl","namespace","getApps","keys","map","registerService","createService","serviceProperties","appHook","allowMultipleInstances","factories","appHooks","forEach","serviceNamespace","appArg","deep_copy","_getService","extendNamespace","props","eventName","factoryName","useAsService","useService","apps","SDK_VERSION","INTERNAL","appErrors","tokenListeners","FirebaseAppImpl","firebase_","isDeleted_","services_","name_","options_","getUid","getToken","addAuthTokenListener","removeAuthTokenListener","filter","listener","checkDestroyed_","delete","services","serviceKey","instanceKey","instanceIdentifier","instanceSpecifier","extendApp","log","firebase_app_errors","no-app","bad-app-name","duplicate-app","app-deleted","duplicate-service","sa-not-supported","invalid-app-argument","default","webpackJsonpFirebase","assert","assertionError","__WEBPACK_IMPORTED_MODULE_0__constants__","assertion","utils_obj","stringToByteArray","str","output","charCodeAt","byteArrayToString","bytes","String","fromCharCode","base64","_","O","S","T","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","opt_webSafe","isArray","init_","byteToCharMap","byteToCharMapWebSafe_","byteToCharMap_","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","join","encodeString","btoa","decodeString","decodeStringToByteArray","charToByteMap","charToByteMapWebSafe_","charToByteMap_","charAt","haveByte4","byte4","N","Hash","blockSize","__extends","extendStatics","setPrototypeOf","__proto__","b","__","Sha1","_super","chain_","buf_","W_","pad_","inbuf_","total_","reset","compress_","buf","opt_offset","W","t","f","a","update","opt_length","lengthMinusBlock","inbuf","digest","totalBits","j","utf8","json","storage","environment","LUIDGenerator","util_base64Encode","util_base64Decode","util_sha1","logger","util_enableLogging","util_log","logWrapper","fatal","warnIfPageIsSecure","isInvalidJSONNumber","util_executeWhenDOMReady","MIN_NAME","MAX_NAME","nameCompare","stringCompare","util_requireKey","util_ObjectToUniqueKey","splitStringBySize","util_each","util_doubleToIEEE754String","isChromeExtensionContentScript","isWindowsStoreApp","errorForServerCode","exceptionGuard","beingCrawled","setTimeoutNonBlocking","BufferImpl","utf8Bytes","sha1","sha1Bytes","util_buildLogMessage_","buildLogMessage_","var_args","firstLog_","logger_","persistent","set","remove","prefix","location","protocol","Number","POSITIVE_INFINITY","NEGATIVE_INFINITY","readyState","called_1","wrappedFn_1","body","floor","aAsInt","tryParseInt","bAsInt","ObjectToUniqueKey","sort","segsize","dataSegs","substring","v","ln","bits","abs","pow","min","LN2","round","reverse","hexByteString","hexByte","parseInt","substr","toLowerCase","test","href","Windows","UI","query","path","toUpperCase","INTEGER_REGEXP_","RegExp","intVal","search","time","safeGet","clone","isEmpty","getCount","findKey","findValue","getAnyKey","getValues","every","extend","objTo","objFrom","rv","opt_obj","opt_this","Path","ValidationPath","__WEBPACK_IMPORTED_MODULE_0__util__","__WEBPACK_IMPORTED_MODULE_1__utils_utf8__","pathOrString","pieceNum","pieces_","split","copyTo","pieceNum_","getFront","getLength","popFront","getBack","pathString","toUrlEncodedString","encodeURIComponent","begin","parent","pieces","child","childPathObj","childPieces","relativePath","outerPath","innerPath","outer","inner","comparePaths","left","right","leftKeys","rightKeys","cmp","equals","other","errorPrefix_","parts_","byteLength_","max","checkValid_","pop","last","MAX_PATH_LENGTH_BYTES","MAX_PATH_DEPTH","toErrorString","setNodeFromJSON","nodeFromJSON","setMaxNode","MAX_NODE","PRIORITY_INDEX","__WEBPACK_IMPORTED_MODULE_0__Index__","__WEBPACK_IMPORTED_MODULE_1__util_util__","__WEBPACK_IMPORTED_MODULE_2__Node__","__WEBPACK_IMPORTED_MODULE_3__LeafNode__","PriorityIndex","compare","aPriority","node","getPriority","bPriority","indexCmp","compareTo","isDefinedOn","indexedValueChanged","oldNode","newNode","minPost","MIN","maxPost","makePost","indexValue","priorityNode","ChildrenNode","EMPTY_NODE","__WEBPACK_IMPORTED_MODULE_0__utils_assert__","__WEBPACK_IMPORTED_MODULE_2__util_SortedMap__","__WEBPACK_IMPORTED_MODULE_3__Node__","__WEBPACK_IMPORTED_MODULE_4__snap__","__WEBPACK_IMPORTED_MODULE_5__indexes_PriorityIndex__","__WEBPACK_IMPORTED_MODULE_6__indexes_KeyIndex__","__WEBPACK_IMPORTED_MODULE_7__IndexMap__","__WEBPACK_IMPORTED_MODULE_8__LeafNode__","__WEBPACK_IMPORTED_MODULE_9__comparators__","children_","priorityNode_","indexMap_","lazyHash_","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","hash","toHash_1","childHash","getPredecessorChildName","index","idx","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","indexDefinition","minKey","getFirstChild","getLastChildName","getLastChild","action","inorderTraversal","wrappedNode","getIterator","getIteratorFrom","startPost","Wrap","peek","getNext","getReverseIterator","getReverseIteratorFrom","endPost","withIndex","hasIndex","addIndex","isIndexed","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","defineProperties","MAX","__EMPTY_NODE","__childrenNodeConstructor","NamedNode","jsonEval","stringify","JSON","parse","errorPrefix","fnName","argumentNumber","optional","argName","validateArgCount","validateCallback","validateContextObject","minCount","maxCount","argCount","argError","context","isValidPriority","validateFirebaseDataArg","validateFirebaseData","validateFirebaseMergeDataArg","validatePriority","validateEventType","validateKey","validatePathString","validateRootPathString","validateWritablePath","validateUrl","validateBoolean","__WEBPACK_IMPORTED_MODULE_0__Path__","__WEBPACK_IMPORTED_MODULE_1__utils_obj__","__WEBPACK_IMPORTED_MODULE_2__util__","__WEBPACK_IMPORTED_MODULE_3__utils_validation__","__WEBPACK_IMPORTED_MODULE_4__utils_utf8__","INVALID_KEY_REGEX_","INVALID_PATH_REGEX_","isValidKey","isValidPathString","isValidRootPathString","priority","path_","hasDotValue_1","hasActualChild_1","validateFirebaseMergePaths","mergePaths","curPath","prevPath","eventType","parsedUrl","repoInfo","host","bool","OperationType","OperationSource","fromUser","fromServer","queryId","tagged","User","Server","forServerTaggedQuery","isMobileCordova","isReactNative","isNodeSdk","getUA","navigator","NODE_CLIENT","NODE_ADMIN","Change","snapshotNode","oldSnap","prevName","valueChange","snapshot","VALUE","childAddedChange","childKey","CHILD_ADDED","childRemovedChange","CHILD_REMOVED","childChangedChange","newSnapshot","oldSnapshot","CHILD_CHANGED","childMovedChange","CHILD_MOVED","KeyIndex","KEY_INDEX","__WEBPACK_IMPORTED_MODULE_1__Node__","__WEBPACK_IMPORTED_MODULE_2__util_util__","__WEBPACK_IMPORTED_MODULE_3__utils_assert__","__WEBPACK_IMPORTED_MODULE_0__ChildrenNode__","__WEBPACK_IMPORTED_MODULE_4__utils_assert__","jsonLeaf","__WEBPACK_IMPORTED_MODULE_1__LeafNode__","USE_HINZE","node_1","jsonObj_1","__WEBPACK_IMPORTED_MODULE_3__utils_obj__","childData","children_1","childrenHavePriority_1","hinzeJsonObj_1","childSet","__WEBPACK_IMPORTED_MODULE_5__childSet__","__WEBPACK_IMPORTED_MODULE_6__comparators__","sortedChildSet","__WEBPACK_IMPORTED_MODULE_8__indexes_PriorityIndex__","getCompare",".priority","CONSTANTS","DOMStorageWrapper_DOMStorageWrapper","DOMStorageWrapper","domStorage_","prefix_","removeItem","prefixedName_","setItem","storedVal","getItem","MemoryStorage_MemoryStorage","MemoryStorage","cache_","isInMemoryStorage","PersistentStorage","SessionStorage","storage_createStoragefor","domStorageName","domStorage","PROTOCOL_VERSION","VERSION_PARAM","TRANSPORT_SESSION_PARAM","REFERER_PARAM","FORGE_REF","FORGE_DOMAIN","LAST_SESSION_PARAM","WEBSOCKET","LONG_POLLING","Index","__WEBPACK_IMPORTED_MODULE_0__Node__","oldWrapped","newWrapped","LeafNode","__WEBPACK_IMPORTED_MODULE_2__snap__","value_",".value","getValue","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","LLRBNode","SortedMap","SortedMapIterator","startKey","comparator","isReverse_","resultGenerator_","nodeStack_","hasNext","color","RED","copy","reverseTraversal","min_","fixUp_","removeMin_","isRed_","moveRedLeft_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","nr","checkMaxDepth_","blackDepth","check_","BLACK","LLRBEmptyNode","comparator_","root_","rightParent","resultGenerator","ServerValues","SparseSnapshotTree","util","Operation","AckUserWrite_AckUserWrite","AckUserWrite","affectedTree","revert","ACK_USER_WRITE","operationForChild","children","childTree","subtree","Empty","ImmutableTree","ListenComplete_ListenComplete","ListenComplete","LISTEN_COMPLETE","Overwrite_Overwrite","Overwrite","snap","OVERWRITE","Merge_Merge","Merge","MERGE","SyncPoint","Node","CompoundWrite_CompoundWrite","CompoundWrite","writeTree_","addWrite","rootmost","findRootMostValueAndPath","rootMostPath","setTree","addWrites","updates","newWrite","removeWrite","hasCompleteWrite","getCompleteNode","getCompleteChildren","childCompoundWrite","shadowingNode","applySubtreeWrite_","writeTree","priorityWrite_1","WriteTree_WriteTree","WriteTree","visibleWrites_","allWrites_","lastWriteId_","childWrites","WriteTreeRef","addOverwrite","writeId","visible","addMerge","changedChildren","getWrite","record","writeToRemove","splice","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","getCompleteWriteData","calcCompleteEventCache","treePath","completeServerCache","writeIdsToExclude","includeHiddenWrites","merge","write","mergeAtPath","layerTree_","layeredCache","subMerge","calcCompleteEventChildren","completeServerChildren","completeChildren","topLevelSet","childSnap","merge_1","calcEventCacheAfterServerOverwrite","childPath","existingEventSnap","existingServerSnap","childMerge","calcCompleteChild","isCompleteForChild","getNode","shadowingWrite","calcIndexedSlice","completeServerData","toIterate","nodes","iter","writeRecord","DefaultFilter_","writes","treeRoot","compoundWrite","writePath","deepNode","treePath_","existingServerCache","SyncTree_SyncTree","SyncTree","listenProvider_","syncPointTree_","pendingWriteTree_","tagToQueryMap_","queryToTagMap_","applyUserOverwrite","newData","applyOperationToSyncPoints_","applyUserMerge","changeTree","fromObject","ackUserWrite","affectedTree_1","applyServerOverwrite","applyServerMerge","applyListenComplete","applyTaggedQueryOverwrite","tag","queryKey","queryKeyForTag_","r","parseQueryKey_","queryPath","op","applyTaggedOperation_","applyTaggedQueryMerge","applyTaggedListenComplete","addEventRegistration","eventRegistration","serverCache","foundAncestorDefaultView","foreachOnPath","pathToSyncPoint","sp","getCompleteServerCache","hasCompleteView","syncPoint","serverCacheComplete","foreachChild","childSyncPoint","completeCache","viewAlreadyExists","viewExistsForQuery","getQueryParams","loadsAllData","makeQueryKey_","getNextQueryTag_","writesCache","events","view","viewForQuery","setupListener_","removeEventRegistration","cancelError","maybeSyncPoint","cancelEvents","queryIdentifier","removedAndEvents","removed","removingDefault","covered","findOnPath","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","getQuery","createListenerForView_","startListening","queryForListening_","tagForQuery_","hashFn","onComplete","stopListening","queryToRemove","tagToRemove","removeTags_","pathSoFar","fold","maybeChildSyncPoint","childMap","getCompleteView","views_1","getQueryViews","childViews","queries","removedQuery","removedQueryKey","removedQueryTag","isDefault","getRef","queriesToStop","queries_1","childQueries","queryToStop","getServerCache","status","splitIndex","nextQueryTag_","operation","applyOperation","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","childServerCache","childWritesCache","SnapshotHolder_SnapshotHolder","SnapshotHolder","rootNode_","updateSnapshot","newSnapshotNode","AuthTokenProvider_AuthTokenProvider","AuthTokenProvider","app_","forceRefresh","addTokenChangeListener","removeTokenChangeListener","notifyForInvalidToken","errorMessage","StatsManager","StatsListener_StatsListener","StatsListener","collection_","last_","newStats","delta","stat","FIRST_STATS_MIN_TIME","FIRST_STATS_MAX_TIME","StatsReporter_StatsReporter","StatsReporter","collection","server_","statsToReport_","statsListener_","reportStats_","includeStat","stats","reportedStats","haveStatsToReport","reportStats","EventQueue","eventLists_","recursionDepth_","queueEvents","eventDataList","currList","eventData","eventPath","getPath","EventQueue_EventList","add","raiseEventsAtPath","raiseQueuedEventsMatchingPredicate_","raiseEventsForChangedPath","changedPath","sentAll","eventList","raise","EventList","events_","eventFn","getEventRunner","PersistentConnection","util_querystring","querystringParams","params","arrayVal","ServerActions","ReadonlyRestClient_ReadonlyRestClient","ReadonlyRestClient","repoInfo_","onDataUpdate_","authTokenProvider_","log_","listens_","getListenId_","listen","currentHashFn","listenId","thisListen","queryStringParamaters","toRestQueryStringParameters","restRequest_","status_1","unlisten","refreshAuthToken","token","queryStringParameters","authTokenData","authToken","accessToken","url","secure","xhr","XMLHttpRequest","responseText","open","send","Database","Repo_Repo","Repo","forceRestClient","dataUpdateCount","eventQueue_","nextWriteId_","interceptServerDataCallback_","onDisconnect_","persistentConnection_","authTokenProvider","stats_","getCollection","onConnectStatus_","authOverride","onServerInfoUpdate_","statsReporter_","getOrCreateReporter","transactions_init_","infoData_","infoSyncTree_","infoEvents","updateInfo_","serverSyncTree_","serverTime","offsetNode","offset","generateServerValues","timestamp","isMerge","taggedChildren","raw","taggedSnap","affectedPath","rerunTransactions_","interceptServerData_","connectStatus","runOnDisconnectEvents_","getNextWriteId_","setWithPriority","newVal","serverValues","newNodeUnresolved","put","errorReason","success","clearEvents","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","resolvedOnDisconnectTree","forEachTree","onDisconnectCancel","forget","onDisconnectSet","onDisconnectPut","remember","onDisconnectSetWithPriority","onDisconnectUpdate","onDisconnectMerge","addEventCallbackForQuery","removeEventCallbackForQuery","interrupt","resume","showDelta","longestName","reduce","previousValue","currentValue","statsIncrementCounter","metric","incrementCounter","__database","stringLength","__WEBPACK_IMPORTED_MODULE_0__assert__","out","high","validation","util_validation","utils_promise","onDisconnect_OnDisconnect","OnDisconnect","repo_","cancel","objectToMerge","newObjectToMerge","TransactionResult_TransactionResult","TransactionResult","committed","toJSON","nextPushId","PUSH_CHARS","lastPushTime","lastRandChars","now","duplicateTime","timeStampChars","Query","ValueIndex","PathIndex","IndexedFilter","RangedFilter_RangedFilter","RangedFilter","indexedFilter_","getIndex","index_","startPost_","getStartPost_","endPost_","getEndPost_","getStartPost","getEndPost","matches","newChild","optChangeAccumulator","updateFullNode","newSnap","filtered","filtersNodes","getIndexedFilter","hasStart","startName","getIndexStartName","getIndexStartValue","hasEnd","endName","getIndexEndName","getIndexEndValue","LimitedFilter_LimitedFilter","LimitedFilter","rangedFilter_","limit_","getLimit","reverse_","isViewFromLeft","fullLimitUpdateChild_","inRange","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","oldEventCache","newChildNamedNode","windowBoundary","oldChildSnap","nextChild","getChildAfterChild","compareNext","trackChildChange","newEventCache","QueryParams_QueryParams","QueryParams","limitSet_","startSet_","startNameSet_","endSet_","endNameSet_","viewFrom_","indexStartValue_","indexStartName_","indexEndValue_","indexEndName_","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","hasLimit","hasAnchoredLimit","copy_","limit","newLimit","newParams","limitToFirst","limitToLast","VIEW_FROM_RIGHT","startAt","endAt","orderBy","getQueryObject","WIRE_PROTOCOL_CONSTANTS","INDEX_START_VALUE","INDEX_START_NAME","INDEX_END_VALUE","INDEX_END_NAME","LIMIT","viewFrom","VIEW_FROM","INDEX","getNodeFilter","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","VALUE_INDEX","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","DEFAULT","Reference_Reference","Reference","repo","getKey","getParent","parentPath","getRoot","databaseProp","database","transaction","transactionUpdate","applyLocally","promiseComplete","startTransaction","setPriority","thennablePushRef","pushRef","onDisconnect","__referenceConstructor","emptyChildrenSingleton","__WEBPACK_IMPORTED_MODULE_0__SortedMap__","__WEBPACK_IMPORTED_MODULE_1__Path__","EmptyChildren","tree","findRootMostMatchingPathAndValue","childExistingPathAndValue","toSet","newTree","fold_","accum","findOnPath_","pathToFollow","foreachOnPath_","currentRelativePath","foreach","foreach_","__WEBPACK_IMPORTED_MODULE_1__Change__","__WEBPACK_IMPORTED_MODULE_2__snap_ChildrenNode__","__WEBPACK_IMPORTED_MODULE_3__snap_indexes_PriorityIndex__","oldChild","StatsCollection_StatsCollection","StatsCollection","counters_","amount","StatsManager_StatsManager","hashString","collections_","creatorFunction","reporters_","TransactionStatus","parser","DataSnapshot","TreeNode","childCount","Tree_Tree","Tree","parent_","node_","subTree","pathObj","setValue","updateParents_","clear","hasChildren","forEachDescendant","includeSelf","childrenFirst","forEachAncestor","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","valueCallback","watchRef","unwatcher","order","retryCount","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","nodeQueue","priorityForNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","buildTransactionQueue_","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","callbacks","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","txnsToRerun","q","abortTransaction","currentNode","newDataNode","hasExplicitPriority","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","from","abortTransactionsOnNode_","lastSent","RepoManager_RepoManager","_staticInstance","RepoManager","repos_","useRestClient_","getInstance","appName","dbUrl","databaseFromApp","createRepo","deleteRepo","appRepos","toURLString","__WEBPACK_IMPORTED_MODULE_0__core_util_util__","__WEBPACK_IMPORTED_MODULE_1__core_util_libs_parser__","__WEBPACK_IMPORTED_MODULE_2__core_util_Path__","__WEBPACK_IMPORTED_MODULE_3__utils_promise__","__WEBPACK_IMPORTED_MODULE_4__Reference__","__WEBPACK_IMPORTED_MODULE_5__core_Repo__","__WEBPACK_IMPORTED_MODULE_6__core_RepoManager__","__WEBPACK_IMPORTED_MODULE_7__utils_validation__","__WEBPACK_IMPORTED_MODULE_8__core_util_validation__","DatabaseInternals","checkDeleted_","refFromURL","apiName","parsedURL","goOffline","goOnline","ServerValue","TIMESTAMP",".sv","decodePath","pathStringDecoded","piece","decodeURIComponent","parseRepoInfo","__WEBPACK_IMPORTED_MODULE_1__RepoInfo__","dataURL","parseURL","subdomain","domain","webSocketOnly","scheme","port","colonInd","slashInd","parts","RepoInfo","__WEBPACK_IMPORTED_MODULE_2__storage_storage__","__WEBPACK_IMPORTED_MODULE_3__realtime_Constants__","persistenceKey","internalHost","needsQueryParam","isCacheableHost","isDemoHost","isCustomHost","updateHost","newHost","connectionURL","connURL","pairs","utils_validation","Event_DataEvent","DataEvent","getEventType","exportVal","CancelEvent","EventRegistration_ValueEventRegistration","ValueEventRegistration","callback_","cancelCallback_","context_","respondsTo","createEvent","change","ctx","cancelCB_1","cb_1","createCancelEvent","hasAnyCallback","EventRegistration_ChildEventRegistration","ChildEventRegistration","callbacks_","eventToCheck","cancelCB_2","cb_2","otherCount","otherKey","thisKey","Query_Query","queryParams_","orderByCalled_","validateQueryEndpoints_","startNode","endNode","tooManyArgsError","wrongArgTypeError","validateLimit_","validateNoPreviousOrderByCall_","cancelCallbackOrContext","getCancelAndContextArgs_","onValueEvent","onChildEvent","cancelCallback","container","userCallback","cancelOrContext","firstCall","onceCallback","orderByChild","parsedPath","orderByKey","orderByPriority","orderByValue","equalTo","queryObject","isEqual","sameRepo","samePath","sameQueryIdentifier","priorityHashText","validatePriorityNode","__WEBPACK_IMPORTED_MODULE_2__utils_obj__","__WEBPACK_IMPORTED_MODULE_3__nodeFromJSON__","valueNode","IndexMap","_defaultIndexMap","__WEBPACK_IMPORTED_MODULE_1__childSet__","__WEBPACK_IMPORTED_MODULE_4__indexes_PriorityIndex__","__WEBPACK_IMPORTED_MODULE_5__indexes_KeyIndex__","fallbackObject","indexes_","indexSet_","indexKey","sortedMap","existingChildren","childList","sawIndexedValue","newIndex","indexName","newIndexSet","newIndexes","indexedChildren","existingSnap","buildChildSet","__WEBPACK_IMPORTED_MODULE_0__util_SortedMap__","LOG_2","Base12Num","num","current_","mask","bits_","nextBitIsOne","keyFn","mapSortFn","buildBalancedTree","low","middle","base12","buildPennant","chunkSize","attachPennant","pennant","isOne","NAME_ONLY_COMPARATOR","__WEBPACK_IMPORTED_MODULE_0__util_util__","NAME_COMPARATOR","__WEBPACK_IMPORTED_MODULE_2__Index__","__WEBPACK_IMPORTED_MODULE_3__ChildrenNode__","__WEBPACK_IMPORTED_MODULE_4__Node__","__WEBPACK_IMPORTED_MODULE_5__nodeFromJSON__","indexPath_","extractChild","aChild","bChild","__WEBPACK_IMPORTED_MODULE_0__utils_validation__","__WEBPACK_IMPORTED_MODULE_1__core_util_validation__","__WEBPACK_IMPORTED_MODULE_3__core_snap_indexes_PriorityIndex__","ref_","exists","childPathString","childRef","generateWithValues","resolveDeferredValueTree","resolveDeferredValueSnapshot","__WEBPACK_IMPORTED_MODULE_2__SparseSnapshotTree__","__WEBPACK_IMPORTED_MODULE_3__snap_LeafNode__","__WEBPACK_IMPORTED_MODULE_4__snap_nodeFromJSON__","__WEBPACK_IMPORTED_MODULE_5__snap_indexes_PriorityIndex__","resolveDeferredValue","resolvedTree","rawPri","leafNode","childrenNode","__WEBPACK_IMPORTED_MODULE_0__util_Path__","__WEBPACK_IMPORTED_MODULE_1__snap_indexes_PriorityIndex__","__WEBPACK_IMPORTED_MODULE_2__util_CountedSet__","self_1","prefixPath","func","each","CountedSet","__WEBPACK_IMPORTED_MODULE_0__utils_obj__","CacheNode","fullyInitialized_","filtered_","isFullyInitialized","isFiltered","isCompleteForPath","ViewCache_ViewCache","ViewCache","eventCache_","serverCache_","updateEventSnap","eventSnap","updateServerSnap","serverSnap","getEventCache","getCompleteEventSnap","getCompleteServerSnap","ChildChangeAccumulator_ChildChangeAccumulator","ChildChangeAccumulator","changeMap_","oldChange","oldType","getChanges","NoCompleteChildSource_","getCompleteChild","NO_COMPLETE_CHILD_SOURCE","CompleteChildSource_WriteTreeCompleteChildSource","WriteTreeCompleteChildSource","writes_","viewCache_","optCompleteServerCache_","serverNode","ProcessorResult","viewCache","changes","ViewProcessor_ViewProcessor","ViewProcessor","filter_","assertIndexed","oldViewCache","newViewCache","filterServerNode","accumulator","overwrite","applyUserOverwrite_","applyServerOverwrite_","applyUserMerge_","applyServerMerge_","revertUserWrite_","ackUserWrite_","listenComplete_","maybeAddValueEvent_","isLeafOrEmpty","oldCompleteSnap","generateEventCacheAfterServerEvent_","changePath","oldEventSnap","completeEventChildren","completeNode","oldEventNode","updatedPriority","childChangePath","newEventChild","eventChildUpdate","changedSnap","newServerCache","oldServerSnap","serverFilter","newServerNode","newEventSnap","cacheHasChild_","curViewCache","applyMerge_","viewMergeTree","serverChild","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","serverChildren","EventGenerator_EventGenerator","EventGenerator","query_","generateEventsForChanges","eventCache","eventRegistrations","moves","generateEventsForType_","registrations","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","registration","aWrapped","bWrapped","View_View","View","initialViewCache","eventRegistrations_","indexFilter","processor_","initialServerCache","initialEventCache","eventGenerator_","cache","path_1","maybeEvent","existing","generateEventsForChanges_","getInitialEvents","initialChanges","SyncPoint_SyncPoint","views_","optCompleteServerCache","events_1","eventCacheComplete","hadCompleteView","viewQueryId","EventEmitter_EventEmitter","EventEmitter","allowedEvents_","listeners_","trigger","validateEventType_","getInitialEvent","et","VisibilityMonitor_VisibilityMonitor","VisibilityMonitor","hidden","visibilityChange","visible_","OnlineMonitor___extends","OnlineMonitor_OnlineMonitor","OnlineMonitor","online_","currentlyOnline","jwt_decode","header","claims","signature","isValidFormat","decoded","isAdmin","Connection","constants","PersistentConnection_PersistentConnection","PersistentConnection__typeof","PersistentConnection___extends","RECONNECT_MIN_DELAY","RECONNECT_MAX_DELAY_DEFAULT","authOverride_","nextPersistentConnectionId_","interruptReasons_","outstandingPuts_","outstandingPutCount_","onDisconnectRequestQueue_","connected_","reconnectDelay_","maxReconnectDelay_","securityDebugCallback_","lastSessionId","establishConnectionTimer_","requestCBHash_","requestNumber_","realtime_","authToken_","forceTokenRefresh_","invalidAuthTokenCount_","firstConnection_","lastConnectionAttemptTime_","lastConnectionEstablishedTime_","scheduleConnect_","onVisible_","onOnline_","sendRequest","onResponse","curReqNum","msg","listenSpec","sendListen_","req","payload","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","tryAuth","reduceReconnectDelayIfAdminCredential_","credential","token_1","authMethod","requestData","cred","onAuthRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","request","response","putInternal","sendPut_","queued","onDataMessage_","reqNum","onDataPush_","onListenRevoked_","onSecurityDebugPacket_","onReady_","sessionId","handleTimestamp_","sendConnectStats_","restoreState_","establishConnection_","online","onRealtimeDisconnect_","cancelSentTransactions_","shouldReconnect_","timeSinceLastConnectSucceeded","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage_1","onReady_1","onDisconnect_1","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","sendRequestFn","serverTimeOffset","normalizedPathString","statusCode","explanation","clientName","Constants","BrowserPollConnection","WebSocketConnection","TransportManager_TransportManager","TransportManager","initTransports_","isWebSocketsAvailable","isSkipPollConnection","previouslyFailed","transports_","transports_1","ALL_TRANSPORTS","transport","initialTransport","upgradeTransport","Connection_Connection","onMessage_","onKill_","connectionCount","pendingDataMessages","state_","transportManager_","start_","conn","conn_","nextTransportId_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeout_ms","healthyTimeout_","bytesReceived","markConnectionHealthy","bytesSent","everConnected","onConnectionLost_","onSecondaryConnectionLost_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","sendData_","tryCleanupConnection","connId","onSecondaryControl_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","proceedWithUpgrade_","start","onControl_","onPrimaryResponse_","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","ts","h","onConnectionEstablished_","tryStartUpgrade_","startUpgrade_","onMessage","closeConnections_","PacketReceiver_PacketReceiver","PacketReceiver","pendingResponses","currentResponseNum","closeAfterResponse","onClose","closeAfter","responseNum","handleResponse","requestNum","this_1","toProcess","BrowserPollConnection_BrowserPollConnection","FIREBASE_LONGPOLL_COMMAND_CB_NAME","FIREBASE_LONGPOLL_DATA_CB_NAME","transportSessionId","everConnected_","urlFn","curSegmentNum","myPacketOrderer","isClosed_","connectTimeoutTimer_","onClosed_","scriptTagHolder","BrowserPollConnection_FirebaseIFrameScriptHolder","command","arg1","arg2","incrementIncomingBytes_","password","sendNewPolls","pN","urlParams","uniqueCallbackIdentifier","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow","forceAllow_","forceDisallow","forceDisallow_","isAvailable","shutdown_","myDisconnFrame","dataStr","base64data","MAX_URL_DATA_SIZE","enqueueSegment","pw","style","display","FirebaseIFrameScriptHolder","commandCB","onMessageCB","outstandingRequests","pendingSegs","currentSerial","myIFrame","createIFrame_","iframeContents","iframe","contentWindow","contentDocument","alive","innerHTML","myID","myPW","theURL","nodeRestRequest","newRequest_","curDataString","theSeg","seg","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","readyStateCB","loadCB","doNodeLongPoll","newScript_1","rstate","parentNode","__WEBPACK_IMPORTED_MODULE_0__app__","__WEBPACK_IMPORTED_MODULE_1__utils_assert__","__WEBPACK_IMPORTED_MODULE_2__core_util_util__","__WEBPACK_IMPORTED_MODULE_3__core_stats_StatsManager__","__WEBPACK_IMPORTED_MODULE_4__Constants__","__WEBPACK_IMPORTED_MODULE_5__utils_constants__","__WEBPACK_IMPORTED_MODULE_6__core_storage_storage__","__WEBPACK_IMPORTED_MODULE_7__utils_json__","__WEBPACK_IMPORTED_MODULE_8__utils_environment__","WebSocketImpl","MozWebSocket","WebSocket","keepaliveTimer","frames","totalFrames","connectionURL_","device","headers","User-Agent","platform","origin","mySock","onopen","onclose","handleIncomingFrame","isOldAndroid","userAgent","oldAndroidRegex","oldAndroidMatch","parseFloat","appendFrame_","fullMess","jsonMess","handleNewFrameCount_","frameCount","extractFrameCount_","isNaN","mess","resetKeepAlive","remainingData","sendString_","responsesRequiredToBeHealthy","healthyTimeout","registerDatabase","instance","unused","__WEBPACK_IMPORTED_MODULE_5__database_core_RepoManager__","__WEBPACK_IMPORTED_MODULE_3__database_api_Reference__","__WEBPACK_IMPORTED_MODULE_2__database_api_Query__","__WEBPACK_IMPORTED_MODULE_1__database_api_Database__","enableLogging","__WEBPACK_IMPORTED_MODULE_4__database_core_util_util__","__WEBPACK_IMPORTED_MODULE_6__database_api_internal__","TEST_ACCESS","__WEBPACK_IMPORTED_MODULE_7__database_api_test_access__","originalModule","webpackPolyfill","forceLongPolling","forceWebSockets","setSecurityDebugCallback","interceptServerData","__WEBPACK_IMPORTED_MODULE_0__realtime_WebSocketConnection__","__WEBPACK_IMPORTED_MODULE_1__realtime_BrowserPollConnection__","DataConnection","RealTimeConnection","hijackHash","ConnectionTarget","listens","__WEBPACK_IMPORTED_MODULE_0__core_RepoInfo__","__WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__","__WEBPACK_IMPORTED_MODULE_2__core_RepoManager__","__WEBPACK_IMPORTED_MODULE_3__realtime_Connection__","simpleListen","echo","onEcho","newHash","oldPut","opt_onComplete","opt_hash","firebaseRef","_forceRestClient","61","toBase64","arrayBuffer","uint8Version","Uint8Array","registerMessaging","factoryMethod","sw_controller","window_controller","namespaceExports","Messaging","_a","CODES","AVAILABLE_IN_WINDOW","AVAILABLE_IN_SW","SHOULD_BE_INHERITED","BAD_SENDER_ID","INCORRECT_GCM_SENDER_ID","PERMISSION_DEFAULT","PERMISSION_BLOCKED","UNSUPPORTED_BROWSER","NOTIFICATIONS_BLOCKED","FAILED_DEFAULT_REGISTRATION","SW_REGISTRATION_EXPECTED","GET_SUBSCRIPTION_FAILED","INVALID_SAVED_TOKEN","SW_REG_REDUNDANT","TOKEN_SUBSCRIBE_FAILED","TOKEN_SUBSCRIBE_NO_TOKEN","TOKEN_SUBSCRIBE_NO_PUSH_SET","USE_SW_BEFORE_GET_TOKEN","INVALID_DELETE_TOKEN","DELETE_TOKEN_NOT_FOUND","DELETE_SCOPE_NOT_FOUND","BG_HANDLER_FUNCTION_EXPECTED","NO_WINDOW_CLIENT_TO_MSG","UNABLE_TO_RESUBSCRIBE","NO_FCM_TOKEN_FOR_RESUBSCRIBE","FAILED_TO_DELETE_TOKEN","NO_SW_IN_REG","BAD_SCOPE","BAD_VAPID_KEY","BAD_SUBSCRIPTION","BAD_TOKEN","BAD_PUSH_SET","FAILED_DELETE_VAPID_KEY","ERROR_MAP","models_errors","codes","array_buffer_to_base64","FCM_APPLICATION_SERVER_KEY","SUBSCRIPTION_DETAILS","userVisibleOnly","applicationServerKey","fcm_details","ENDPOINT","APPLICATION_SERVER_KEY","SUBSCRIPTION_OPTIONS","FCM_TOKEN_OBJ_STORE","token_manager_TokenManager","TokenManager","errorFactory_","openDbPromise_","openDatabase_","indexedDB","onsuccess","onupgradeneeded","db","objectStore","createObjectStore","keyPath","createIndex","unique","closeDatabase","getTokenDetailsFromToken","fcmToken","getTokenDetailsFromSWScope_","swScope","scopeRequest","getAllTokenDetailsForSenderId_","senderId","senderIdTokens","cursorRequest","openCursor","cursor","continue","subscribeToFCM","subscription","pushSet","p256dh","auth","fcmSubscribeBody","endpoint","Headers","append","subscribeOptions","fetch","fcmTokenResponse","isSameSubscription_","masterTokenDetails","saveTokenDetails_","swRegistration","fcmPushSet","details","fcmSenderId","getSavedToken","ServiceWorkerRegistration","allTokenDetails","tokenDetails","pushManager","getSubscription","createToken","fcmTokenDetails","sub","deleteToken","token_manager","SENDER_ID_OPTION_NAME","controller_interface_ControllerInterface","ControllerInterface","messagingSenderId_","tokenManager_","currentPermission","getNotificationPermission_","notification_permission","getSWRegistration_","unsubscribe","requestPermission","useServiceWorker","optError","optCompleted","onTokenRefresh","setBackgroundMessageHandler","Notification","permission","getTokenManager","controller_interface","PARAMS","TYPE_OF_MSG","DATA","msgType","PUSH_MSG_RECEIVED","NOTIFICATION_CLICKED","createNewMsg","msgData","worker_page_message","TYPES_OF_MSG","default_sw","window_controller_WindowController","WindowController","registrationToUse_","manifestCheckPromise_","messageObserver_","tokenRefreshObserver_","onTokenRefresh_","setupSWMessageListener_","isSupported_","manifestCheck_","manifestTag","querySelector","manifestContent","managePermissionResult","permissionPromise","waitForRegistrationToActivate_","serviceWorker","installing","waiting","state","stateChangeListener","removeEventListener","register","browserErrorMessage","workerPageMessage","pushMessage","PushSubscription","sw_controller___extends","sw_controller_SWController","SWController","onPush_","onSubChange_","onNotificationClick_","bgMessageHandler_","msgPayload","handleMsgPromise","hasVisibleClients_","hasVisibleClients","notification","sendMessageToWindowClients_","notificationDetails","getNotificationData_","notificationTitle","showNotification","waitUntil","promiseChain","tokenManager","newSubscription","stopImmediatePropagation","clickAction","getWindowClient_","windowClient","clients","openWindow","internalMsg","attemptToMessageClient_","notificationInformation","assign","URL","matchAll","includeUncontrolled","clientList","suitableClient","focus","client","some","visibilityState","src_app","60","prependCode","unknown","FirebaseStorageError","Code","UNKNOWN","objectNotFound","OBJECT_NOT_FOUND","quotaExceeded","bucket","QUOTA_EXCEEDED","unauthenticated","UNAUTHENTICATED","unauthorized","UNAUTHORIZED","retryLimitExceeded","RETRY_LIMIT_EXCEEDED","error_canceled","CANCELED","invalidUrl","INVALID_URL","invalidDefaultBucket","INVALID_DEFAULT_BUCKET","cannotSliceBlob","CANNOT_SLICE_BLOB","serverFileWrongSize","SERVER_FILE_WRONG_SIZE","noDownloadURL","NO_DOWNLOAD_URL","invalidArgument","INVALID_ARGUMENT","invalidArgumentCount","argMin","argMax","real","countPart","plural","INVALID_ARGUMENT_COUNT","appDeleted","APP_DELETED","invalidRootOperation","INVALID_ROOT_OPERATION","invalidFormat","format","INVALID_FORMAT","internalError","INTERNAL_ERROR","formatValidator","stringFormat","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","dataFromString","string","StringData","utf8Bytes_","base64Bytes_","dataURLBytes_","dataURLContentType_","valid","hi","lo","percentEncodedBytes_","hasMinus","hasUnder","invalidChar","hasPlus","hasSlash","string_DataURLParts","rest","contentType","endsWith","end","taskStateFromInternalTaskState","InternalTaskState","RUNNING","PAUSING","CANCELING","TaskState","PAUSED","SUCCESS","ERROR","make","resolver","promise_external_resolve","promise_external_reject","isDef","isJustDef","isFunction","isObject","isNonNullObject","isNonArrayObject","isString","isNumber","isNativeBlob","isNativeBlobDefined","Blob","jsonObjectOrNull","path_parent","lastIndexOf","canonicalChildPath","component","lastComponent","makeNormalUrl","urlPart","domainBase","apiBaseUrl","makeDownloadUrl","downloadBase","makeUploadUrl","apiUploadBaseUrl","makeQueryString","encode","queryPart","nextPart","noXform_","metadata","xformPath","fullPath","getMappings","mappingsXformPath","xformSize","size","xformTokens","tokens","alt","mappings_","mappings","Mapping","nameMapping","xform","sizeMapping","addRef","authWrapper","generateRef","loc","location_Location","makeStorageReference","fromResource","resource","mapping","local","server","fromResourceString","resourceString","toResourceString","writable","metadataValidator","validate","specs","passed","minArgs","maxArgs","validator","and_","v1","v2","stringSpec","opt_validator","opt_optional","stringValidator","args_ArgSpec","uploadDataSpec","ArrayBuffer","metadataSpec","nonNegativeNumberSpec","looseObjectSpec","nullFunctionSpec","getBlobBuilder","BlobBuilder","WebKitBlobBuilder","getBlob","bb","sliceBlob","blob","webkitSlice","mozSlice","array_contains","elem","array_clone","arraylike","handlerCheck","cndn","metadataHandler","handler","text","sharedErrorHandler","errorHandler","newErr","getStatus","setServerResponseProp","serverResponseProp","objectErrorHandler","shared","getMetadata","fullServerUrl","maxOperationRetryTime","requestInfo","RequestInfo","updateMetadata","Content-Type","deleteObject","successCodes","determineContentType_","metadataForUpload_","opt_metadata","multipartUpload","bucketOnlyServerUrl","X-Goog-Upload-Protocol","boundary","metadataString","preBlobPart","postBlobPart","blob_FbsBlob","maxUploadRetryTime","uploadData","checkResumeHeader_","opt_allowed","getResponseHeader","createResumableUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","ResumableUploadStatus","continueResumableUpload","opt_status","opt_progressCallback","uploadStatus","newCurrent","current","bytesToUpload","total","bytesLeft","startByte","endByte","uploadCommand","X-Goog-Upload-Offset","progressCallback","async_async","argsToForward","canceled","cancelState","triggerCallback","triggeredCallback","callWithDelay","millis","timeoutId","hitTimeout","waitSeconds","waitMillis","stop","wasTimeout","stopped","addAuthHeader_","addVersionHeader_","number","makeRequest","pool","request_NetworkRequest","additionalRetryCodes","factory","opt_url","service_Service","xhriopool_XhrIoPool","registerStorage","TaskEvent","Storage","reference_Reference","STORAGE_TYPE","ErrorCode","defaultMaxOperationRetryTime","defaultMaxUploadRetryTime","minSafeInteger","code_","message_","serverResponse_","codeProp","codeEquals","serverResponse","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","INVALID_CHECKSUM","INVALID_EVENT_NAME","NO_DEFAULT_BUCKET","opt_contentType","DataURLParts","STATE_CHANGED","xhrio_network_NetworkXhrIo","NetworkXhrIo","sent_","xhr_","errorCode_","NO_ERROR","sendPromise_","ABORT","NETWORK_ERROR","opt_body","opt_headers","setRequestHeader","getErrorCode","getResponseText","abort","addUploadProgressListener","upload","removeUploadProgressListener","XhrIoPool","createXhrIo","Location","makeFromBucketSpec","bucketString","bucketLocation","makeFromUrl","gsModify","httpModify","gsRegex","gsIndices","httpRegex","httpIndices","groups","regex","indices","postModify","group","captures","exec","bucketValue","pathValue","opt_local","opt_writable","opt_xform","ArgSpec","FbsBlob","opt_elideCopy","blobType","data_","byteLength","size_","type_","realBlob","sliced","buffer","blobby","uint8Arrays","finalLength_1","merged_1","index_1","observer_Observer","Observer","opt_error","opt_complete","UploadTaskSnapshot","bytesTransferred","totalBytes","urls","task_UploadTask","UploadTask","transferred_","needToFetchStatus_","needToFetchMetadata_","observers_","error_","uploadUrl_","request_","chunkMultiplier_","resolve_","reject_","authWrapper_","location_","blob_","metadata_","resumable_","shouldDoResumable_","errorHandler_","completeTransitions_","transition_","metadataErrorHandler_","promise_","makeProgressCallback_","sizeBefore","loaded","updateProgress_","createResumable_","fetchStatus_","fetchMetadata_","continueUpload_","oneShotUpload_","resolveToken_","getAuthToken","createRequest","getPromise","statusRequest","uploadRequest","newStatus","increaseMultiplier_","metadataRequest","multipartRequest","transferred","old","notifyObservers_","wasPaused","externalState","completed","typeValidator","_p","nextOrObserverValidator","nextValidator","observerValidator","nextOrObserverMessage","makeBinder","binder","addObserver_","removeObserver_","binderNextOrObserverValidator","binderSpecs","notifyObserver_","finishPromise_","triggered","pause","newRef","newPath","throwIfRoot_","putString","getDownloadURL","failrequest_FailRequest","FailRequest","appDelete","requestmap_RequestMap","RequestMap","map_","id_","addRequest","unmap","authwrapper_AuthWrapper","AuthWrapper","maker","requestMaker","bucket_","deleted_","extractBucket_","storageRefMaker_","requestMaker_","pool_","service_","maxOperationRetryTime_","maxUploadRetryTime_","requestMap_","config","_error","deleteApp","setMaxUploadRetryTime","setMaxOperationRetryTime","NetworkRequest","errorCallback","pendingXhr_","backoffId_","canceled_","appDelete_","url_","method_","headers_","body_","successCodes_","additionalRetryCodes_","errorCallback_","progressCallback_","timeout_","doTheRequest","backoffCallback","progressListener","progressEvent","lengthComputable","RequestEndStatus","hitServer","isRetryStatusCode_","wasCanceled","successCode","backoffDone","requestWentThrough","wasSuccessCode","isFiveHundredCode","extraRetryCodes","isExtraRetryCode","isRequestSpecificRetryCode","opt_canceled","Service","authWrapperBucket","internals_","service_ServiceInternals","ServiceInternals"],"mappings":"AAAA,GAAIA,UAAW,WACH,GAAIC,OAA2B,KAAXA,EAAyBC,KAAOD,CACtD,OAAgB,UAAUE,GCqCpC,QAAAC,GAAAC,GAGA,GAAAC,EAAAD,GACA,MAAAC,GAAAD,GAAAE,OAGA,IAAAC,GAAAF,EAAAD,IACAI,EAAAJ,EACAK,GAAA,EACAH,WAUA,OANAJ,GAAAE,GAAAM,KAAAH,EAAAD,QAAAC,IAAAD,QAAAH,GAGAI,EAAAE,GAAA,EAGAF,EAAAD,QA1DA,GAAAK,GAAAX,EAAA,oBACAA,GAAA,8BAAAY,EAAAC,EAAAC,GAIA,IADA,GAAAV,GAAAW,EAAAC,EAAAR,EAAA,EAAAS,KACQT,EAAAI,EAAAM,OAAoBV,IAC5BO,EAAAH,EAAAJ,GACAW,EAAAJ,IACAE,EAAAG,KAAAD,EAAAJ,GAAA,IAEAI,EAAAJ,GAAA,CAEA,KAAAX,IAAAS,GACAQ,OAAAC,UAAAC,eAAAb,KAAAG,EAAAT,KACAF,EAAAE,GAAAS,EAAAT,GAIA,KADAO,KAAAC,EAAAC,EAAAC,GACAG,EAAAC,QACAD,EAAAO,SAEA,IAAAV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,EAAgDkT,GAE9DvO,GAAA,gBd60DeyS;;Aer2Df;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A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AwC,eAAIszF,EAAA71F,UAAG,OjCisGD0C,IiCjsGN,WACQ,MAAKiB,MACb0hC,IjCksGM5iC,YAAY,EACZD,ciCnsGL,IAEDzC,OAAAwC,eAAIszF,EAAA71F,UAAQ,YjCosGN0C,IiCpsGN,WACQ,MAAKiB,MACboyF,IjCqsGMtzF,YAAY,EACZD,ciCtsGL,IACFqzF,KAKDG,GAAA,WAGE,QAAAC,GAA4B/xF,GACtBP,KAASwvF,GACfjvF,EAUF,MAJE+xF,GAAAj2F,UAAM6U,OAAN,WAEQ,MADFlR,MAASwvF,GAAa5E,EAAakF,YAClB9W,MACvB77E,KACDm1F,If7IE7yF,GAAA,gBAAA6kF,EAYH,IAAkBI,IAAa,SAyBhBJ,IAAW7Q,GAAA,YlBg2GvB,KACS,MAAMl0E,GACN,KAAUrC,OACR","file":"firebase.js","sourcesContent":["var firebase = (function() {\n var window = typeof window === 'undefined' ? self : window;\n return /******/ (function(modules) { // webpackBootstrap\n/******/ \t// install a JSONP callback for chunk loading\n/******/ \tvar parentJsonpFunction = window[\"webpackJsonpFirebase\"];\n/******/ \twindow[\"webpackJsonpFirebase\"] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {\n/******/ \t\t// add \"moreModules\" to the modules object,\n/******/ \t\t// then flag all \"chunkIds\" as loaded and fire callback\n/******/ \t\tvar moduleId, chunkId, i = 0, resolves = [], result;\n/******/ \t\tfor(;i < chunkIds.length; i++) {\n/******/ \t\t\tchunkId = chunkIds[i];\n/******/ \t\t\tif(installedChunks[chunkId]) {\n/******/ \t\t\t\tresolves.push(installedChunks[chunkId][0]);\n/******/ \t\t\t}\n/******/ \t\t\tinstalledChunks[chunkId] = 0;\n/******/ \t\t}\n/******/ \t\tfor(moduleId in moreModules) {\n/******/ \t\t\tif(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {\n/******/ \t\t\t\tmodules[moduleId] = moreModules[moduleId];\n/******/ \t\t\t}\n/******/ \t\t}\n/******/ \t\tif(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);\n/******/ \t\twhile(resolves.length) {\n/******/ \t\t\tresolves.shift()();\n/******/ \t\t}\n/******/ \t\tif(executeModules) {\n/******/ \t\t\tfor(i=0; i < executeModules.length; i++) {\n/******/ \t\t\t\tresult = __webpack_require__(__webpack_require__.s = executeModules[i]);\n/******/ \t\t\t}\n/******/ \t\t}\n/******/ \t\treturn result;\n/******/ \t};\n/******/\n/******/ \t// The module cache\n/******/ \tvar installedModules = {};\n/******/\n/******/ \t// objects to store loaded and loading chunks\n/******/ \tvar installedChunks = {\n/******/ \t\t4: 0\n/******/ \t};\n/******/\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(installedModules[moduleId]) {\n/******/ \t\t\treturn installedModules[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = installedModules[moduleId] = {\n/******/ \t\t\ti: moduleId,\n/******/ \t\t\tl: false,\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/\n/******/ \t\t// Execute the module function\n/******/ \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n/******/\n/******/ \t\t// Flag the module as loaded\n/******/ \t\tmodule.l = true;\n/******/\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/\n/******/ \t// This file contains only the entry chunk.\n/******/ \t// The chunk loading function for additional chunks\n/******/ \t__webpack_require__.e = function requireEnsure(chunkId) {\n/******/ \t\tvar installedChunkData = installedChunks[chunkId];\n/******/ \t\tif(installedChunkData === 0) {\n/******/ \t\t\treturn new Promise(function(resolve) { resolve(); });\n/******/ \t\t}\n/******/\n/******/ \t\t// a Promise means \"currently loading\".\n/******/ \t\tif(installedChunkData) {\n/******/ \t\t\treturn installedChunkData[2];\n/******/ \t\t}\n/******/\n/******/ \t\t// setup Promise in chunk cache\n/******/ \t\tvar promise = new Promise(function(resolve, reject) {\n/******/ \t\t\tinstalledChunkData = installedChunks[chunkId] = [resolve, reject];\n/******/ \t\t});\n/******/ \t\tinstalledChunkData[2] = promise;\n/******/\n/******/ \t\t// start chunk loading\n/******/ \t\tvar head = document.getElementsByTagName('head')[0];\n/******/ \t\tvar script = document.createElement('script');\n/******/ \t\tscript.type = 'text/javascript';\n/******/ \t\tscript.charset = 'utf-8';\n/******/ \t\tscript.async = true;\n/******/ \t\tscript.timeout = 120000;\n/******/\n/******/ \t\tif (__webpack_require__.nc) {\n/******/ \t\t\tscript.setAttribute(\"nonce\", __webpack_require__.nc);\n/******/ \t\t}\n/******/ \t\tscript.src = __webpack_require__.p + \"\" + chunkId + \".js\";\n/******/ \t\tvar timeout = setTimeout(onScriptComplete, 120000);\n/******/ \t\tscript.onerror = script.onload = onScriptComplete;\n/******/ \t\tfunction onScriptComplete() {\n/******/ \t\t\t// avoid mem leaks in IE.\n/******/ \t\t\tscript.onerror = script.onload = null;\n/******/ \t\t\tclearTimeout(timeout);\n/******/ \t\t\tvar chunk = installedChunks[chunkId];\n/******/ \t\t\tif(chunk !== 0) {\n/******/ \t\t\t\tif(chunk) {\n/******/ \t\t\t\t\tchunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));\n/******/ \t\t\t\t}\n/******/ \t\t\t\tinstalledChunks[chunkId] = undefined;\n/******/ \t\t\t}\n/******/ \t\t};\n/******/ \t\thead.appendChild(script);\n/******/\n/******/ \t\treturn promise;\n/******/ \t};\n/******/\n/******/ \t// expose the modules object (__webpack_modules__)\n/******/ \t__webpack_require__.m = modules;\n/******/\n/******/ \t// expose the module cache\n/******/ \t__webpack_require__.c = installedModules;\n/******/\n/******/ \t// define getter function for harmony exports\n/******/ \t__webpack_require__.d = function(exports, name, getter) {\n/******/ \t\tif(!__webpack_require__.o(exports, name)) {\n/******/ \t\t\tObject.defineProperty(exports, name, {\n/******/ \t\t\t\tconfigurable: false,\n/******/ \t\t\t\tenumerable: true,\n/******/ \t\t\t\tget: getter\n/******/ \t\t\t});\n/******/ \t\t}\n/******/ \t};\n/******/\n/******/ \t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t__webpack_require__.n = function(module) {\n/******/ \t\tvar getter = module && module.__esModule ?\n/******/ \t\t\tfunction getDefault() { return module['default']; } :\n/******/ \t\t\tfunction getModuleExports() { return module; };\n/******/ \t\t__webpack_require__.d(getter, 'a', getter);\n/******/ \t\treturn getter;\n/******/ \t};\n/******/\n/******/ \t// Object.prototype.hasOwnProperty.call\n/******/ \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n/******/\n/******/ \t// __webpack_public_path__\n/******/ \t__webpack_require__.p = \"\";\n/******/\n/******/ \t// on error function for async loading\n/******/ \t__webpack_require__.oe = function(err) { console.error(err); throw err; };\n/******/\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(__webpack_require__.s = 9);\n/******/ })\n/************************************************************************/\n/******/ ({\n\n/***/ 24:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* unused harmony export patchCapture */\n/* unused harmony export FirebaseError */\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return ErrorFactory; });\nvar ERROR_NAME = 'FirebaseError';\nvar captureStackTrace = Error.captureStackTrace;\n// Export for faking in tests\nfunction patchCapture(captureFake) {\n var result = captureStackTrace;\n captureStackTrace = captureFake;\n return result;\n}\nvar FirebaseError = /** @class */function () {\n function FirebaseError(code, message) {\n this.code = code;\n this.message = message;\n var stack;\n // We want the stack value, if implemented by Error\n if (captureStackTrace) {\n // Patches this.stack, omitted calls above ErrorFactory#create\n captureStackTrace(this, ErrorFactory.prototype.create);\n } else {\n var err_1 = Error.apply(this, arguments);\n this.name = ERROR_NAME;\n // Make non-enumerable getter for the property.\n Object.defineProperty(this, 'stack', {\n get: function get() {\n return err_1.stack;\n }\n });\n }\n }\n return FirebaseError;\n}();\n\n// Back-door inheritance\nFirebaseError.prototype = Object.create(Error.prototype);\nFirebaseError.prototype.constructor = FirebaseError;\nFirebaseError.prototype.name = ERROR_NAME;\nvar ErrorFactory = /** @class */function () {\n function ErrorFactory(service, serviceName, errors) {\n this.service = service;\n this.serviceName = serviceName;\n this.errors = errors;\n // Matches {$name}, by default.\n this.pattern = /\\{\\$([^}]+)}/g;\n // empty\n }\n ErrorFactory.prototype.create = function (code, data) {\n if (data === undefined) {\n data = {};\n }\n var template = this.errors[code];\n var fullCode = this.service + '/' + code;\n var message;\n if (template === undefined) {\n message = 'Error';\n } else {\n message = template.replace(this.pattern, function (match, key) {\n var value = data[key];\n return value !== undefined ? value.toString() : '<' + key + '?>';\n });\n }\n // Service: Error message (service/code).\n message = this.serviceName + ': ' + message + ' (' + fullCode + ').';\n var err = new FirebaseError(fullCode, message);\n // Populate the Error object with message parts for programmatic\n // accesses (e.g., e.file).\n for (var prop in data) {\n if (!data.hasOwnProperty(prop) || prop.slice(-1) === '_') {\n continue;\n }\n err[prop] = data[prop];\n }\n return err;\n };\n return ErrorFactory;\n}();\n\n\n/***/ }),\n\n/***/ 3:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return PromiseImpl; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return Deferred; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"c\", function() { return attachDummyErrorHandler; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_globalScope__ = __webpack_require__(32);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar PromiseImpl = __WEBPACK_IMPORTED_MODULE_0__utils_globalScope__[\"a\" /* globalScope */].Promise || __webpack_require__(57);\n/**\r\n * A deferred promise implementation.\r\n */\nvar Deferred = /** @class */function () {\n /** @constructor */\n function Deferred() {\n var self = this;\n this.resolve = null;\n this.reject = null;\n this.promise = new PromiseImpl(function (resolve, reject) {\n self.resolve = resolve;\n self.reject = reject;\n });\n }\n /**\r\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\r\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\r\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\r\n * @param {((?function(?(Error)): (?|undefined))| (?function(?(Error),?=): (?|undefined)))=} opt_nodeCallback\r\n * @return {!function(?(Error), ?=)}\r\n */\n Deferred.prototype.wrapCallback = function (opt_nodeCallback) {\n var self = this;\n /**\r\n * @param {?Error} error\r\n * @param {?=} opt_value\r\n */\n function meta(error, opt_value) {\n if (error) {\n self.reject(error);\n } else {\n self.resolve(opt_value);\n }\n if (typeof opt_nodeCallback === 'function') {\n attachDummyErrorHandler(self.promise);\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (opt_nodeCallback.length === 1) {\n opt_nodeCallback(error);\n } else {\n opt_nodeCallback(error, opt_value);\n }\n }\n }\n return meta;\n };\n return Deferred;\n}();\n\n/**\r\n * Chrome (and maybe other browsers) report an Error in the console if you reject a promise\r\n * and nobody handles the error. This is normally a good thing, but this will confuse devs who\r\n * never intended to use promises in the first place. So in some cases (in particular, if the\r\n * developer attached a callback), we should attach a dummy resolver to the promise to suppress\r\n * this error.\r\n *\r\n * Note: We can't do this all the time, since it breaks the Promise spec (though in the obscure\r\n * 3.3.3 section related to upgrading non-compliant promises).\r\n * @param {!firebase.Promise} promise\r\n */\nvar attachDummyErrorHandler = function attachDummyErrorHandler(promise) {\n promise.catch(function () {});\n};\n\n/***/ }),\n\n/***/ 31:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = createSubscribe;\n/* unused harmony export async */\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__utils_promise__ = __webpack_require__(3);\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\n\n/**\r\n * Helper to make a Subscribe function (just like Promise helps make a\r\n * Thenable).\r\n *\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\nfunction createSubscribe(executor, onNoObservers) {\n var proxy = new ObserverProxy(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n/**\r\n * Implement fan-out for any number of Observers attached via a subscribe\r\n * function.\r\n */\nvar ObserverProxy = /** @class */function () {\n /**\r\n * @param executor Function which can make calls to a single Observer\r\n * as a proxy.\r\n * @param onNoObservers Callback when count of Observers goes to zero.\r\n */\n function ObserverProxy(executor, onNoObservers) {\n var _this = this;\n this.observers = [];\n this.unsubscribes = [];\n this.observerCount = 0;\n // Micro-task scheduling by calling task.then().\n this.task = __WEBPACK_IMPORTED_MODULE_0__utils_promise__[\"b\" /* PromiseImpl */].resolve();\n this.finalized = false;\n this.onNoObservers = onNoObservers;\n // Call the executor asynchronously so subscribers that are called\n // synchronously after the creation of the subscribe function\n // can still receive the very first value generated in the executor.\n this.task.then(function () {\n executor(_this);\n }).catch(function (e) {\n _this.error(e);\n });\n }\n ObserverProxy.prototype.next = function (value) {\n this.forEachObserver(function (observer) {\n observer.next(value);\n });\n };\n ObserverProxy.prototype.error = function (error) {\n this.forEachObserver(function (observer) {\n observer.error(error);\n });\n this.close(error);\n };\n ObserverProxy.prototype.complete = function () {\n this.forEachObserver(function (observer) {\n observer.complete();\n });\n this.close();\n };\n /**\r\n * Subscribe function that can be used to add an Observer to the fan-out list.\r\n *\r\n * - We require that no event is sent to a subscriber sychronously to their\r\n * call to subscribe().\r\n */\n ObserverProxy.prototype.subscribe = function (nextOrObserver, error, complete) {\n var _this = this;\n var observer;\n if (nextOrObserver === undefined && error === undefined && complete === undefined) {\n throw new Error('Missing Observer.');\n }\n // Assemble an Observer object when passed as callback functions.\n if (implementsAnyMethods(nextOrObserver, ['next', 'error', 'complete'])) {\n observer = nextOrObserver;\n } else {\n observer = {\n next: nextOrObserver,\n error: error,\n complete: complete\n };\n }\n if (observer.next === undefined) {\n observer.next = noop;\n }\n if (observer.error === undefined) {\n observer.error = noop;\n }\n if (observer.complete === undefined) {\n observer.complete = noop;\n }\n var unsub = this.unsubscribeOne.bind(this, this.observers.length);\n // Attempt to subscribe to a terminated Observable - we\n // just respond to the Observer with the final error or complete\n // event.\n if (this.finalized) {\n this.task.then(function () {\n try {\n if (_this.finalError) {\n observer.error(_this.finalError);\n } else {\n observer.complete();\n }\n } catch (e) {\n // nothing\n }\n return;\n });\n }\n this.observers.push(observer);\n return unsub;\n };\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n ObserverProxy.prototype.unsubscribeOne = function (i) {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n delete this.observers[i];\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n };\n ObserverProxy.prototype.forEachObserver = function (fn) {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (var i = 0; i < this.observers.length; i++) {\n this.sendOne(i, fn);\n }\n };\n // Call the Observer via one of it's callback function. We are careful to\n // confirm that the observe has not been unsubscribed since this asynchronous\n // function had been queued.\n ObserverProxy.prototype.sendOne = function (i, fn) {\n var _this = this;\n // Execute the callback asynchronously\n this.task.then(function () {\n if (_this.observers !== undefined && _this.observers[i] !== undefined) {\n try {\n fn(_this.observers[i]);\n } catch (e) {\n // Ignore exceptions raised in Observers or missing methods of an\n // Observer.\n // Log error to console. b/31404806\n if (typeof console !== 'undefined' && console.error) {\n console.error(e);\n }\n }\n }\n });\n };\n ObserverProxy.prototype.close = function (err) {\n var _this = this;\n if (this.finalized) {\n return;\n }\n this.finalized = true;\n if (err !== undefined) {\n this.finalError = err;\n }\n // Proxy is no longer needed - garbage collect references\n this.task.then(function () {\n _this.observers = undefined;\n _this.onNoObservers = undefined;\n });\n };\n return ObserverProxy;\n}();\n/** Turn synchronous function into one called asynchronously. */\nfunction async(fn, onError) {\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n __WEBPACK_IMPORTED_MODULE_0__utils_promise__[\"b\" /* PromiseImpl */].resolve(true).then(function () {\n fn.apply(void 0, args);\n }).catch(function (error) {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n/**\r\n * Return true if the object passed in implements any of the named methods.\r\n */\nfunction implementsAnyMethods(obj, methods) {\n if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' || obj === null) {\n return false;\n }\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n return false;\n}\nfunction noop() {\n // do nothing\n}\n\n/***/ }),\n\n/***/ 32:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return globalScope; });\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\nvar scope;\nif (typeof global !== 'undefined') {\n scope = global;\n} else if (typeof self !== 'undefined') {\n scope = self;\n} else {\n try {\n scope = Function('return this')();\n } catch (e) {\n throw new Error('polyfill failed because global object is unavailable in this environment');\n }\n}\nvar globalScope = scope;\n/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(33)))\n\n/***/ }),\n\n/***/ 33:\n/***/ (function(module, exports) {\n\nvar g;\r\n\r\n// This works in non-strict mode\r\ng = (function() {\r\n\treturn this;\r\n})();\r\n\r\ntry {\r\n\t// This works if eval is allowed (see CSP)\r\n\tg = g || Function(\"return this\")() || (1,eval)(\"this\");\r\n} catch(e) {\r\n\t// This works if the window reference is available\r\n\tif(typeof window === \"object\")\r\n\t\tg = window;\r\n}\r\n\r\n// g can still be undefined, but nothing to do about it...\r\n// We return undefined, instead of nothing here, so it's\r\n// easier to handle this case. if(!global) { ...}\r\n\r\nmodule.exports = g;\r\n\n\n/***/ }),\n\n/***/ 34:\n/***/ (function(module, exports) {\n\n// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n\n\n/***/ }),\n\n/***/ 35:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (immutable) */ __webpack_exports__[\"a\"] = deepCopy;\n/* harmony export (immutable) */ __webpack_exports__[\"b\"] = deepExtend;\n/* harmony export (immutable) */ __webpack_exports__[\"c\"] = patchProperty;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * Do a deep-copy of basic JavaScript Objects or Arrays.\r\n */\nfunction deepCopy(value) {\n return deepExtend(undefined, value);\n}\n/**\r\n * Copy properties from source to target (recursively allows extension\r\n * of Objects and Arrays). Scalar values in the target are over-written.\r\n * If target is undefined, an object of the appropriate type will be created\r\n * (and returned).\r\n *\r\n * We recursively copy all child properties of plain Objects in the source- so\r\n * that namespace- like dictionaries are merged.\r\n *\r\n * Note that the target can be a function, in which case the properties in\r\n * the source Object are copied onto it as static properties of the Function.\r\n */\nfunction deepExtend(target, source) {\n if (!(source instanceof Object)) {\n return source;\n }\n switch (source.constructor) {\n case Date:\n // Treat Dates like scalars; if the target date object had any child\n // properties - they will be lost!\n var dateValue = source;\n return new Date(dateValue.getTime());\n case Object:\n if (target === undefined) {\n target = {};\n }\n break;\n case Array:\n // Always copy the array source and overwrite the target.\n target = [];\n break;\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n for (var prop in source) {\n if (!source.hasOwnProperty(prop)) {\n continue;\n }\n target[prop] = deepExtend(target[prop], source[prop]);\n }\n return target;\n}\n// TODO: Really needed (for JSCompiler type checking)?\nfunction patchProperty(obj, prop, value) {\n obj[prop] = value;\n}\n\n/***/ }),\n\n/***/ 56:\n/***/ (function(module, exports) {\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * This is the Array.prototype.findIndex polyfill from MDN\r\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\r\n * https://tc39.github.io/ecma262/#sec-array.prototype.findIndex\r\n */\nif (!Array.prototype.findIndex) {\n Object.defineProperty(Array.prototype, 'findIndex', {\n value: function value(predicate) {\n // 1. Let O be ? ToObject(this value).\n if (this == null) {\n throw new TypeError('\"this\" is null or not defined');\n }\n var o = Object(this);\n // 2. Let len be ? ToLength(? Get(O, \"length\")).\n var len = o.length >>> 0;\n // 3. If IsCallable(predicate) is false, throw a TypeError exception.\n if (typeof predicate !== 'function') {\n throw new TypeError('predicate must be a function');\n }\n // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.\n var thisArg = arguments[1];\n // 5. Let k be 0.\n var k = 0;\n // 6. Repeat, while k < len\n while (k < len) {\n // a. Let Pk be ! ToString(k).\n // b. Let kValue be ? Get(O, Pk).\n // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).\n // d. If testResult is true, return k.\n var kValue = o[k];\n if (predicate.call(thisArg, kValue, k, o)) {\n return k;\n }\n // e. Increase k by 1.\n k++;\n }\n // 7. Return -1.\n return -1;\n }\n });\n}\n/**\r\n * This is the Array.prototype.find polyfill from MDN\r\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\r\n * https://tc39.github.io/ecma262/#sec-array.prototype.find\r\n */\nif (!Array.prototype.find) {\n Object.defineProperty(Array.prototype, 'find', {\n value: function value(predicate) {\n // 1. Let O be ? ToObject(this value).\n if (this == null) {\n throw new TypeError('\"this\" is null or not defined');\n }\n var o = Object(this);\n // 2. Let len be ? ToLength(? Get(O, \"length\")).\n var len = o.length >>> 0;\n // 3. If IsCallable(predicate) is false, throw a TypeError exception.\n if (typeof predicate !== 'function') {\n throw new TypeError('predicate must be a function');\n }\n // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.\n var thisArg = arguments[1];\n // 5. Let k be 0.\n var k = 0;\n // 6. Repeat, while k < len\n while (k < len) {\n // a. Let Pk be ! ToString(k).\n // b. Let kValue be ? Get(O, Pk).\n // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).\n // d. If testResult is true, return kValue.\n var kValue = o[k];\n if (predicate.call(thisArg, kValue, k, o)) {\n return kValue;\n }\n // e. Increase k by 1.\n k++;\n }\n // 7. Return undefined.\n return undefined;\n }\n });\n}\n\n/***/ }),\n\n/***/ 57:\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(setImmediate) {(function (root) {\n\n // Store setTimeout reference so promise-polyfill will be unaffected by\n // other code modifying setTimeout (like sinon.useFakeTimers())\n var setTimeoutFunc = setTimeout;\n\n function noop() {}\n \n // Polyfill for Function.prototype.bind\n function bind(fn, thisArg) {\n return function () {\n fn.apply(thisArg, arguments);\n };\n }\n\n function Promise(fn) {\n if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');\n if (typeof fn !== 'function') throw new TypeError('not a function');\n this._state = 0;\n this._handled = false;\n this._value = undefined;\n this._deferreds = [];\n\n doResolve(fn, this);\n }\n\n function handle(self, deferred) {\n while (self._state === 3) {\n self = self._value;\n }\n if (self._state === 0) {\n self._deferreds.push(deferred);\n return;\n }\n self._handled = true;\n Promise._immediateFn(function () {\n var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;\n if (cb === null) {\n (self._state === 1 ? resolve : reject)(deferred.promise, self._value);\n return;\n }\n var ret;\n try {\n ret = cb(self._value);\n } catch (e) {\n reject(deferred.promise, e);\n return;\n }\n resolve(deferred.promise, ret);\n });\n }\n\n function resolve(self, newValue) {\n try {\n // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure\n if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.');\n if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {\n var then = newValue.then;\n if (newValue instanceof Promise) {\n self._state = 3;\n self._value = newValue;\n finale(self);\n return;\n } else if (typeof then === 'function') {\n doResolve(bind(then, newValue), self);\n return;\n }\n }\n self._state = 1;\n self._value = newValue;\n finale(self);\n } catch (e) {\n reject(self, e);\n }\n }\n\n function reject(self, newValue) {\n self._state = 2;\n self._value = newValue;\n finale(self);\n }\n\n function finale(self) {\n if (self._state === 2 && self._deferreds.length === 0) {\n Promise._immediateFn(function() {\n if (!self._handled) {\n Promise._unhandledRejectionFn(self._value);\n }\n });\n }\n\n for (var i = 0, len = self._deferreds.length; i < len; i++) {\n handle(self, self._deferreds[i]);\n }\n self._deferreds = null;\n }\n\n function Handler(onFulfilled, onRejected, promise) {\n this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;\n this.onRejected = typeof onRejected === 'function' ? onRejected : null;\n this.promise = promise;\n }\n\n /**\n * Take a potentially misbehaving resolver function and make sure\n * onFulfilled and onRejected are only called once.\n *\n * Makes no guarantees about asynchrony.\n */\n function doResolve(fn, self) {\n var done = false;\n try {\n fn(function (value) {\n if (done) return;\n done = true;\n resolve(self, value);\n }, function (reason) {\n if (done) return;\n done = true;\n reject(self, reason);\n });\n } catch (ex) {\n if (done) return;\n done = true;\n reject(self, ex);\n }\n }\n\n Promise.prototype['catch'] = function (onRejected) {\n return this.then(null, onRejected);\n };\n\n Promise.prototype.then = function (onFulfilled, onRejected) {\n var prom = new (this.constructor)(noop);\n\n handle(this, new Handler(onFulfilled, onRejected, prom));\n return prom;\n };\n\n Promise.all = function (arr) {\n var args = Array.prototype.slice.call(arr);\n\n return new Promise(function (resolve, reject) {\n if (args.length === 0) return resolve([]);\n var remaining = args.length;\n\n function res(i, val) {\n try {\n if (val && (typeof val === 'object' || typeof val === 'function')) {\n var then = val.then;\n if (typeof then === 'function') {\n then.call(val, function (val) {\n res(i, val);\n }, reject);\n return;\n }\n }\n args[i] = val;\n if (--remaining === 0) {\n resolve(args);\n }\n } catch (ex) {\n reject(ex);\n }\n }\n\n for (var i = 0; i < args.length; i++) {\n res(i, args[i]);\n }\n });\n };\n\n Promise.resolve = function (value) {\n if (value && typeof value === 'object' && value.constructor === Promise) {\n return value;\n }\n\n return new Promise(function (resolve) {\n resolve(value);\n });\n };\n\n Promise.reject = function (value) {\n return new Promise(function (resolve, reject) {\n reject(value);\n });\n };\n\n Promise.race = function (values) {\n return new Promise(function (resolve, reject) {\n for (var i = 0, len = values.length; i < len; i++) {\n values[i].then(resolve, reject);\n }\n });\n };\n\n // Use polyfill for setImmediate for performance gains\n Promise._immediateFn = (typeof setImmediate === 'function' && function (fn) { setImmediate(fn); }) ||\n function (fn) {\n setTimeoutFunc(fn, 0);\n };\n\n Promise._unhandledRejectionFn = function _unhandledRejectionFn(err) {\n if (typeof console !== 'undefined' && console) {\n console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console\n }\n };\n\n /**\n * Set the immediate function to execute callbacks\n * @param fn {function} Function to execute\n * @deprecated\n */\n Promise._setImmediateFn = function _setImmediateFn(fn) {\n Promise._immediateFn = fn;\n };\n\n /**\n * Change the function to execute on unhandled rejection\n * @param {function} fn Function to execute on unhandled rejection\n * @deprecated\n */\n Promise._setUnhandledRejectionFn = function _setUnhandledRejectionFn(fn) {\n Promise._unhandledRejectionFn = fn;\n };\n \n if (typeof module !== 'undefined' && module.exports) {\n module.exports = Promise;\n } else if (!root.Promise) {\n root.Promise = Promise;\n }\n\n})(this);\n\n/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(58).setImmediate))\n\n/***/ }),\n\n/***/ 58:\n/***/ (function(module, exports, __webpack_require__) {\n\nvar apply = Function.prototype.apply;\n\n// DOM APIs, for completeness\n\nexports.setTimeout = function() {\n return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);\n};\nexports.setInterval = function() {\n return new Timeout(apply.call(setInterval, window, arguments), clearInterval);\n};\nexports.clearTimeout =\nexports.clearInterval = function(timeout) {\n if (timeout) {\n timeout.close();\n }\n};\n\nfunction Timeout(id, clearFn) {\n this._id = id;\n this._clearFn = clearFn;\n}\nTimeout.prototype.unref = Timeout.prototype.ref = function() {};\nTimeout.prototype.close = function() {\n this._clearFn.call(window, this._id);\n};\n\n// Does not start the time, just sets up the members needed.\nexports.enroll = function(item, msecs) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = msecs;\n};\n\nexports.unenroll = function(item) {\n clearTimeout(item._idleTimeoutId);\n item._idleTimeout = -1;\n};\n\nexports._unrefActive = exports.active = function(item) {\n clearTimeout(item._idleTimeoutId);\n\n var msecs = item._idleTimeout;\n if (msecs >= 0) {\n item._idleTimeoutId = setTimeout(function onTimeout() {\n if (item._onTimeout)\n item._onTimeout();\n }, msecs);\n }\n};\n\n// setimmediate attaches itself to the global object\n__webpack_require__(59);\nexports.setImmediate = setImmediate;\nexports.clearImmediate = clearImmediate;\n\n\n/***/ }),\n\n/***/ 59:\n/***/ (function(module, exports, __webpack_require__) {\n\n/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {\n \"use strict\";\n\n if (global.setImmediate) {\n return;\n }\n\n var nextHandle = 1; // Spec says greater than zero\n var tasksByHandle = {};\n var currentlyRunningATask = false;\n var doc = global.document;\n var registerImmediate;\n\n function setImmediate(callback) {\n // Callback can either be a function or a string\n if (typeof callback !== \"function\") {\n callback = new Function(\"\" + callback);\n }\n // Copy function arguments\n var args = new Array(arguments.length - 1);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i + 1];\n }\n // Store and register the task\n var task = { callback: callback, args: args };\n tasksByHandle[nextHandle] = task;\n registerImmediate(nextHandle);\n return nextHandle++;\n }\n\n function clearImmediate(handle) {\n delete tasksByHandle[handle];\n }\n\n function run(task) {\n var callback = task.callback;\n var args = task.args;\n switch (args.length) {\n case 0:\n callback();\n break;\n case 1:\n callback(args[0]);\n break;\n case 2:\n callback(args[0], args[1]);\n break;\n case 3:\n callback(args[0], args[1], args[2]);\n break;\n default:\n callback.apply(undefined, args);\n break;\n }\n }\n\n function runIfPresent(handle) {\n // From the spec: \"Wait until any invocations of this algorithm started before this one have completed.\"\n // So if we're currently running a task, we'll need to delay this invocation.\n if (currentlyRunningATask) {\n // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a\n // \"too much recursion\" error.\n setTimeout(runIfPresent, 0, handle);\n } else {\n var task = tasksByHandle[handle];\n if (task) {\n currentlyRunningATask = true;\n try {\n run(task);\n } finally {\n clearImmediate(handle);\n currentlyRunningATask = false;\n }\n }\n }\n }\n\n function installNextTickImplementation() {\n registerImmediate = function(handle) {\n process.nextTick(function () { runIfPresent(handle); });\n };\n }\n\n function canUsePostMessage() {\n // The test against `importScripts` prevents this implementation from being installed inside a web worker,\n // where `global.postMessage` means something completely different and can't be used for this purpose.\n if (global.postMessage && !global.importScripts) {\n var postMessageIsAsynchronous = true;\n var oldOnMessage = global.onmessage;\n global.onmessage = function() {\n postMessageIsAsynchronous = false;\n };\n global.postMessage(\"\", \"*\");\n global.onmessage = oldOnMessage;\n return postMessageIsAsynchronous;\n }\n }\n\n function installPostMessageImplementation() {\n // Installs an event handler on `global` for the `message` event: see\n // * https://developer.mozilla.org/en/DOM/window.postMessage\n // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages\n\n var messagePrefix = \"setImmediate$\" + Math.random() + \"$\";\n var onGlobalMessage = function(event) {\n if (event.source === global &&\n typeof event.data === \"string\" &&\n event.data.indexOf(messagePrefix) === 0) {\n runIfPresent(+event.data.slice(messagePrefix.length));\n }\n };\n\n if (global.addEventListener) {\n global.addEventListener(\"message\", onGlobalMessage, false);\n } else {\n global.attachEvent(\"onmessage\", onGlobalMessage);\n }\n\n registerImmediate = function(handle) {\n global.postMessage(messagePrefix + handle, \"*\");\n };\n }\n\n function installMessageChannelImplementation() {\n var channel = new MessageChannel();\n channel.port1.onmessage = function(event) {\n var handle = event.data;\n runIfPresent(handle);\n };\n\n registerImmediate = function(handle) {\n channel.port2.postMessage(handle);\n };\n }\n\n function installReadyStateChangeImplementation() {\n var html = doc.documentElement;\n registerImmediate = function(handle) {\n // Create a ';\n }\n var iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n Object(util[\"s\" /* log */])('frame writing exception');\n if (e.stack) {\n Object(util[\"s\" /* log */])(e.stack);\n }\n Object(util[\"s\" /* log */])(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n * @private\r\n * @return {Element}\r\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 Object(util[\"s\" /* log */])('No IE domain setting required');\n }\n } catch (e) {\n var domain = document.domain;\n iframe.src = \"javascript:void((function(){document.open();document.domain='\" + domain + \"';document.close();})())\";\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 } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n } else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n return iframe;\n };\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\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 (Object(environment[\"b\" /* isNodeSdk */])() && this.myID) {\n var urlParams = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[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 /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param {!string} id - The ID of this connection\r\n * @param {!string} pw - The password for this connection\r\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 /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\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 && this.sendNewPolls && this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[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 <= MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString = curDataString + '&' + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + i + '=' + theSeg.seg + '&' + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + i + '=' + theSeg.ts + '&' + FIREBASE_LONGPOLL_DATA_PARAM + i + '=' + theSeg.d;\n i++;\n } else {\n break;\n }\n }\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n } else {\n return false;\n }\n };\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\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 /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param {!string} url - The URL of the script tag.\r\n * @param {!number} serial - The serial number of the request.\r\n * @private\r\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 doNewRequest() {\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 readyStateCB() {\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 /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param {!string} url - The URL for the script tag source.\r\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\r\n */\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n if (Object(environment[\"b\" /* isNodeSdk */])()) {\n this.doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls) 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 Object(util[\"s\" /* 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 } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n return FirebaseIFrameScriptHolder;\n}();\n\n\n/***/ }),\n/* 54 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* WEBPACK VAR INJECTION */(function(process) {/* unused harmony export setWebSocketImpl */\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return WebSocketConnection; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__app__ = __webpack_require__(9);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__utils_assert__ = __webpack_require__(0);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__core_util_util__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__core_stats_StatsManager__ = __webpack_require__(29);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__Constants__ = __webpack_require__(19);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__utils_constants__ = __webpack_require__(17);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__core_storage_storage__ = __webpack_require__(18);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__utils_json__ = __webpack_require__(8);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_environment__ = __webpack_require__(13);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n\n\n\n\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\nfunction setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n * @constructor\r\n * @implements {Transport}\r\n */\nvar WebSocketConnection = /** @class */function () {\n /**\r\n * @param {string} connId identifier for this transport\r\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\r\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\r\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_ = Object(__WEBPACK_IMPORTED_MODULE_2__core_util_util__[\"t\" /* logWrapper */])(this.connId);\n this.stats_ = __WEBPACK_IMPORTED_MODULE_3__core_stats_StatsManager__[\"a\" /* StatsManager */].getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\r\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\r\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\r\n * @return {string} connection url\r\n * @private\r\n */\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[__WEBPACK_IMPORTED_MODULE_4__Constants__[\"h\" /* VERSION_PARAM */]] = __WEBPACK_IMPORTED_MODULE_4__Constants__[\"e\" /* PROTOCOL_VERSION */];\n if (!Object(__WEBPACK_IMPORTED_MODULE_8__utils_environment__[\"b\" /* isNodeSdk */])() && typeof location !== 'undefined' && location.href && location.href.indexOf(__WEBPACK_IMPORTED_MODULE_4__Constants__[\"a\" /* FORGE_DOMAIN */]) !== -1) {\n urlParams[__WEBPACK_IMPORTED_MODULE_4__Constants__[\"f\" /* REFERER_PARAM */]] = __WEBPACK_IMPORTED_MODULE_4__Constants__[\"b\" /* FORGE_REF */];\n }\n if (transportSessionId) {\n urlParams[__WEBPACK_IMPORTED_MODULE_4__Constants__[\"g\" /* TRANSPORT_SESSION_PARAM */]] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[__WEBPACK_IMPORTED_MODULE_4__Constants__[\"c\" /* LAST_SESSION_PARAM */]] = lastSessionId;\n }\n return repoInfo.connectionURL(__WEBPACK_IMPORTED_MODULE_4__Constants__[\"i\" /* WEBSOCKET */], urlParams);\n };\n /**\r\n *\r\n * @param onMessage Callback when messages arrive\r\n * @param onDisconnect Callback with connection lost.\r\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 __WEBPACK_IMPORTED_MODULE_6__core_storage_storage__[\"a\" /* PersistentStorage */].set('previous_websocket_failure', true);\n try {\n if (Object(__WEBPACK_IMPORTED_MODULE_8__utils_environment__[\"b\" /* isNodeSdk */])()) {\n var device = __WEBPACK_IMPORTED_MODULE_5__utils_constants__[\"a\" /* CONSTANTS */].NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + __WEBPACK_IMPORTED_MODULE_4__Constants__[\"e\" /* PROTOCOL_VERSION */] + \"/\" + __WEBPACK_IMPORTED_MODULE_0__app__[\"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 ? env['HTTPS_PROXY'] || env['https_proxy'] : env['HTTP_PROXY'] || env['http_proxy'];\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } else {\n this.mySock = new WebSocketImpl(this.connURL);\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 /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\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 && WebSocketImpl !== null && !WebSocketConnection.forceDisallow_;\n };\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n * @return {boolean}\r\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 __WEBPACK_IMPORTED_MODULE_6__core_storage_storage__[\"a\" /* PersistentStorage */].isInMemoryStorage || __WEBPACK_IMPORTED_MODULE_6__core_storage_storage__[\"a\" /* PersistentStorage */].get('previous_websocket_failure') === true;\n };\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n __WEBPACK_IMPORTED_MODULE_6__core_storage_storage__[\"a\" /* 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 = Object(__WEBPACK_IMPORTED_MODULE_7__utils_json__[\"a\" /* jsonEval */])(fullMess);\n //handle the message\n this.onMessage(jsonMess);\n }\n };\n /**\r\n * @param {number} frameCount The number of frames we are expecting from the server\r\n * @private\r\n */\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @param {!String} data\r\n * @return {?String} Any remaining data to be process, or null if there is none\r\n * @private\r\n */\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n Object(__WEBPACK_IMPORTED_MODULE_1__utils_assert__[\"a\" /* 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 /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess The frame data\r\n */\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null) 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 } 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 /**\r\n * Send a message to the server\r\n * @param {Object} data The JSON object to transmit\r\n */\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = Object(__WEBPACK_IMPORTED_MODULE_7__utils_json__[\"b\" /* 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 = Object(__WEBPACK_IMPORTED_MODULE_2__core_util_util__[\"z\" /* 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 /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\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 /**\r\n * Send a string over the websocket.\r\n *\r\n * @param {string} str String to send.\r\n * @private\r\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 } 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 /**\r\n * Number of response before we consider the connection \"healthy.\"\r\n * @type {number}\r\n */\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\r\n * Time to wait for the connection te become healthy before giving up.\r\n * @type {number}\r\n */\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}();\n\n/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(34)))\n\n/***/ }),\n/* 55 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return ServerActions; });\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\nvar ServerActions = /** @class */function () {\n function ServerActions() {}\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n * @param {string=} hash\r\n */\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) {};\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, ?string)} onComplete\r\n * @param {string=} hash\r\n */\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) {};\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param {string} token The authentication token\r\n */\n ServerActions.prototype.refreshAuthToken = function (token) {};\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n */\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) {};\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n */\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) {};\n /**\r\n * @param {string} pathString\r\n * @param {function(string, string)=} onComplete\r\n */\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) {};\n /**\r\n * @param {Object.} stats\r\n */\n ServerActions.prototype.reportStats = function (stats) {};\n return ServerActions;\n}();\n\n\n/***/ }),\n/* 56 */,\n/* 57 */,\n/* 58 */,\n/* 59 */,\n/* 60 */,\n/* 61 */,\n/* 62 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* WEBPACK VAR INJECTION */(function(module) {/* harmony export (immutable) */ __webpack_exports__[\"registerDatabase\"] = registerDatabase;\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__app__ = __webpack_require__(9);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__database_api_Database__ = __webpack_require__(36);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__database_api_Query__ = __webpack_require__(39);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__database_api_Reference__ = __webpack_require__(26);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__database_core_util_util__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__database_core_RepoManager__ = __webpack_require__(30);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__database_api_internal__ = __webpack_require__(64);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__database_api_test_access__ = __webpack_require__(65);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__utils_environment__ = __webpack_require__(13);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n\n\n\n\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) {\n return __WEBPACK_IMPORTED_MODULE_5__database_core_RepoManager__[\"a\" /* RepoManager */].getInstance().databaseFromApp(app, url);\n },\n // firebase.database namespace properties\n {\n Reference: __WEBPACK_IMPORTED_MODULE_3__database_api_Reference__[\"a\" /* Reference */],\n Query: __WEBPACK_IMPORTED_MODULE_2__database_api_Query__[\"a\" /* Query */],\n Database: __WEBPACK_IMPORTED_MODULE_1__database_api_Database__[\"a\" /* Database */],\n enableLogging: __WEBPACK_IMPORTED_MODULE_4__database_core_util_util__[\"j\" /* enableLogging */],\n INTERNAL: __WEBPACK_IMPORTED_MODULE_6__database_api_internal__,\n ServerValue: __WEBPACK_IMPORTED_MODULE_1__database_api_Database__[\"a\" /* Database */].ServerValue,\n TEST_ACCESS: __WEBPACK_IMPORTED_MODULE_7__database_api_test_access__\n }, null, true);\n if (Object(__WEBPACK_IMPORTED_MODULE_8__utils_environment__[\"b\" /* isNodeSdk */])()) {\n module.exports = namespace;\n }\n}\nregisterDatabase(__WEBPACK_IMPORTED_MODULE_0__app__[\"default\"]);\n/* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(63)(module)))\n\n/***/ }),\n/* 63 */\n/***/ (function(module, exports) {\n\nmodule.exports = function(originalModule) {\r\n\tif(!originalModule.webpackPolyfill) {\r\n\t\tvar module = Object.create(originalModule);\r\n\t\t// module.parent = undefined by default\r\n\t\tif(!module.children) module.children = [];\r\n\t\tObject.defineProperty(module, \"loaded\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.l;\r\n\t\t\t}\r\n\t\t});\r\n\t\tObject.defineProperty(module, \"id\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.i;\r\n\t\t\t}\r\n\t\t});\r\n\t\tObject.defineProperty(module, \"exports\", {\r\n\t\t\tenumerable: true,\r\n\t\t});\r\n\t\tmodule.webpackPolyfill = 1;\r\n\t}\r\n\treturn module;\r\n};\r\n\n\n/***/ }),\n/* 64 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"forceLongPolling\", function() { return forceLongPolling; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"forceWebSockets\", function() { return forceWebSockets; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"isWebSocketsAvailable\", function() { return isWebSocketsAvailable; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"setSecurityDebugCallback\", function() { return setSecurityDebugCallback; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"stats\", function() { return stats; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"statsIncrementCounter\", function() { return statsIncrementCounter; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"dataUpdateCount\", function() { return dataUpdateCount; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"interceptServerData\", function() { return interceptServerData; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__realtime_WebSocketConnection__ = __webpack_require__(54);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__realtime_BrowserPollConnection__ = __webpack_require__(53);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n/**\r\n * INTERNAL methods for internal-use only (tests, etc.).\r\n *\r\n * Customers shouldn't use these or else should be aware that they could break at any time.\r\n *\r\n * @const\r\n */\nvar forceLongPolling = function forceLongPolling() {\n __WEBPACK_IMPORTED_MODULE_0__realtime_WebSocketConnection__[\"a\" /* WebSocketConnection */].forceDisallow();\n __WEBPACK_IMPORTED_MODULE_1__realtime_BrowserPollConnection__[\"a\" /* BrowserPollConnection */].forceAllow();\n};\nvar forceWebSockets = function forceWebSockets() {\n __WEBPACK_IMPORTED_MODULE_1__realtime_BrowserPollConnection__[\"a\" /* BrowserPollConnection */].forceDisallow();\n};\n/* Used by App Manager */\nvar isWebSocketsAvailable = function isWebSocketsAvailable() {\n return __WEBPACK_IMPORTED_MODULE_0__realtime_WebSocketConnection__[\"a\" /* WebSocketConnection */]['isAvailable']();\n};\nvar setSecurityDebugCallback = function setSecurityDebugCallback(ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\nvar stats = function stats(ref, showDelta) {\n ref.repo.stats(showDelta);\n};\nvar statsIncrementCounter = function statsIncrementCounter(ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\nvar dataUpdateCount = function dataUpdateCount(ref) {\n return ref.repo.dataUpdateCount;\n};\nvar interceptServerData = function interceptServerData(ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\n/***/ }),\n/* 65 */\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"DataConnection\", function() { return DataConnection; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"RealTimeConnection\", function() { return RealTimeConnection; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"hijackHash\", function() { return hijackHash; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ConnectionTarget\", function() { return ConnectionTarget; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"queryIdentifier\", function() { return queryIdentifier; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"listens\", function() { return listens; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"forceRestClient\", function() { return forceRestClient; });\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__core_RepoInfo__ = __webpack_require__(38);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__ = __webpack_require__(51);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__core_RepoManager__ = __webpack_require__(30);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__realtime_Connection__ = __webpack_require__(52);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\nvar DataConnection = __WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__[\"a\" /* PersistentConnection */];\n/**\r\n * @param {!string} pathString\r\n * @param {function(*)} onComplete\r\n */\n__WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__[\"a\" /* PersistentConnection */].prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n/**\r\n * @param {*} data\r\n * @param {function(*)} onEcho\r\n */\n__WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__[\"a\" /* PersistentConnection */].prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n// RealTimeConnection properties that we use in tests.\nvar RealTimeConnection = __WEBPACK_IMPORTED_MODULE_3__realtime_Connection__[\"a\" /* Connection */];\n/**\r\n * @param {function(): string} newHash\r\n * @return {function()}\r\n */\nvar hijackHash = function hijackHash(newHash) {\n var oldPut = __WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__[\"a\" /* PersistentConnection */].prototype.put;\n __WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__[\"a\" /* 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 __WEBPACK_IMPORTED_MODULE_1__core_PersistentConnection__[\"a\" /* PersistentConnection */].prototype.put = oldPut;\n };\n};\n/**\r\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\r\n */\nvar ConnectionTarget = __WEBPACK_IMPORTED_MODULE_0__core_RepoInfo__[\"a\" /* RepoInfo */];\n/**\r\n * @param {!Query} query\r\n * @return {!string}\r\n */\nvar queryIdentifier = function queryIdentifier(query) {\n return query.queryIdentifier();\n};\n/**\r\n * @param {!Query} firebaseRef\r\n * @return {!Object}\r\n */\nvar listens = function listens(firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n *\r\n * @param {boolean} forceRestClient\r\n */\nvar forceRestClient = function forceRestClient(_forceRestClient) {\n __WEBPACK_IMPORTED_MODULE_2__core_RepoManager__[\"a\" /* RepoManager */].getInstance().forceRestClient(_forceRestClient);\n};\n\n/***/ })\n],[62]);\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","/**\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\nimport { CONSTANTS } from './constants';\n\n/**\n * Throws an error if the provided assertion is falsy\n * @param {*} assertion The assertion to be tested for falsiness\n * @param {!string} message The message to display if the check fails\n */\nexport const assert = function(assertion, message) {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n * @param {string} message\n * @return {!Error}\n */\nexport const assertionError = function(message) {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/assert.ts","/**\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\nimport { globalScope } from './globalScope';\n\nconst stringToByteArray = function(str) {\n var output = [],\n p = 0;\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\n while (c > 255) {\n output[p++] = c & 255;\n c >>= 8;\n }\n output[p++] = c;\n }\n return output;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param {Array} bytes Array of numbers representing characters.\n * @return {string} Stringification of the array.\n */\nconst byteArrayToString = function(bytes) {\n var CHUNK_SIZE = 8192;\n\n // Special-case the simple case for speed's sake.\n if (bytes.length < CHUNK_SIZE) {\n return String.fromCharCode.apply(null, bytes);\n }\n\n // The remaining logic splits conversion by chunks since\n // Function#apply() has a maximum parameter count.\n // See discussion: http://goo.gl/LrWmZ9\n\n var str = '';\n for (var i = 0; i < bytes.length; i += CHUNK_SIZE) {\n var chunk = bytes.slice(i, i + CHUNK_SIZE);\n str += String.fromCharCode.apply(null, chunk);\n }\n return str;\n};\n\n// Static lookup maps, lazily populated by init_()\nexport const base64 = {\n /**\n * Maps bytes to characters.\n * @type {Object}\n * @private\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n * @type {Object}\n * @private\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @type {Object}\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @type {Object}\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n * @type {string}\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n * @type {string}\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n * @type {string}\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n * @type {boolean}\n */\n HAS_NATIVE_SUPPORT: typeof globalScope.atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param {Array|Uint8Array} input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param {boolean=} opt_webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return {string} The base64 encoded string.\n */\n encodeByteArray(input, opt_webSafe?) {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n var byteToCharMap = opt_webSafe\n ? this.byteToCharMapWebSafe_\n : this.byteToCharMap_;\n\n var output = [];\n\n for (var i = 0; i < input.length; i += 3) {\n var byte1 = input[i];\n var haveByte2 = i + 1 < input.length;\n var byte2 = haveByte2 ? input[i + 1] : 0;\n var haveByte3 = i + 2 < input.length;\n var byte3 = haveByte3 ? input[i + 2] : 0;\n\n var outByte1 = byte1 >> 2;\n var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n var outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n var outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param {string} input A string to encode.\n * @param {boolean=} opt_webSafe If true, we should use the\n * alternative alphabet.\n * @return {string} The base64 encoded string.\n */\n encodeString(input, opt_webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), opt_webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param {string} input to decode.\n * @param {boolean=} opt_webSafe True if we should use the\n * alternative alphabet.\n * @return {string} string representing the decoded value.\n */\n decodeString(input, opt_webSafe) {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !opt_webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, opt_webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param {string} input Input to decode.\n * @param {boolean=} opt_webSafe True if we should use the web-safe alphabet.\n * @return {!Array} bytes representing the decoded value.\n */\n decodeStringToByteArray(input, opt_webSafe) {\n this.init_();\n\n var charToByteMap = opt_webSafe\n ? this.charToByteMapWebSafe_\n : this.charToByteMap_;\n\n var output = [];\n\n for (var i = 0; i < input.length; ) {\n var byte1 = charToByteMap[input.charAt(i++)];\n\n var haveByte2 = i < input.length;\n var byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n var haveByte3 = i < input.length;\n var byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n var haveByte4 = i < input.length;\n var byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw Error();\n }\n\n var outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 != 64) {\n var outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 != 64) {\n var outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (var i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/crypt.ts","/**\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\n// Copyright 2011 The Closure Library Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * @fileoverview Abstract cryptographic hash interface.\n *\n * See Sha1 and Md5 for sample implementations.\n *\n */\n\n/**\n * Create a cryptographic hash instance.\n *\n * @constructor\n * @struct\n */\nexport class Hash {\n /**\n * The block size for the hasher.\n * @type {number}\n */\n blockSize: number = -1;\n\n constructor() {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/hash.ts","/**\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\nimport { Hash } from './hash';\n\n/**\n * @fileoverview SHA-1 cryptographic hash.\n * Variable names follow the notation in FIPS PUB 180-3:\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\n *\n * Usage:\n * var sha1 = new sha1();\n * sha1.update(bytes);\n * var hash = sha1.digest();\n *\n * Performance:\n * Chrome 23: ~400 Mbit/s\n * Firefox 16: ~250 Mbit/s\n *\n */\n\n/**\n * SHA-1 cryptographic hash constructor.\n *\n * The properties declared here are discussed in the above algorithm document.\n * @constructor\n * @extends {Hash}\n * @final\n * @struct\n */\nexport class Sha1 extends Hash {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @type {!Array}\n * @private\n */\n private chain_: Array = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @type {!Array}\n * @private\n */\n private buf_: Array = [];\n\n /**\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\n * as the message schedule in the docs.\n * @type {!Array}\n * @private\n */\n private W_: Array = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @type {!Array}\n * @private\n */\n private pad_: Array = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n constructor() {\n super();\n\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (var i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset() {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n\n this.inbuf_ = 0;\n this.total_ = 0;\n }\n\n /**\n * Internal compress helper function.\n * @param {!Array|!Uint8Array|string} buf Block to compress.\n * @param {number=} opt_offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf, opt_offset?) {\n if (!opt_offset) {\n opt_offset = 0;\n }\n\n var W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (var i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] =\n (buf.charCodeAt(opt_offset) << 24) |\n (buf.charCodeAt(opt_offset + 1) << 16) |\n (buf.charCodeAt(opt_offset + 2) << 8) |\n buf.charCodeAt(opt_offset + 3);\n opt_offset += 4;\n }\n } else {\n for (var i = 0; i < 16; i++) {\n W[i] =\n (buf[opt_offset] << 24) |\n (buf[opt_offset + 1] << 16) |\n (buf[opt_offset + 2] << 8) |\n buf[opt_offset + 3];\n opt_offset += 4;\n }\n }\n\n // expand to 80 words\n for (var i = 16; i < 80; i++) {\n var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n var a = this.chain_[0];\n var b = this.chain_[1];\n var c = this.chain_[2];\n var d = this.chain_[3];\n var e = this.chain_[4];\n var f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (var i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ (b & (c ^ d));\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = (b & c) | (d & (b | c));\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n var t = (((a << 5) | (a >>> 27)) + f + e + k + W[i]) & 0xffffffff;\n e = d;\n d = c;\n c = ((b << 30) | (b >>> 2)) & 0xffffffff;\n b = a;\n a = t;\n }\n\n this.chain_[0] = (this.chain_[0] + a) & 0xffffffff;\n this.chain_[1] = (this.chain_[1] + b) & 0xffffffff;\n this.chain_[2] = (this.chain_[2] + c) & 0xffffffff;\n this.chain_[3] = (this.chain_[3] + d) & 0xffffffff;\n this.chain_[4] = (this.chain_[4] + e) & 0xffffffff;\n }\n\n update(bytes, opt_length?) {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (opt_length === undefined) {\n opt_length = bytes.length;\n }\n\n var lengthMinusBlock = opt_length - this.blockSize;\n var n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n var buf = this.buf_;\n var inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < opt_length) {\n // When we have no data in the block to top up, we can directly process the\n // input buffer (assuming it contains sufficient data). This gives ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf == 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < opt_length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n if (inbuf == this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n } else {\n while (n < opt_length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n if (inbuf == this.blockSize) {\n this.compress_(buf);\n inbuf = 0;\n // Jump to the outer loop so we use the full-block optimization.\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += opt_length;\n }\n\n /** @override */\n digest() {\n var digest = [];\n var totalBits = this.total_ * 8;\n\n // Add pad 0x80 0x00*.\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n }\n\n // Add # bits.\n for (var i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n\n var n = 0;\n for (var i = 0; i < 5; i++) {\n for (var j = 24; j >= 0; j -= 8) {\n digest[n] = (this.chain_[i] >> j) & 255;\n ++n;\n }\n }\n return digest;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/Sha1.ts","/**\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\nimport { Query } from '../../api/Query';\n\ndeclare const window: any;\ndeclare const Windows: any;\n\nimport { assert } from '../../../utils/assert';\nimport { forEach } from '../../../utils/obj';\nimport { base64 } from '../../../utils/crypt';\nimport { Sha1 } from '../../../utils/Sha1';\nimport { stringToByteArray } from '../../../utils/utf8';\nimport { stringify } from '../../../utils/json';\nimport { SessionStorage } from '../storage/storage';\nimport { isNodeSdk } from '../../../utils/environment';\n\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 */\nexport const LUIDGenerator: (() => number) = (function() {\n let id = 1;\n return function() {\n return id++;\n };\n})();\n\n/**\n * URL-safe base64 encoding\n * @param {!string} str\n * @return {!string}\n */\nexport const base64Encode = function(str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, /*useWebSafe=*/ true);\n};\n\nlet BufferImpl;\nexport function setBufferImpl(impl) {\n BufferImpl = impl;\n}\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param {string} str To be decoded\n * @return {?string} Decoded result, if possible\n */\nexport const base64Decode = function(str: string): string | null {\n try {\n if (BufferImpl) {\n return new BufferImpl(str, 'base64').toString('utf8');\n } else {\n return base64.decodeString(str, /*useWebSafe=*/ true);\n }\n } catch (e) {\n log('base64Decode failed: ', e);\n }\n return null;\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 */\nexport const sha1 = function(str: string): string {\n const utf8Bytes = stringToByteArray(str);\n const sha1 = new Sha1();\n sha1.update(utf8Bytes);\n const sha1Bytes = sha1.digest();\n return base64.encodeByteArray(sha1Bytes);\n};\n\n/**\n * @param {...*} var_args\n * @return {string}\n * @private\n */\nconst buildLogMessage_ = function(...var_args: any[]): string {\n let message = '';\n for (let i = 0; i < var_args.length; i++) {\n if (\n Array.isArray(var_args[i]) ||\n (var_args[i] &&\n typeof var_args[i] === 'object' &&\n typeof var_args[i].length === 'number')\n ) {\n message += buildLogMessage_.apply(null, var_args[i]);\n } else if (typeof var_args[i] === 'object') {\n message += stringify(var_args[i]);\n } else {\n message += var_args[i];\n }\n message += ' ';\n }\n\n return message;\n};\n\n/**\n * Use this for all debug messages in Firebase.\n * @type {?function(string)}\n */\nexport let logger: ((a: string) => void) | null = null;\n\n/**\n * Flag to check for log availability on first log message\n * @type {boolean}\n * @private\n */\nlet firstLog_ = true;\n\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 */\nexport const enableLogging = function(\n logger_?: boolean | ((a: string) => void) | null,\n persistent?: boolean\n) {\n assert(\n !persistent || (logger_ === true || logger_ === false),\n \"Can't turn on custom loggers persistently.\"\n );\n if (logger_ === true) {\n if (typeof console !== 'undefined') {\n if (typeof console.log === 'function') {\n logger = console.log.bind(console);\n } else if (typeof console.log === 'object') {\n // IE does this.\n logger = function(message) {\n console.log(message);\n };\n }\n }\n if (persistent) SessionStorage.set('logging_enabled', true);\n } else if (typeof logger_ === 'function') {\n logger = logger_;\n } else {\n logger = null;\n SessionStorage.remove('logging_enabled');\n }\n};\n\n/**\n *\n * @param {...(string|Arguments)} var_args\n */\nexport const log = function(...var_args: string[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true)\n enableLogging(true);\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, var_args);\n logger(message);\n }\n};\n\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexport const logWrapper = function(\n prefix: string\n): (...var_args: any[]) => void {\n return function(...var_args: any[]) {\n log(prefix, ...var_args);\n };\n};\n\n/**\n * @param {...string} var_args\n */\nexport const error = function(...var_args: string[]) {\n if (typeof console !== 'undefined') {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...var_args);\n if (typeof console.error !== 'undefined') {\n console.error(message);\n } else {\n console.log(message);\n }\n }\n};\n\n/**\n * @param {...string} var_args\n */\nexport const fatal = function(...var_args: string[]) {\n const message = buildLogMessage_(...var_args);\n throw new Error('FIREBASE FATAL ERROR: ' + message);\n};\n\n/**\n * @param {...*} var_args\n */\nexport const warn = function(...var_args: any[]) {\n if (typeof console !== 'undefined') {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...var_args);\n if (typeof console.warn !== 'undefined') {\n console.warn(message);\n } else {\n console.log(message);\n }\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 */\nexport const warnIfPageIsSecure = function() {\n // Be very careful accessing browser globals. Who knows what may or may not exist.\n if (\n typeof window !== 'undefined' &&\n window.location &&\n window.location.protocol &&\n window.location.protocol.indexOf('https:') !== -1\n ) {\n warn(\n 'Insecure Firebase access from a secure page. ' +\n 'Please use https in calls to new Firebase().'\n );\n }\n};\n\n/**\n * @param {!String} methodName\n */\nexport const warnAboutUnsupportedMethod = function(methodName: string) {\n warn(\n methodName +\n ' is unsupported and will likely change soon. ' +\n 'Please do not use.'\n );\n};\n\n/**\n * Returns true if data is NaN, or +/- Infinity.\n * @param {*} data\n * @return {boolean}\n */\nexport const isInvalidJSONNumber = function(data: any): boolean {\n return (\n typeof data === 'number' &&\n (data != data || // NaN\n data == Number.POSITIVE_INFINITY ||\n data == Number.NEGATIVE_INFINITY)\n );\n};\n\n/**\n * @param {function()} fn\n */\nexport const executeWhenDOMReady = function(fn: () => void) {\n if (isNodeSdk() || document.readyState === 'complete') {\n fn();\n } else {\n // Modeled after jQuery. Try DOMContentLoaded and onreadystatechange (which\n // fire before onload), but fall back to onload.\n\n let called = false;\n let wrappedFn = function() {\n if (!document.body) {\n setTimeout(wrappedFn, Math.floor(10));\n return;\n }\n\n if (!called) {\n called = true;\n fn();\n }\n };\n\n if (document.addEventListener) {\n document.addEventListener('DOMContentLoaded', wrappedFn, false);\n // fallback to onload.\n window.addEventListener('load', wrappedFn, false);\n } else if ((document as any).attachEvent) {\n // IE.\n (document as any).attachEvent('onreadystatechange', function() {\n if (document.readyState === 'complete') wrappedFn();\n });\n // fallback to onload.\n (window as any).attachEvent('onload', wrappedFn);\n\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/**\n * Minimum key name. Invalid for actual data, used as a marker to sort before any valid names\n * @type {!string}\n */\nexport const MIN_NAME = '[MIN_NAME]';\n\n/**\n * Maximum key name. Invalid for actual data, used as a marker to sort above any valid names\n * @type {!string}\n */\nexport const MAX_NAME = '[MAX_NAME]';\n\n/**\n * Compares valid Firebase key names, plus min and max name\n * @param {!string} a\n * @param {!string} b\n * @return {!number}\n */\nexport const nameCompare = function(a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a === MIN_NAME || b === MAX_NAME) {\n return -1;\n } else if (b === MIN_NAME || a === MAX_NAME) {\n return 1;\n } else {\n const aAsInt = tryParseInt(a),\n bAsInt = tryParseInt(b);\n\n if (aAsInt !== null) {\n if (bAsInt !== null) {\n return aAsInt - bAsInt == 0 ? a.length - b.length : aAsInt - bAsInt;\n } else {\n return -1;\n }\n } else if (bAsInt !== null) {\n return 1;\n } else {\n return a < b ? -1 : 1;\n }\n }\n};\n\n/**\n * @param {!string} a\n * @param {!string} b\n * @return {!number} comparison result.\n */\nexport const stringCompare = function(a: string, b: string): number {\n if (a === b) {\n return 0;\n } else if (a < b) {\n return -1;\n } else {\n return 1;\n }\n};\n\n/**\n * @param {string} key\n * @param {Object} obj\n * @return {*}\n */\nexport const requireKey = function(\n key: string,\n obj: { [k: string]: any }\n): any {\n if (obj && key in obj) {\n return obj[key];\n } else {\n throw new Error(\n 'Missing required key (' + key + ') in object: ' + stringify(obj)\n );\n }\n};\n\n/**\n * @param {*} obj\n * @return {string}\n */\nexport const ObjectToUniqueKey = function(obj: any): string {\n if (typeof obj !== 'object' || obj === null) return stringify(obj);\n\n const keys = [];\n for (let k in obj) {\n keys.push(k);\n }\n\n // Export as json, but with the keys sorted.\n keys.sort();\n let key = '{';\n for (let i = 0; i < keys.length; i++) {\n if (i !== 0) key += ',';\n key += stringify(keys[i]);\n key += ':';\n key += ObjectToUniqueKey(obj[keys[i]]);\n }\n\n key += '}';\n return key;\n};\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 */\nexport const splitStringBySize = function(\n str: string,\n segsize: number\n): string[] {\n const len = str.length;\n\n if (len <= segsize) {\n return [str];\n }\n\n const dataSegs = [];\n for (let c = 0; c < len; c += segsize) {\n if (c + segsize > len) {\n dataSegs.push(str.substring(c, len));\n } else {\n dataSegs.push(str.substring(c, c + segsize));\n }\n }\n return dataSegs;\n};\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 */\nexport const each = function(\n obj: Object | Array,\n fn: (v?: any, k?: any) => void\n) {\n if (Array.isArray(obj)) {\n for (let i = 0; i < obj.length; ++i) {\n fn(i, obj[i]);\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 forEach(obj, (key: any, val: any) => fn(val, key));\n }\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 */\nexport const bindCallback = function(\n callback: (a: any) => void,\n context?: object | null\n): Function {\n return context ? callback.bind(context) : callback;\n};\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 */\nexport const doubleToIEEE754String = function(v: number): string {\n assert(!isInvalidJSONNumber(v), 'Invalid JSON number'); // MJL\n\n const ebits = 11,\n fbits = 52;\n let bias = (1 << (ebits - 1)) - 1,\n s,\n e,\n f,\n ln,\n i,\n bits,\n str;\n\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 } else {\n s = v < 0;\n v = Math.abs(v);\n\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 } else {\n // Denormalized\n e = 0;\n f = Math.round(v / Math.pow(2, 1 - bias - fbits));\n }\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\n // Return the data as a hex string. --MJL\n let hexByteString = '';\n for (i = 0; i < 64; i += 8) {\n let hexByte = parseInt(str.substr(i, 8), 2).toString(16);\n if (hexByte.length === 1) hexByte = '0' + hexByte;\n hexByteString = hexByteString + hexByte;\n }\n return hexByteString.toLowerCase();\n};\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 */\nexport const isChromeExtensionContentScript = function(): boolean {\n return !!(\n typeof window === 'object' &&\n window['chrome'] &&\n window['chrome']['extension'] &&\n !/^chrome/.test(window.location.href)\n );\n};\n\n/**\n * Used to detect if we're in a Windows 8 Store app.\n * @return {boolean}\n */\nexport const isWindowsStoreApp = function(): boolean {\n // Check for the presence of a couple WinRT globals\n return typeof Windows === 'object' && typeof Windows.UI === 'object';\n};\n\n/**\n * Converts a server error code to a Javascript Error\n * @param {!string} code\n * @param {!Query} query\n * @return {Error}\n */\nexport const errorForServerCode = function(code: string, query: Query): Error {\n let 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 } else if (code == 'permission_denied') {\n reason = \"Client doesn't have permission to access the desired data.\";\n } else if (code == 'unavailable') {\n reason = 'The service is unavailable';\n }\n\n const error = new Error(\n code + ' at ' + query.path.toString() + ': ' + reason\n );\n (error as any).code = code.toUpperCase();\n return error;\n};\n\n/**\n * Used to test for integer-looking strings\n * @type {RegExp}\n * @private\n */\nexport const INTEGER_REGEXP_ = new RegExp('^-?\\\\d{1,10}$');\n\n/**\n * If the string contains a 32-bit integer, return it. Else return null.\n * @param {!string} str\n * @return {?number}\n */\nexport const tryParseInt = function(str: string): number | null {\n if (INTEGER_REGEXP_.test(str)) {\n const intVal = Number(str);\n if (intVal >= -2147483648 && intVal <= 2147483647) {\n return intVal;\n }\n }\n return null;\n};\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 */\nexport const exceptionGuard = function(fn: () => void) {\n try {\n fn();\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 const stack = e.stack || '';\n warn('Exception was thrown by user callback.', stack);\n throw e;\n }, Math.floor(0));\n }\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 */\nexport const callUserCallback = function(\n callback?: Function | null,\n ...var_args: any[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(function() {\n callback(...var_args);\n });\n }\n};\n\n/**\n * @return {boolean} true if we think we're currently being crawled.\n */\nexport const beingCrawled = function(): boolean {\n const userAgent =\n (typeof window === 'object' &&\n window['navigator'] &&\n window['navigator']['userAgent']) ||\n '';\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 (\n userAgent.search(\n /googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i\n ) >= 0\n );\n};\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 */\nexport const exportPropGetter = function(\n object: Object,\n name: string,\n fnGet: () => any\n) {\n Object.defineProperty(object, name, { get: fnGet });\n};\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 */\nexport const setTimeoutNonBlocking = function(\n fn: Function,\n time: number\n): number | Object {\n const timeout: number | Object = setTimeout(fn, time);\n if (typeof timeout === 'object' && (timeout as any)['unref']) {\n (timeout as any)['unref']();\n }\n return timeout;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/util.ts","/**\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\n// See http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/\n\nexport const contains = function(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nexport const safeGet = function(obj, key) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) return obj[key];\n // else return undefined.\n};\n\n/**\n * Enumerates the keys/values in an object, excluding keys defined on the prototype.\n *\n * @param {?Object.} obj Object to enumerate.\n * @param {!function(K, V)} fn Function to call for each key and value.\n * @template K,V\n */\nexport const forEach = function(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n};\n\n/**\n * Copies all the (own) properties from one object to another.\n * @param {!Object} objTo\n * @param {!Object} objFrom\n * @return {!Object} objTo\n */\nexport const extend = function(objTo, objFrom) {\n forEach(objFrom, function(key, value) {\n objTo[key] = value;\n });\n return objTo;\n};\n\n/**\n * Returns a clone of the specified object.\n * @param {!Object} obj\n * @return {!Object} cloned obj.\n */\nexport const clone = function(obj) {\n return extend({}, obj);\n};\n\n/**\n * Returns true if obj has typeof \"object\" and is not null. Unlike goog.isObject(), does not return true\n * for functions.\n *\n * @param obj {*} A potential object.\n * @returns {boolean} True if it's an object.\n */\nexport const isNonNullObject = function(obj) {\n return typeof obj === 'object' && obj !== null;\n};\n\nexport const isEmpty = function(obj) {\n for (var key in obj) {\n return false;\n }\n return true;\n};\n\nexport const getCount = function(obj) {\n var rv = 0;\n for (var key in obj) {\n rv++;\n }\n return rv;\n};\n\nexport const map = function(obj, f, opt_obj?) {\n var res = {};\n for (var key in obj) {\n res[key] = f.call(opt_obj, obj[key], key, obj);\n }\n return res;\n};\n\nexport const findKey = function(obj, fn, opt_this?) {\n for (var key in obj) {\n if (fn.call(opt_this, obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n};\n\nexport const findValue = function(obj, fn, opt_this?) {\n var key = findKey(obj, fn, opt_this);\n return key && obj[key];\n};\n\nexport const getAnyKey = function(obj) {\n for (var key in obj) {\n return key;\n }\n};\n\nexport const getValues = function(obj) {\n var res = [];\n var i = 0;\n for (var key in obj) {\n res[i++] = obj[key];\n }\n return res;\n};\n\n/**\n * Tests whether every key/value pair in an object pass the test implemented\n * by the provided function\n *\n * @param {?Object.} obj Object to test.\n * @param {!function(K, V)} fn Function to call for each key and value.\n * @template K,V\n */\nexport const every = function(\n obj: Object,\n fn: (k: string, v?: V) => boolean\n): boolean {\n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n if (!fn(key, obj[key])) {\n return false;\n }\n }\n }\n return true;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/obj.ts","/**\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\nimport { nameCompare } from './util';\nimport { stringLength } from '../../../utils/utf8';\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 */\n\nexport class Path {\n private pieces_: string[];\n private pieceNum_: number;\n\n /**\n * Singleton to represent an empty path\n *\n * @const\n */\n static get Empty() {\n return new Path('');\n }\n\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 constructor(pathOrString: string | string[], pieceNum?: number) {\n if (pieceNum === void 0) {\n this.pieces_ = (pathOrString as string).split('/');\n\n // Remove empty pieces.\n let copyTo = 0;\n for (let 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\n this.pieceNum_ = 0;\n } else {\n this.pieces_ = pathOrString as string[];\n this.pieceNum_ = pieceNum;\n }\n }\n\n getFront(): string | null {\n if (this.pieceNum_ >= this.pieces_.length) return null;\n\n return this.pieces_[this.pieceNum_];\n }\n\n /**\n * @return {number} The number of segments in this path\n */\n getLength(): number {\n return this.pieces_.length - this.pieceNum_;\n }\n\n /**\n * @return {!Path}\n */\n popFront(): Path {\n let pieceNum = this.pieceNum_;\n if (pieceNum < this.pieces_.length) {\n pieceNum++;\n }\n return new Path(this.pieces_, pieceNum);\n }\n\n /**\n * @return {?string}\n */\n getBack(): string | null {\n if (this.pieceNum_ < this.pieces_.length)\n return this.pieces_[this.pieces_.length - 1];\n\n return null;\n }\n\n toString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '') pathString += '/' + this.pieces_[i];\n }\n\n return pathString || '/';\n }\n\n toUrlEncodedString(): string {\n let pathString = '';\n for (let i = this.pieceNum_; i < this.pieces_.length; i++) {\n if (this.pieces_[i] !== '')\n pathString += '/' + encodeURIComponent(String(this.pieces_[i]));\n }\n\n return pathString || '/';\n }\n\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array}\n */\n slice(begin: number = 0): string[] {\n return this.pieces_.slice(this.pieceNum_ + begin);\n }\n\n /**\n * @return {?Path}\n */\n parent(): Path | null {\n if (this.pieceNum_ >= this.pieces_.length) return null;\n\n const pieces = [];\n for (let i = this.pieceNum_; i < this.pieces_.length - 1; i++)\n pieces.push(this.pieces_[i]);\n\n return new Path(pieces, 0);\n }\n\n /**\n * @param {string|!Path} childPathObj\n * @return {!Path}\n */\n child(childPathObj: string | Path): Path {\n const pieces = [];\n for (let i = this.pieceNum_; i < this.pieces_.length; i++)\n pieces.push(this.pieces_[i]);\n\n if (childPathObj instanceof Path) {\n for (\n let i = childPathObj.pieceNum_;\n i < childPathObj.pieces_.length;\n i++\n ) {\n pieces.push(childPathObj.pieces_[i]);\n }\n } else {\n const childPieces = childPathObj.split('/');\n for (let i = 0; i < childPieces.length; i++) {\n if (childPieces[i].length > 0) pieces.push(childPieces[i]);\n }\n }\n\n return new Path(pieces, 0);\n }\n\n /**\n * @return {boolean} True if there are no segments in this path\n */\n isEmpty(): boolean {\n return this.pieceNum_ >= this.pieces_.length;\n }\n\n /**\n * @param {!Path} outerPath\n * @param {!Path} innerPath\n * @return {!Path} The path from outerPath to innerPath\n */\n static relativePath(outerPath: Path, innerPath: Path): Path {\n const outer = outerPath.getFront(),\n inner = innerPath.getFront();\n if (outer === null) {\n return innerPath;\n } else if (outer === inner) {\n return Path.relativePath(outerPath.popFront(), innerPath.popFront());\n } else {\n throw new Error(\n 'INTERNAL ERROR: innerPath (' +\n innerPath +\n ') is not within ' +\n 'outerPath (' +\n outerPath +\n ')'\n );\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 static comparePaths(left: Path, right: Path): number {\n const leftKeys = left.slice();\n const rightKeys = right.slice();\n for (let i = 0; i < leftKeys.length && i < rightKeys.length; i++) {\n const cmp = nameCompare(leftKeys[i], rightKeys[i]);\n if (cmp !== 0) return cmp;\n }\n if (leftKeys.length === rightKeys.length) return 0;\n return leftKeys.length < rightKeys.length ? -1 : 1;\n }\n\n /**\n *\n * @param {Path} other\n * @return {boolean} true if paths are the same.\n */\n equals(other: Path): boolean {\n if (this.getLength() !== other.getLength()) {\n return false;\n }\n\n for (\n let i = this.pieceNum_, j = other.pieceNum_;\n i <= this.pieces_.length;\n i++, j++\n ) {\n if (this.pieces_[i] !== other.pieces_[j]) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n *\n * @param {!Path} other\n * @return {boolean} True if this path is a parent (or the same as) other\n */\n contains(other: Path): boolean {\n let i = this.pieceNum_;\n let 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} // end Path\n\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 */\nexport class ValidationPath {\n /** @type {!Array} */\n private parts_: string[];\n /** @type {number} Initialize to number of '/' chars needed in path. */\n private byteLength_: number;\n\n /**\n * @param {!Path} path Initial Path.\n * @param {string} errorPrefix_ Prefix for any error messages.\n */\n constructor(path: Path, private errorPrefix_: string) {\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\n for (let i = 0; i < this.parts_.length; i++) {\n this.byteLength_ += stringLength(this.parts_[i]);\n }\n this.checkValid_();\n }\n\n /** @const {number} Maximum key depth. */\n static get MAX_PATH_DEPTH() {\n return 32;\n }\n\n /** @const {number} Maximum number of (UTF8) bytes in a Firebase path. */\n static get MAX_PATH_LENGTH_BYTES() {\n return 768;\n }\n\n /** @param {string} child */\n push(child: string) {\n // Count the needed '/'\n if (this.parts_.length > 0) {\n this.byteLength_ += 1;\n }\n this.parts_.push(child);\n this.byteLength_ += stringLength(child);\n this.checkValid_();\n }\n\n pop() {\n const last = this.parts_.pop();\n this.byteLength_ -= stringLength(last);\n // Un-count the previous '/'\n if (this.parts_.length > 0) {\n this.byteLength_ -= 1;\n }\n }\n\n private checkValid_() {\n if (this.byteLength_ > ValidationPath.MAX_PATH_LENGTH_BYTES) {\n throw new Error(\n this.errorPrefix_ +\n 'has a key path longer than ' +\n ValidationPath.MAX_PATH_LENGTH_BYTES +\n ' bytes (' +\n this.byteLength_ +\n ').'\n );\n }\n if (this.parts_.length > ValidationPath.MAX_PATH_DEPTH) {\n throw new Error(\n 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\n /**\n * String for use in error messages - uses '.' notation for path.\n *\n * @return {string}\n */\n toErrorString(): string {\n if (this.parts_.length == 0) {\n return '';\n }\n return \"in property '\" + this.parts_.join('.') + \"'\";\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/Path.ts","/**\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\nimport { Index } from './Index';\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { NamedNode, Node } from '../Node';\nimport { LeafNode } from '../LeafNode';\n\nlet nodeFromJSON: (a: any) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: any) => Node) {\n nodeFromJSON = val;\n}\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nexport class PriorityIndex extends Index {\n /**\n * @inheritDoc\n */\n compare(a: NamedNode, b: NamedNode): number {\n const aPriority = a.node.getPriority();\n const bPriority = b.node.getPriority();\n const indexCmp = aPriority.compareTo(bPriority);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n\n /**\n * @inheritDoc\n */\n isDefinedOn(node: Node): boolean {\n return !node.getPriority().isEmpty();\n }\n\n /**\n * @inheritDoc\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.getPriority().equals(newNode.getPriority());\n }\n\n /**\n * @inheritDoc\n */\n minPost(): NamedNode {\n return (NamedNode as any).MIN;\n }\n\n /**\n * @inheritDoc\n */\n maxPost(): NamedNode {\n return new NamedNode(MAX_NAME, new LeafNode('[PRIORITY-POST]', MAX_NODE));\n }\n\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n makePost(indexValue: any, name: string): NamedNode {\n const priorityNode = nodeFromJSON(indexValue);\n return new NamedNode(name, new LeafNode('[PRIORITY-POST]', priorityNode));\n }\n\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n toString(): string {\n return '.priority';\n }\n}\n\nexport const PRIORITY_INDEX = new PriorityIndex();\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/indexes/PriorityIndex.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { sha1, MAX_NAME, MIN_NAME } from '../util/util';\nimport { SortedMap, SortedMapIterator } from '../util/SortedMap';\nimport { Node, NamedNode } from './Node';\nimport { validatePriorityNode, priorityHashText, setMaxNode } from './snap';\nimport {\n PRIORITY_INDEX,\n setMaxNode as setPriorityMaxNode\n} from './indexes/PriorityIndex';\nimport { KEY_INDEX, KeyIndex } from './indexes/KeyIndex';\nimport { IndexMap } from './IndexMap';\nimport { LeafNode } from './LeafNode';\nimport { NAME_COMPARATOR } from './comparators';\nimport { Index } from './indexes/Index';\nimport { Path } from '../util/Path';\n\nexport interface ChildrenNodeConstructor {\n new (\n children_: SortedMap,\n priorityNode_: Node | null,\n indexMap_: IndexMap\n ): ChildrenNode;\n EMPTY_NODE: ChildrenNode;\n}\n\n// TODO: For memory savings, don't store priorityNode_ if it's empty.\n\nlet EMPTY_NODE: ChildrenNode;\n\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 */\nexport class ChildrenNode implements Node {\n private lazyHash_: string | null = null;\n\n static get EMPTY_NODE(): ChildrenNode {\n return (\n EMPTY_NODE ||\n (EMPTY_NODE = new ChildrenNode(\n new SortedMap(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\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 constructor(\n private readonly children_: SortedMap,\n private readonly priorityNode_: Node | null,\n private indexMap_: IndexMap\n ) {\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 validatePriorityNode(this.priorityNode_);\n }\n\n if (this.children_.isEmpty()) {\n assert(\n !this.priorityNode_ || this.priorityNode_.isEmpty(),\n 'An empty node cannot have a priority'\n );\n }\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_ || EMPTY_NODE;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n if (this.children_.isEmpty()) {\n // Don't allow priorities on empty nodes\n return this;\n } else {\n return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);\n }\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.getPriority();\n } else {\n const child = this.children_.get(childName);\n return child === null ? EMPTY_NODE : child;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n const front = path.getFront();\n if (front === null) return this;\n\n return this.getImmediateChild(front).getChild(path.popFront());\n }\n\n /** @inheritDoc */\n hasChild(childName: string): boolean {\n return this.children_.get(childName) !== null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n assert(newChildNode, 'We should always be passing snapshot nodes');\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else {\n const namedNode = new NamedNode(childName, newChildNode);\n let newChildren, newIndexMap, newPriority;\n if (newChildNode.isEmpty()) {\n newChildren = this.children_.remove(childName);\n newIndexMap = this.indexMap_.removeFromIndexes(\n namedNode,\n this.children_\n );\n } else {\n newChildren = this.children_.insert(childName, newChildNode);\n newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);\n }\n\n newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;\n return new ChildrenNode(newChildren, newPriority, newIndexMap);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = path.getFront();\n if (front === null) {\n return newChildNode;\n } else {\n assert(\n path.getFront() !== '.priority' || path.getLength() === 1,\n '.priority must be the last token in a path'\n );\n const newImmediateChild = this.getImmediateChild(front).updateChild(\n path.popFront(),\n newChildNode\n );\n return this.updateImmediateChild(front, newImmediateChild);\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return this.children_.isEmpty();\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return this.children_.count();\n }\n\n /**\n * @private\n * @type {RegExp}\n */\n private static INTEGER_REGEXP_ = /^(0|[1-9]\\d*)$/;\n\n /** @inheritDoc */\n val(exportFormat?: boolean): object {\n if (this.isEmpty()) return null;\n\n const obj: { [k: string]: Object } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, function(key: string, childNode: Node) {\n obj[key] = childNode.val(exportFormat);\n\n numKeys++;\n if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {\n maxKey = Math.max(maxKey, Number(key));\n } else {\n allIntegerKeys = false;\n }\n });\n\n if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {\n // convert to array.\n const array: Object[] = [];\n for (let key in obj) array[(key as any) as number] = obj[key];\n\n return array;\n } else {\n if (exportFormat && !this.getPriority().isEmpty()) {\n obj['.priority'] = this.getPriority().val();\n }\n return obj;\n }\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.getPriority().isEmpty())\n toHash +=\n 'priority:' +\n priorityHashText(this.getPriority().val() as string | number) +\n ':';\n\n this.forEachChild(PRIORITY_INDEX, function(key, childNode) {\n const childHash = childNode.hash();\n if (childHash !== '') toHash += ':' + key + ':' + childHash;\n });\n\n this.lazyHash_ = toHash === '' ? '' : sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(\n childName: string,\n childNode: Node,\n index: Index\n ): string {\n const idx = this.resolveIndex_(index);\n if (idx) {\n const predecessor = idx.getPredecessorKey(\n new NamedNode(childName, childNode)\n );\n return predecessor ? predecessor.name : null;\n } else {\n return this.children_.getPredecessorKey(childName);\n }\n }\n\n /**\n * @param {!Index} indexDefinition\n * @return {?string}\n */\n getFirstChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const minKey = idx.minKey();\n return minKey && minKey.name;\n } else {\n return this.children_.minKey();\n }\n }\n\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n getFirstChild(indexDefinition: Index): NamedNode | null {\n const minKey = this.getFirstChildName(indexDefinition);\n if (minKey) {\n return new NamedNode(minKey, this.children_.get(minKey));\n } else {\n return null;\n }\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 getLastChildName(indexDefinition: Index): string | null {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n const maxKey = idx.maxKey();\n return maxKey && maxKey.name;\n } else {\n return this.children_.maxKey();\n }\n }\n\n /**\n * @param {!Index} indexDefinition\n * @return {?NamedNode}\n */\n getLastChild(indexDefinition: Index): NamedNode | null {\n const maxKey = this.getLastChildName(indexDefinition);\n if (maxKey) {\n return new NamedNode(maxKey, this.children_.get(maxKey));\n } else {\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n forEachChild(index: Index, action: (key: string, node: Node) => void): any {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(function(wrappedNode) {\n return action(wrappedNode.name, wrappedNode.node);\n });\n } else {\n return this.children_.inorderTraversal(action);\n }\n }\n\n /**\n * @param {!Index} indexDefinition\n * @return {SortedMapIterator}\n */\n getIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);\n }\n\n /**\n *\n * @param {!NamedNode} startPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n getIteratorFrom(\n startPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getIteratorFrom(startPost, key => key);\n } else {\n const iterator = this.children_.getIteratorFrom(\n startPost.name,\n NamedNode.Wrap\n );\n let 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 /**\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n getReverseIterator(\n indexDefinition: Index\n ): SortedMapIterator {\n return this.getReverseIteratorFrom(\n indexDefinition.maxPost(),\n indexDefinition\n );\n }\n\n /**\n * @param {!NamedNode} endPost\n * @param {!Index} indexDefinition\n * @return {!SortedMapIterator}\n */\n getReverseIteratorFrom(\n endPost: NamedNode,\n indexDefinition: Index\n ): SortedMapIterator {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, function(key) {\n return key;\n });\n } else {\n const iterator = this.children_.getReverseIteratorFrom(\n endPost.name,\n NamedNode.Wrap\n );\n let 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 /**\n * @inheritDoc\n */\n compareTo(other: ChildrenNode): number {\n if (this.isEmpty()) {\n if (other.isEmpty()) {\n return 0;\n } else {\n return -1;\n }\n } else if (other.isLeafNode() || other.isEmpty()) {\n return 1;\n } else if (other === MAX_NODE) {\n return -1;\n } else {\n // Must be another node with children.\n return 0;\n }\n }\n\n /**\n * @inheritDoc\n */\n withIndex(indexDefinition: Index): Node {\n if (\n indexDefinition === KEY_INDEX ||\n this.indexMap_.hasIndex(indexDefinition)\n ) {\n return this;\n } else {\n const newIndexMap = this.indexMap_.addIndex(\n indexDefinition,\n this.children_\n );\n return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);\n }\n }\n\n /**\n * @inheritDoc\n */\n isIndexed(index: Index): boolean {\n return index === KEY_INDEX || this.indexMap_.hasIndex(index);\n }\n\n /**\n * @inheritDoc\n */\n equals(other: Node): boolean {\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n return false;\n } else {\n const otherChildrenNode = other as ChildrenNode;\n if (!this.getPriority().equals(otherChildrenNode.getPriority())) {\n return false;\n } else if (\n this.children_.count() === otherChildrenNode.children_.count()\n ) {\n const thisIter = this.getIterator(PRIORITY_INDEX);\n const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);\n let thisCurrent = thisIter.getNext();\n let otherCurrent = otherIter.getNext();\n while (thisCurrent && otherCurrent) {\n if (\n thisCurrent.name !== otherCurrent.name ||\n !thisCurrent.node.equals(otherCurrent.node)\n ) {\n return false;\n }\n thisCurrent = thisIter.getNext();\n otherCurrent = otherIter.getNext();\n }\n return thisCurrent === null && otherCurrent === null;\n } else {\n return false;\n }\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 private resolveIndex_(\n indexDefinition: Index\n ): SortedMap | null {\n if (indexDefinition === KEY_INDEX) {\n return null;\n } else {\n return this.indexMap_.get(indexDefinition.toString());\n }\n }\n}\n\n/**\n * @constructor\n * @extends {ChildrenNode}\n * @private\n */\nexport class MaxNode extends ChildrenNode {\n constructor() {\n super(\n new SortedMap(NAME_COMPARATOR),\n ChildrenNode.EMPTY_NODE,\n IndexMap.Default\n );\n }\n\n compareTo(other: Node): number {\n if (other === this) {\n return 0;\n } else {\n return 1;\n }\n }\n\n equals(other: Node): boolean {\n // Not that we every compare it, but MAX_NODE is only ever equal to itself\n return other === this;\n }\n\n getPriority(): MaxNode {\n return this;\n }\n\n getImmediateChild(childName: string): ChildrenNode {\n return ChildrenNode.EMPTY_NODE;\n }\n\n isEmpty(): boolean {\n return false;\n }\n}\n\n/**\n * Marker that will sort higher than any other snapshot.\n * @type {!MAX_NODE}\n * @const\n */\nexport const MAX_NODE = new MaxNode();\n\n/**\n * Document NamedNode extensions\n */\ndeclare module './Node' {\n interface NamedNode {\n MIN: NamedNode;\n MAX: NamedNode;\n }\n}\n\nObject.defineProperties(NamedNode, {\n MIN: {\n value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)\n },\n MAX: {\n value: new NamedNode(MAX_NAME, MAX_NODE)\n }\n});\n\n/**\n * Reference Extensions\n */\nKeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;\nLeafNode.__childrenNodeConstructor = ChildrenNode;\nsetMaxNode(MAX_NODE);\nsetPriorityMaxNode(MAX_NODE);\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/ChildrenNode.ts","/**\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\nimport { Path } from '../util/Path';\nimport { Index } from './indexes/Index';\n\n/**\n * Node is an interface defining the common functionality for nodes in\n * a DataSnapshot.\n *\n * @interface\n */\nexport interface Node {\n /**\n * Whether this node is a leaf node.\n * @return {boolean} Whether this is a leaf node.\n */\n isLeafNode(): boolean;\n\n /**\n * Gets the priority of the node.\n * @return {!Node} The priority of the node.\n */\n getPriority(): Node;\n\n /**\n * Returns a duplicate node with the new priority.\n * @param {!Node} newPriorityNode New priority to set for the node.\n * @return {!Node} Node with new priority.\n */\n updatePriority(newPriorityNode: Node): Node;\n\n /**\n * Returns the specified immediate child, or null if it doesn't exist.\n * @param {string} childName The name of the child to retrieve.\n * @return {!Node} The retrieved child, or an empty node.\n */\n getImmediateChild(childName: string): Node;\n\n /**\n * Returns a child by path, or null if it doesn't exist.\n * @param {!Path} path The path of the child to retrieve.\n * @return {!Node} The retrieved child or an empty node.\n */\n getChild(path: Path): Node;\n\n /**\n * Returns the name of the child immediately prior to the specified childNode, or null.\n * @param {!string} childName The name of the child to find the predecessor of.\n * @param {!Node} childNode The node to find the predecessor of.\n * @param {!Index} index The index to use to determine the predecessor\n * @return {?string} The name of the predecessor child, or null if childNode is the first child.\n */\n getPredecessorChildName(\n childName: String,\n childNode: Node,\n index: Index\n ): string | null;\n\n /**\n * Returns a duplicate node, with the specified immediate child updated.\n * Any value in the node will be removed.\n * @param {string} childName The name of the child to update.\n * @param {!Node} newChildNode The new child node\n * @return {!Node} The updated node.\n */\n updateImmediateChild(childName: string, newChildNode: Node): Node;\n\n /**\n * Returns a duplicate node, with the specified child updated. Any value will\n * be removed.\n * @param {!Path} path The path of the child to update.\n * @param {!Node} newChildNode The new child node, which may be an empty node\n * @return {!Node} The updated node.\n */\n updateChild(path: Path, newChildNode: Node): Node;\n\n /**\n * True if the immediate child specified exists\n * @param {!string} childName\n * @return {boolean}\n */\n hasChild(childName: string): boolean;\n\n /**\n * @return {boolean} True if this node has no value or children.\n */\n isEmpty(): boolean;\n\n /**\n * @return {number} The number of children of this node.\n */\n numChildren(): number;\n\n /**\n * Calls action for each child.\n * @param {!Index} index\n * @param {function(string, !Node)} action Action to be called for\n * each child. It's passed the child name and the child node.\n * @return {*} The first truthy value return by action, or the last falsey one\n */\n forEachChild(index: Index, action: (a: string, b: Node) => void): any;\n\n /**\n * @param {boolean=} exportFormat True for export format (also wire protocol format).\n * @return {*} Value of this node as JSON.\n */\n val(exportFormat?: boolean): Object;\n\n /**\n * @return {string} hash representing the node contents.\n */\n hash(): string;\n\n /**\n * @param {!Node} other Another node\n * @return {!number} -1 for less than, 0 for equal, 1 for greater than other\n */\n compareTo(other: Node): number;\n\n /**\n * @param {!Node} other\n * @return {boolean} Whether or not this snapshot equals other\n */\n equals(other: Node): boolean;\n\n /**\n * @param {!Index} indexDefinition\n * @return {!Node} This node, with the specified index now available\n */\n withIndex(indexDefinition: Index): Node;\n\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n isIndexed(indexDefinition: Index): boolean;\n}\n\n/**\n *\n * @param {!string} name\n * @param {!Node} node\n * @constructor\n * @struct\n */\nexport class NamedNode {\n constructor(public name: string, public node: Node) {}\n\n /**\n *\n * @param {!string} name\n * @param {!Node} node\n * @return {NamedNode}\n */\n static Wrap(name: string, node: Node) {\n return new NamedNode(name, node);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/Node.ts","/**\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\n/**\n * Evaluates a JSON string into a javascript object.\n *\n * @param {string} str A string containing JSON.\n * @return {*} The javascript object representing the specified JSON.\n */\nexport const jsonEval = function(str) {\n return JSON.parse(str);\n};\n\n/**\n * Returns JSON representing a javascript object.\n * @param {*} data Javascript object to be stringified.\n * @return {string} The JSON contents of the object.\n */\nexport const stringify = function(data) {\n return JSON.stringify(data);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/json.ts","/**\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\n/**\n * Check to make sure the appropriate number of arguments are provided for a public function.\n * Throws an error if it fails.\n *\n * @param {!string} fnName The function name\n * @param {!number} minCount The minimum number of arguments to allow for the function call\n * @param {!number} maxCount The maximum number of argument to allow for the function call\n * @param {!number} argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function(fnName, minCount, maxCount, argCount) {\n var argError;\n if (argCount < minCount) {\n argError = 'at least ' + minCount;\n } else if (argCount > maxCount) {\n argError = maxCount === 0 ? 'none' : 'no more than ' + maxCount;\n }\n if (argError) {\n var error =\n fnName +\n ' failed: Was called with ' +\n argCount +\n (argCount === 1 ? ' argument.' : ' arguments.') +\n ' Expects ' +\n argError +\n '.';\n throw new Error(error);\n }\n};\n\n/**\n * Generates a string to prefix an error message about failed argument validation\n *\n * @param {!string} fnName The function name\n * @param {!number} argumentNumber The index of the argument\n * @param {boolean} optional Whether or not the argument is optional\n * @return {!string} The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(fnName, argumentNumber, optional) {\n var argName = '';\n switch (argumentNumber) {\n case 1:\n argName = optional ? 'first' : 'First';\n break;\n case 2:\n argName = optional ? 'second' : 'Second';\n break;\n case 3:\n argName = optional ? 'third' : 'Third';\n break;\n case 4:\n argName = optional ? 'fourth' : 'Fourth';\n break;\n default:\n throw new Error(\n 'errorPrefix called with argumentNumber > 4. Need to update it?'\n );\n }\n\n var error = fnName + ' failed: ';\n\n error += argName + ' argument ';\n return error;\n}\n\n/**\n * @param {!string} fnName\n * @param {!number} argumentNumber\n * @param {!string} namespace\n * @param {boolean} optional\n */\nexport const validateNamespace = function(\n fnName,\n argumentNumber,\n namespace,\n optional\n) {\n if (optional && !namespace) return;\n if (typeof namespace !== 'string') {\n //TODO: I should do more validation here. We only allow certain chars in namespaces.\n throw new Error(\n errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid firebase namespace.'\n );\n }\n};\n\nexport const validateCallback = function(\n fnName,\n argumentNumber,\n callback,\n optional\n) {\n if (optional && !callback) return;\n if (typeof callback !== 'function')\n throw new Error(\n errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid function.'\n );\n};\n\nexport const validateContextObject = function(\n fnName,\n argumentNumber,\n context,\n optional\n) {\n if (optional && !context) return;\n if (typeof context !== 'object' || context === null)\n throw new Error(\n errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid context object.'\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/validation.ts","/**\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\nimport { Path, ValidationPath } from './Path';\nimport { forEach, contains, safeGet } from '../../../utils/obj';\nimport { isInvalidJSONNumber } from './util';\nimport { errorPrefix as errorPrefixFxn } from '../../../utils/validation';\nimport { stringLength } from '../../../utils/utf8';\nimport { RepoInfo } from '../RepoInfo';\n\n/**\n * True for invalid Firebase keys\n * @type {RegExp}\n * @private\n */\nexport const INVALID_KEY_REGEX_ = /[\\[\\].#$\\/\\u0000-\\u001F\\u007F]/;\n\n/**\n * True for invalid Firebase paths.\n * Allows '/' in paths.\n * @type {RegExp}\n * @private\n */\nexport const INVALID_PATH_REGEX_ = /[\\[\\].#$\\u0000-\\u001F\\u007F]/;\n\n/**\n * Maximum number of characters to allow in leaf value\n * @type {number}\n * @private\n */\nexport const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;\n\n/**\n * @param {*} key\n * @return {boolean}\n */\nexport const isValidKey = function(key: any): boolean {\n return (\n typeof key === 'string' && key.length !== 0 && !INVALID_KEY_REGEX_.test(key)\n );\n};\n\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexport const isValidPathString = function(pathString: string): boolean {\n return (\n typeof pathString === 'string' &&\n pathString.length !== 0 &&\n !INVALID_PATH_REGEX_.test(pathString)\n );\n};\n\n/**\n * @param {string} pathString\n * @return {boolean}\n */\nexport const isValidRootPathString = function(pathString: string): boolean {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n return isValidPathString(pathString);\n};\n\n/**\n * @param {*} priority\n * @return {boolean}\n */\nexport const isValidPriority = function(priority: any): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority && typeof priority === 'object' && contains(priority, '.sv'))\n );\n};\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 */\nexport const validateFirebaseDataArg = function(\n fnName: string,\n argumentNumber: number,\n data: any,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) return;\n\n validateFirebaseData(\n errorPrefixFxn(fnName, argumentNumber, optional),\n data,\n path\n );\n};\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 */\nexport const validateFirebaseData = function(\n errorPrefix: string,\n data: any,\n path_: Path | ValidationPath\n) {\n const path =\n path_ instanceof Path ? new ValidationPath(path_, errorPrefix) : path_;\n\n if (data === undefined) {\n throw new Error(errorPrefix + 'contains undefined ' + path.toErrorString());\n }\n if (typeof data === 'function') {\n throw new Error(\n errorPrefix +\n 'contains a function ' +\n path.toErrorString() +\n ' with contents = ' +\n data.toString()\n );\n }\n if (isInvalidJSONNumber(data)) {\n throw new Error(\n errorPrefix + 'contains ' + data.toString() + ' ' + path.toErrorString()\n );\n }\n\n // Check max leaf size, but try to avoid the utf8 conversion if we can.\n if (\n typeof data === 'string' &&\n data.length > MAX_LEAF_SIZE_ / 3 &&\n stringLength(data) > MAX_LEAF_SIZE_\n ) {\n throw new Error(\n errorPrefix +\n 'contains a string greater than ' +\n MAX_LEAF_SIZE_ +\n ' utf8 bytes ' +\n path.toErrorString() +\n \" ('\" +\n data.substring(0, 50) +\n \"...')\"\n );\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 let hasDotValue = false,\n hasActualChild = false;\n forEach(data, function(key: string, value: any) {\n if (key === '.value') {\n hasDotValue = true;\n } else if (key !== '.priority' && key !== '.sv') {\n hasActualChild = true;\n if (!isValidKey(key)) {\n throw new Error(\n 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 }\n\n path.push(key);\n validateFirebaseData(errorPrefix, value, path);\n path.pop();\n });\n\n if (hasDotValue && hasActualChild) {\n throw new Error(\n errorPrefix +\n ' contains \".value\" child ' +\n path.toErrorString() +\n ' in addition to actual children.'\n );\n }\n }\n};\n\n/**\n * Pre-validate paths passed in the firebase function.\n *\n * @param {string} errorPrefix\n * @param {Array} mergePaths\n */\nexport const validateFirebaseMergePaths = function(\n errorPrefix: string,\n mergePaths: Path[]\n) {\n let i, curPath;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n const keys = curPath.slice();\n for (let j = 0; j < keys.length; j++) {\n if (keys[j] === '.priority' && j === keys.length - 1) {\n // .priority is OK\n } else if (!isValidKey(keys[j])) {\n throw new Error(\n 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 }\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.comparePaths);\n let prevPath: Path | null = null;\n for (i = 0; i < mergePaths.length; i++) {\n curPath = mergePaths[i];\n if (prevPath !== null && prevPath.contains(curPath)) {\n throw new Error(\n errorPrefix +\n 'contains a path ' +\n prevPath.toString() +\n ' that is ancestor of another path ' +\n curPath.toString()\n );\n }\n prevPath = curPath;\n }\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 */\nexport const validateFirebaseMergeDataArg = function(\n fnName: string,\n argumentNumber: number,\n data: any,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) return;\n\n const errorPrefix = errorPrefixFxn(fnName, argumentNumber, optional);\n\n if (!(data && typeof data === 'object') || Array.isArray(data)) {\n throw new Error(\n errorPrefix + ' must be an object containing the children to replace.'\n );\n }\n\n const mergePaths: Path[] = [];\n forEach(data, function(key: string, value: any) {\n const curPath = new Path(key);\n validateFirebaseData(errorPrefix, value, path.child(curPath));\n if (curPath.getBack() === '.priority') {\n if (!isValidPriority(value)) {\n throw new Error(\n 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 }\n mergePaths.push(curPath);\n });\n validateFirebaseMergePaths(errorPrefix, mergePaths);\n};\n\nexport const validatePriority = function(\n fnName: string,\n argumentNumber: number,\n priority: any,\n optional: boolean\n) {\n if (optional && priority === undefined) return;\n if (isInvalidJSONNumber(priority))\n throw new Error(\n errorPrefixFxn(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 );\n // Special case to allow importing data with a .sv.\n if (!isValidPriority(priority))\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must be a valid Firebase priority ' +\n '(a string, finite number, server value, or null).'\n );\n};\n\nexport const validateEventType = function(\n fnName: string,\n argumentNumber: number,\n eventType: string,\n optional: boolean\n) {\n if (optional && eventType === undefined) return;\n\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(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must be a valid event type = \"value\", \"child_added\", \"child_removed\", ' +\n '\"child_changed\", or \"child_moved\".'\n );\n }\n};\n\nexport const validateKey = function(\n fnName: string,\n argumentNumber: number,\n key: string,\n optional: boolean\n) {\n if (optional && key === undefined) return;\n if (!isValidKey(key))\n throw new Error(\n errorPrefixFxn(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 );\n};\n\nexport const validatePathString = function(\n fnName: string,\n argumentNumber: number,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) return;\n\n if (!isValidPathString(pathString))\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'was an invalid path = \"' +\n pathString +\n '\". Paths must be non-empty strings and ' +\n 'can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\"'\n );\n};\n\nexport const validateRootPathString = function(\n fnName: string,\n argumentNumber: number,\n pathString: string,\n optional: boolean\n) {\n if (pathString) {\n // Allow '/.info/' at the beginning.\n pathString = pathString.replace(/^\\/*\\.info(\\/|$)/, '/');\n }\n\n validatePathString(fnName, argumentNumber, pathString, optional);\n};\n\nexport const validateWritablePath = function(fnName: string, path: Path) {\n if (path.getFront() === '.info') {\n throw new Error(fnName + \" failed = Can't modify data under /.info/\");\n }\n};\n\nexport const validateUrl = function(\n fnName: string,\n argumentNumber: number,\n parsedUrl: { repoInfo: RepoInfo; path: Path }\n) {\n // TODO = Validate server better.\n const pathString = parsedUrl.path.toString();\n if (\n !(typeof parsedUrl.repoInfo.host === 'string') ||\n parsedUrl.repoInfo.host.length === 0 ||\n !isValidKey(parsedUrl.repoInfo.namespace) ||\n (pathString.length !== 0 && !isValidRootPathString(pathString))\n ) {\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, false) +\n 'must be a valid firebase URL and ' +\n 'the path can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".'\n );\n }\n};\n\nexport const validateCredential = function(\n fnName: string,\n argumentNumber: number,\n cred: any,\n optional: boolean\n) {\n if (optional && cred === undefined) return;\n if (!(typeof cred === 'string'))\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must be a valid credential (a string).'\n );\n};\n\nexport const validateBoolean = function(\n fnName: string,\n argumentNumber: number,\n bool: any,\n optional: boolean\n) {\n if (optional && bool === undefined) return;\n if (typeof bool !== 'boolean')\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) + 'must be a boolean.'\n );\n};\n\nexport const validateString = function(\n fnName: string,\n argumentNumber: number,\n string: any,\n optional: boolean\n) {\n if (optional && string === undefined) return;\n if (!(typeof string === 'string')) {\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must be a valid string.'\n );\n }\n};\n\nexport const validateObject = function(\n fnName: string,\n argumentNumber: number,\n obj: any,\n optional: boolean\n) {\n if (optional && obj === undefined) return;\n if (!(obj && typeof obj === 'object') || obj === null) {\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must be a valid object.'\n );\n }\n};\n\nexport const validateObjectContainsKey = function(\n fnName: string,\n argumentNumber: number,\n obj: any,\n key: string,\n optional: boolean,\n opt_type?: string\n) {\n const objectContainsKey =\n obj && typeof obj === 'object' && contains(obj, key);\n\n if (!objectContainsKey) {\n if (optional) {\n return;\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\"'\n );\n }\n }\n\n if (opt_type) {\n const val = safeGet(obj, key);\n if (\n (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 ) {\n if (optional) {\n throw new Error(\n errorPrefixFxn(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(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n opt_type +\n '\"'\n );\n }\n }\n }\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/validation.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { Path } from '../util/Path';\n\n/**\n *\n * @enum\n */\nexport enum OperationType {\n OVERWRITE,\n MERGE,\n ACK_USER_WRITE,\n LISTEN_COMPLETE\n}\n\n/**\n * @interface\n */\nexport interface Operation {\n /**\n * @type {!OperationSource}\n */\n source: OperationSource;\n\n /**\n * @type {!OperationType}\n */\n type: OperationType;\n\n /**\n * @type {!Path}\n */\n path: Path;\n\n /**\n * @param {string} childName\n * @return {?Operation}\n */\n operationForChild(childName: string): Operation | null;\n}\n\n/**\n * @param {boolean} fromUser\n * @param {boolean} fromServer\n * @param {?string} queryId\n * @param {boolean} tagged\n * @constructor\n */\nexport class OperationSource {\n constructor(\n public fromUser: boolean,\n public fromServer: boolean,\n public queryId: string | null,\n public tagged: boolean\n ) {\n assert(!tagged || fromServer, 'Tagged queries must be from server.');\n }\n /**\n * @const\n * @type {!OperationSource}\n */\n static User = new OperationSource(\n /*fromUser=*/ true,\n false,\n null,\n /*tagged=*/ false\n );\n\n /**\n * @const\n * @type {!OperationSource}\n */\n static Server = new OperationSource(\n false,\n /*fromServer=*/ true,\n null,\n /*tagged=*/ false\n );\n\n /**\n * @param {string} queryId\n * @return {!OperationSource}\n */\n static forServerTaggedQuery = function(queryId: string): OperationSource {\n return new OperationSource(\n false,\n /*fromServer=*/ true,\n queryId,\n /*tagged=*/ true\n );\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/operation/Operation.ts","/**\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\nimport { CONSTANTS } from './constants';\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return {string} user agent string\n */\nexport const getUA = function() {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n};\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap in the Ripple emulator) nor\n * Cordova `onDeviceReady`, which would normally wait for a callback.\n *\n * @return {boolean} isMobileCordova\n */\nexport const isMobileCordova = function() {\n return (\n typeof window !== 'undefined' &&\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n};\n\n/**\n * Detect React Native.\n *\n * @return {boolean} True if ReactNative environment is detected.\n */\nexport const isReactNative = function() {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n};\n\n/**\n * Detect Node.js.\n *\n * @return {boolean} True if Node.js environment is detected.\n */\nexport const isNodeSdk = function() {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/environment.ts","/**\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\nimport { Node } from '../snap/Node';\n\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 */\nexport class Change {\n constructor(\n public type: string,\n public snapshotNode: Node,\n public childName?: string,\n public oldSnap?: Node,\n public prevName?: string\n ) {}\n\n /**\n * @param {!Node} snapshot\n * @return {!Change}\n */\n static valueChange(snapshot: Node): Change {\n return new Change(Change.VALUE, snapshot);\n }\n\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n static childAddedChange(childKey: string, snapshot: Node): Change {\n return new Change(Change.CHILD_ADDED, snapshot, childKey);\n }\n\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n static childRemovedChange(childKey: string, snapshot: Node): Change {\n return new Change(Change.CHILD_REMOVED, snapshot, childKey);\n }\n\n /**\n * @param {string} childKey\n * @param {!Node} newSnapshot\n * @param {!Node} oldSnapshot\n * @return {!Change}\n */\n static childChangedChange(\n childKey: string,\n newSnapshot: Node,\n oldSnapshot: Node\n ): Change {\n return new Change(Change.CHILD_CHANGED, newSnapshot, childKey, oldSnapshot);\n }\n\n /**\n * @param {string} childKey\n * @param {!Node} snapshot\n * @return {!Change}\n */\n static childMovedChange(childKey: string, snapshot: Node): Change {\n return new Change(Change.CHILD_MOVED, snapshot, childKey);\n }\n\n //event types\n /** Event type for a child added */\n static CHILD_ADDED = 'child_added';\n\n /** Event type for a child removed */\n static CHILD_REMOVED = 'child_removed';\n\n /** Event type for a child changed */\n static CHILD_CHANGED = 'child_changed';\n\n /** Event type for a child moved */\n static CHILD_MOVED = 'child_moved';\n\n /** Event type for a value change */\n static VALUE = 'value';\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/Change.ts","/**\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\nimport { Index } from './Index';\nimport { Node, NamedNode } from '../Node';\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { assert, assertionError } from '../../../../utils/assert';\nimport { ChildrenNode } from '../ChildrenNode';\n\nlet __EMPTY_NODE: ChildrenNode;\n\nexport class KeyIndex extends Index {\n static get __EMPTY_NODE() {\n return __EMPTY_NODE;\n }\n\n static set __EMPTY_NODE(val) {\n __EMPTY_NODE = val;\n }\n\n /**\n * @inheritDoc\n */\n compare(a: NamedNode, b: NamedNode): number {\n return nameCompare(a.name, b.name);\n }\n\n /**\n * @inheritDoc\n */\n isDefinedOn(node: Node): boolean {\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 assertionError('KeyIndex.isDefinedOn not expected to be called.');\n }\n\n /**\n * @inheritDoc\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return false; // The key for a node never changes.\n }\n\n /**\n * @inheritDoc\n */\n minPost() {\n return (NamedNode as any).MIN;\n }\n\n /**\n * @inheritDoc\n */\n maxPost(): NamedNode {\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 NamedNode(MAX_NAME, __EMPTY_NODE);\n }\n\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n makePost(indexValue: string, name: string): NamedNode {\n assert(\n typeof indexValue === 'string',\n 'KeyIndex indexValue must always be a string.'\n );\n // We just use empty node, but it'll never be compared, since our comparator only looks at name.\n return new NamedNode(indexValue, __EMPTY_NODE);\n }\n\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n toString(): string {\n return '.key';\n }\n}\n\nexport const KEY_INDEX = new KeyIndex();\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/indexes/KeyIndex.ts","/**\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\nimport { ChildrenNode } from './ChildrenNode';\nimport { LeafNode } from './LeafNode';\nimport { NamedNode, Node } from './Node';\nimport { forEach, contains } from '../../../utils/obj';\nimport { assert } from '../../../utils/assert';\nimport { buildChildSet } from './childSet';\nimport { NAME_COMPARATOR, NAME_ONLY_COMPARATOR } from './comparators';\nimport { IndexMap } from './IndexMap';\nimport { PRIORITY_INDEX, setNodeFromJSON } from './indexes/PriorityIndex';\nimport { SortedMap } from '../util/SortedMap';\n\nconst USE_HINZE = true;\n\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 */\nexport function nodeFromJSON(\n json: any | null,\n priority: string | number | null = null\n): Node {\n if (json === null) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n if (typeof json === 'object' && '.priority' in json) {\n priority = json['.priority'];\n }\n\n assert(\n priority === null ||\n typeof priority === 'string' ||\n typeof priority === 'number' ||\n (typeof priority === 'object' && '.sv' in (priority as object)),\n 'Invalid priority type found: ' + typeof priority\n );\n\n if (typeof json === 'object' && '.value' in json && json['.value'] !== null) {\n json = json['.value'];\n }\n\n // Valid leaf nodes include non-objects or server-value wrapper objects\n if (typeof json !== 'object' || '.sv' in json) {\n const jsonLeaf = json as string | number | boolean | object;\n return new LeafNode(jsonLeaf, nodeFromJSON(priority));\n }\n\n if (!(json instanceof Array) && USE_HINZE) {\n const children: NamedNode[] = [];\n let childrenHavePriority = false;\n const hinzeJsonObj: { [k: string]: any } = json as object;\n forEach(hinzeJsonObj, (key: string, child: any) => {\n if (typeof key !== 'string' || key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(hinzeJsonObj[key]);\n if (!childNode.isEmpty()) {\n childrenHavePriority =\n childrenHavePriority || !childNode.getPriority().isEmpty();\n children.push(new NamedNode(key, childNode));\n }\n }\n });\n\n if (children.length == 0) {\n return ChildrenNode.EMPTY_NODE;\n }\n\n const childSet = buildChildSet(\n children,\n NAME_ONLY_COMPARATOR,\n namedNode => namedNode.name,\n NAME_COMPARATOR\n ) as SortedMap;\n if (childrenHavePriority) {\n const sortedChildSet = buildChildSet(\n children,\n PRIORITY_INDEX.getCompare()\n );\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n new IndexMap(\n { '.priority': sortedChildSet },\n { '.priority': PRIORITY_INDEX }\n )\n );\n } else {\n return new ChildrenNode(\n childSet,\n nodeFromJSON(priority),\n IndexMap.Default\n );\n }\n } else {\n let node: Node = ChildrenNode.EMPTY_NODE;\n const jsonObj = json as object;\n forEach(jsonObj, (key: string, childData: any) => {\n if (contains(jsonObj, key)) {\n if (key.substring(0, 1) !== '.') {\n // ignore metadata nodes.\n const childNode = nodeFromJSON(childData);\n if (childNode.isLeafNode() || !childNode.isEmpty())\n node = node.updateImmediateChild(key, childNode);\n }\n }\n });\n\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/nodeFromJSON.ts","/**\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\n/**\n * @fileoverview Firebase constants. Some of these (@defines) can be overridden at compile-time.\n */\n\nexport const CONSTANTS = {\n /**\n * @define {boolean} Whether this is the client Node.js SDK.\n */\n NODE_CLIENT: false,\n /**\n * @define {boolean} Whether this is the Admin Node.js SDK.\n */\n NODE_ADMIN: false,\n\n /**\n * Firebase SDK Version\n */\n SDK_VERSION: '4.5.0'\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/constants.ts","/**\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\nimport { jsonEval, stringify } from '../../../utils/json';\n\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 */\nexport class DOMStorageWrapper {\n // Use a prefix to avoid collisions with other stuff saved by the app.\n private prefix_ = 'firebase:';\n\n /**\n * @param {Storage} domStorage_ The underlying storage object (e.g. localStorage or sessionStorage)\n */\n constructor(private domStorage_: Storage) {}\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 set(key: string, value: any | null) {\n if (value == null) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n } else {\n this.domStorage_.setItem(this.prefixedName_(key), stringify(value));\n }\n }\n\n /**\n * @param {string} key\n * @return {*} The value that was stored under this key, or null\n */\n get(key: string): any {\n const storedVal = this.domStorage_.getItem(this.prefixedName_(key));\n if (storedVal == null) {\n return null;\n } else {\n return jsonEval(storedVal);\n }\n }\n\n /**\n * @param {string} key\n */\n remove(key: string) {\n this.domStorage_.removeItem(this.prefixedName_(key));\n }\n\n isInMemoryStorage: boolean;\n\n /**\n * @param {string} name\n * @return {string}\n */\n prefixedName_(name: string): string {\n return this.prefix_ + name;\n }\n\n toString(): string {\n return this.domStorage_.toString();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/storage/DOMStorageWrapper.ts","/**\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\nimport { contains } from '../../../utils/obj';\n\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 */\nexport class MemoryStorage {\n private cache_: { [k: string]: any } = {};\n\n set(key: string, value: any | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): any {\n if (contains(this.cache_, key)) {\n return this.cache_[key];\n }\n return null;\n }\n\n remove(key: string) {\n delete this.cache_[key];\n }\n\n isInMemoryStorage = true;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/storage/MemoryStorage.ts","/**\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\nimport { DOMStorageWrapper } from './DOMStorageWrapper';\nimport { MemoryStorage } from './MemoryStorage';\n\ndeclare const window: any;\n\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 */\nconst createStoragefor = function(\n domStorageName: string\n): DOMStorageWrapper | MemoryStorage {\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 (\n typeof window !== 'undefined' &&\n typeof window[domStorageName] !== 'undefined'\n ) {\n // Need to test cache. Just because it's here doesn't mean it works\n const domStorage = window[domStorageName];\n domStorage.setItem('firebase:sentinel', 'cache');\n domStorage.removeItem('firebase:sentinel');\n return new DOMStorageWrapper(domStorage);\n }\n } catch (e) {}\n\n // Failed to create wrapper. Just return in-memory storage.\n // TODO: log?\n return new MemoryStorage();\n};\n\n/** A storage object that lasts across sessions */\nexport const PersistentStorage = createStoragefor('localStorage');\n\n/** A storage object that only lasts one session */\nexport const SessionStorage = createStoragefor('sessionStorage');\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/storage/storage.ts","/**\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\nexport const PROTOCOL_VERSION = '5';\n\nexport const VERSION_PARAM = 'v';\n\nexport const TRANSPORT_SESSION_PARAM = 's';\n\nexport const REFERER_PARAM = 'r';\n\nexport const FORGE_REF = 'f';\n\nexport const FORGE_DOMAIN = 'firebaseio.com';\n\nexport const LAST_SESSION_PARAM = 'ls';\n\nexport const WEBSOCKET = 'websocket';\n\nexport const LONG_POLLING = 'long_polling';\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/realtime/Constants.ts","/**\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\nimport { Node, NamedNode } from '../Node';\nimport { MIN_NAME, MAX_NAME } from '../../util/util';\nimport { Comparator } from '../../util/SortedMap';\n\n/**\n *\n * @constructor\n */\nexport abstract class Index {\n /**\n * @param {!NamedNode} a\n * @param {!NamedNode} b\n * @return {number}\n */\n abstract compare(a: NamedNode, b: NamedNode): number;\n\n /**\n * @param {!Node} node\n * @return {boolean}\n */\n abstract isDefinedOn(node: Node): boolean;\n\n /**\n * @return {function(!NamedNode, !NamedNode):number} A standalone comparison function for\n * this index\n */\n getCompare(): Comparator {\n return this.compare.bind(this);\n }\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 indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n const oldWrapped = new NamedNode(MIN_NAME, oldNode);\n const newWrapped = new NamedNode(MIN_NAME, newNode);\n return this.compare(oldWrapped, newWrapped) !== 0;\n }\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 minPost(): NamedNode {\n return (NamedNode as any).MIN;\n }\n\n /**\n * @return {!NamedNode} a node wrapper that will sort greater than or equal to\n * any other node wrapper, using this index\n */\n abstract maxPost(): NamedNode;\n\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n abstract makePost(indexValue: any, name: string): NamedNode;\n\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/indexes/Index.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { doubleToIEEE754String, sha1 } from '../util/util';\nimport { priorityHashText, validatePriorityNode } from './snap';\nimport { Node } from './Node';\nimport { Path } from '../util/Path';\nimport { Index } from './indexes/Index';\nimport { ChildrenNodeConstructor } from './ChildrenNode';\n\nlet __childrenNodeConstructor: ChildrenNodeConstructor;\n\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 */\nexport class LeafNode implements Node {\n static set __childrenNodeConstructor(val: ChildrenNodeConstructor) {\n __childrenNodeConstructor = val;\n }\n\n static get __childrenNodeConstructor() {\n return __childrenNodeConstructor;\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 static VALUE_TYPE_ORDER = ['object', 'boolean', 'number', 'string'];\n\n private lazyHash_: string | null = null;\n\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 constructor(\n private readonly value_: string | number | boolean | object,\n private priorityNode_: Node = LeafNode.__childrenNodeConstructor.EMPTY_NODE\n ) {\n assert(\n this.value_ !== undefined && this.value_ !== null,\n \"LeafNode shouldn't be created with null/undefined value.\"\n );\n\n validatePriorityNode(this.priorityNode_);\n }\n\n /** @inheritDoc */\n isLeafNode(): boolean {\n return true;\n }\n\n /** @inheritDoc */\n getPriority(): Node {\n return this.priorityNode_;\n }\n\n /** @inheritDoc */\n updatePriority(newPriorityNode: Node): Node {\n return new LeafNode(this.value_, newPriorityNode);\n }\n\n /** @inheritDoc */\n getImmediateChild(childName: string): Node {\n // Hack to treat priority as a regular child\n if (childName === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /** @inheritDoc */\n getChild(path: Path): Node {\n if (path.isEmpty()) {\n return this;\n } else if (path.getFront() === '.priority') {\n return this.priorityNode_;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE;\n }\n }\n\n /**\n * @inheritDoc\n */\n hasChild(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n getPredecessorChildName(childName: String, childNode: Node): null {\n return null;\n }\n\n /** @inheritDoc */\n updateImmediateChild(childName: string, newChildNode: Node): Node {\n if (childName === '.priority') {\n return this.updatePriority(newChildNode);\n } else if (newChildNode.isEmpty() && childName !== '.priority') {\n return this;\n } else {\n return LeafNode.__childrenNodeConstructor.EMPTY_NODE\n .updateImmediateChild(childName, newChildNode)\n .updatePriority(this.priorityNode_);\n }\n }\n\n /** @inheritDoc */\n updateChild(path: Path, newChildNode: Node): Node {\n const front = path.getFront();\n if (front === null) {\n return newChildNode;\n } else if (newChildNode.isEmpty() && front !== '.priority') {\n return this;\n } else {\n assert(\n front !== '.priority' || path.getLength() === 1,\n '.priority must be the last token in a path'\n );\n\n return this.updateImmediateChild(\n front,\n LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(\n path.popFront(),\n newChildNode\n )\n );\n }\n }\n\n /** @inheritDoc */\n isEmpty(): boolean {\n return false;\n }\n\n /** @inheritDoc */\n numChildren(): number {\n return 0;\n }\n\n /** @inheritDoc */\n forEachChild(index: Index, action: (s: string, n: Node) => void): any {\n return false;\n }\n\n /**\n * @inheritDoc\n */\n val(exportFormat?: boolean): Object {\n if (exportFormat && !this.getPriority().isEmpty())\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n else return this.getValue();\n }\n\n /** @inheritDoc */\n hash(): string {\n if (this.lazyHash_ === null) {\n let toHash = '';\n if (!this.priorityNode_.isEmpty())\n toHash +=\n 'priority:' +\n priorityHashText(this.priorityNode_.val() as number | string) +\n ':';\n\n const type = typeof this.value_;\n toHash += type + ':';\n if (type === 'number') {\n toHash += doubleToIEEE754String(this.value_ as number);\n } else {\n toHash += this.value_;\n }\n this.lazyHash_ = sha1(toHash);\n }\n return this.lazyHash_;\n }\n\n /**\n * Returns the value of the leaf node.\n * @return {Object|string|number|boolean} The value of the node.\n */\n getValue(): object | string | number | boolean {\n return this.value_;\n }\n\n /**\n * @inheritDoc\n */\n compareTo(other: Node): number {\n if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {\n return 1;\n } else if (other instanceof LeafNode.__childrenNodeConstructor) {\n return -1;\n } else {\n assert(other.isLeafNode(), 'Unknown node type');\n return this.compareToLeafNode_(other as LeafNode);\n }\n }\n\n /**\n * Comparison specifically for two leaf nodes\n * @param {!LeafNode} otherLeaf\n * @return {!number}\n * @private\n */\n private compareToLeafNode_(otherLeaf: LeafNode): number {\n const otherLeafType = typeof otherLeaf.value_;\n const thisLeafType = typeof this.value_;\n const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);\n const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);\n assert(otherIndex >= 0, 'Unknown leaf type: ' + otherLeafType);\n 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 } 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 } else if (this.value_ === otherLeaf.value_) {\n return 0;\n } else {\n return 1;\n }\n }\n } else {\n return thisIndex - otherIndex;\n }\n }\n\n /**\n * @inheritDoc\n */\n withIndex(): Node {\n return this;\n }\n\n /**\n * @inheritDoc\n */\n isIndexed(): boolean {\n return true;\n }\n\n /**\n * @inheritDoc\n */\n equals(other: Node): boolean {\n /**\n * @inheritDoc\n */\n if (other === this) {\n return true;\n } else if (other.isLeafNode()) {\n const otherLeaf = other as LeafNode;\n return (\n this.value_ === otherLeaf.value_ &&\n this.priorityNode_.equals(otherLeaf.priorityNode_)\n );\n } else {\n return false;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/LeafNode.ts","/**\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\n/**\n * @fileoverview Implementation of an immutable SortedMap using a Left-leaning\n * Red-Black Tree, adapted from the implementation in Mugs\n * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen\n * (mads379@gmail.com).\n *\n * Original paper on Left-leaning Red-Black Trees:\n * http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf\n *\n * Invariant 1: No red node has a red child\n * Invariant 2: Every leaf path has the same number of black nodes\n * Invariant 3: Only the left child can be red (left leaning)\n */\n\n// TODO: There are some improvements I'd like to make to improve memory / perf:\n// * Create two prototypes, LLRedNode and LLBlackNode, instead of storing a\n// color property in every node.\n// TODO: It would also be good (and possibly necessary) to create a base\n// interface for LLRBNode and LLRBEmptyNode.\n\nexport type Comparator = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator {\n /** @private\n * @type {Array.}\n */\n private nodeStack_: (LLRBNode | LLRBEmptyNode)[] = [];\n\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 constructor(\n node: LLRBNode | LLRBEmptyNode,\n startKey: K | null,\n comparator: Comparator,\n private isReverse_: boolean,\n private resultGenerator_: ((k: K, v: V) => T) | null = null\n ) {\n let cmp = 1;\n while (!node.isEmpty()) {\n node = node as LLRBNode;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) cmp *= -1;\n\n if (cmp < 0) {\n // This node is less than our start key. ignore it\n if (this.isReverse_) {\n node = node.left;\n } else {\n node = node.right;\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 } 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 } else {\n node = node.left;\n }\n }\n }\n }\n\n getNext(): T {\n if (this.nodeStack_.length === 0) return null;\n\n let node = this.nodeStack_.pop();\n let result: T;\n if (this.resultGenerator_)\n result = this.resultGenerator_(node.key, node.value);\n else result = { key: node.key, value: node.value } as any;\n\n if (this.isReverse_) {\n node = node.left;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n while (!node.isEmpty()) {\n this.nodeStack_.push(node);\n node = node.left;\n }\n }\n\n return result;\n }\n\n hasNext(): boolean {\n return this.nodeStack_.length > 0;\n }\n\n peek(): T {\n if (this.nodeStack_.length === 0) return null;\n\n const node = this.nodeStack_[this.nodeStack_.length - 1];\n if (this.resultGenerator_) {\n return this.resultGenerator_(node.key, node.value);\n } else {\n return { key: node.key, value: node.value } as any;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode {\n color: boolean;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n\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 constructor(\n public key: K,\n public value: V,\n color: boolean | null,\n left?: LLRBNode | LLRBEmptyNode | null,\n right?: LLRBNode | LLRBEmptyNode | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : SortedMap.EMPTY_NODE as LLRBEmptyNode;\n this.right =\n right != null ? right : SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n\n static RED = true;\n static BLACK = false;\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 copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBNode {\n return new LLRBNode(\n key != null ? key : this.key,\n value != null ? value : this.value,\n color != null ? color : this.color,\n left != null ? left : this.left,\n right != null ? right : this.right\n );\n }\n\n /**\n * @return {number} The total number of nodes in the tree.\n */\n count(): number {\n return this.left.count() + 1 + this.right.count();\n }\n\n /**\n * @return {boolean} True if the tree is empty.\n */\n isEmpty(): boolean {\n return false;\n }\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 inorderTraversal(action: (k: K, v: V) => any): boolean {\n return (\n this.left.inorderTraversal(action) ||\n action(this.key, this.value) ||\n this.right.inorderTraversal(action)\n );\n }\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 reverseTraversal(action: (k: K, v: V) => void): boolean {\n return (\n this.right.reverseTraversal(action) ||\n action(this.key, this.value) ||\n this.left.reverseTraversal(action)\n );\n }\n\n /**\n * @return {!Object} The minimum node in the tree.\n * @private\n */\n private min_(): LLRBNode {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode).min_();\n }\n }\n\n /**\n * @return {!K} The maximum key in the tree.\n */\n minKey(): K {\n return this.min_().key;\n }\n\n /**\n * @return {!K} The maximum key in the tree.\n */\n maxKey(): K {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\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 insert(key: K, value: V, comparator: Comparator): LLRBNode {\n let 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 } else if (cmp === 0) {\n n = n.copy(null, value, null, null, null);\n } else {\n n = n.copy(\n null,\n null,\n null,\n null,\n n.right.insert(key, value, comparator)\n );\n }\n return n.fixUp_();\n }\n\n /**\n * @private\n * @return {!LLRBNode|LLRBEmptyNode} New tree, with the minimum key removed.\n */\n private removeMin_(): LLRBNode | LLRBEmptyNode {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode;\n }\n let n: LLRBNode = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) n = n.moveRedLeft_();\n n = n.copy(null, null, null, (n.left as LLRBNode).removeMin_(), null);\n return n.fixUp_();\n }\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 remove(\n key: K,\n comparator: Comparator\n ): LLRBNode | LLRBEmptyNode {\n let 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 } else {\n if (n.left.isRed_()) 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 as LLRBEmptyNode;\n } else {\n smallest = (n.right as LLRBNode).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode).removeMin_()\n );\n }\n }\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n return n.fixUp_();\n }\n\n /**\n * @private\n * @return {boolean} Whether this is a RED node.\n */\n isRed_(): boolean {\n return this.color;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree after performing any needed rotations.\n */\n private fixUp_(): LLRBNode {\n let n = this as any;\n if (n.right.isRed_() && !n.left.isRed_()) n = n.rotateLeft_();\n if (n.left.isRed_() && n.left.left.isRed_()) n = n.rotateRight_();\n if (n.left.isRed_() && n.right.isRed_()) n = n.colorFlip_();\n return n;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.right.left.isRed_()) {\n n = n.copy(\n null,\n null,\n null,\n null,\n (n.right as LLRBNode).rotateRight_()\n );\n n = n.rotateLeft_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedRight.\n */\n private moveRedRight_(): LLRBNode {\n let n = this.colorFlip_();\n if (n.left.left.isRed_()) {\n n = n.rotateRight_();\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateLeft.\n */\n private rotateLeft_(): LLRBNode {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null) as LLRBNode;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr) as LLRBNode;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n private colorFlip_(): LLRBNode {\n const left = this.left.copy(null, null, !this.left.color, null, null);\n const right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }\n\n /**\n * For testing.\n *\n * @private\n * @return {boolean} True if all is well.\n */\n private checkMaxDepth_(): boolean {\n const blackDepth = this.check_();\n return Math.pow(2.0, blackDepth) <= this.count() + 1;\n }\n\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n check_(): number {\n let blackDepth;\n if (this.isRed_() && this.left.isRed_()) {\n throw new Error(\n 'Red node has red child(' + this.key + ',' + this.value + ')'\n );\n }\n if (this.right.isRed_()) {\n throw new Error(\n 'Right child of (' + this.key + ',' + this.value + ') is red'\n );\n }\n blackDepth = this.left.check_();\n if (blackDepth !== this.right.check_()) {\n throw new Error('Black depths differ');\n } else {\n return blackDepth + (this.isRed_() ? 0 : 1);\n }\n }\n}\n\n/**\n * Represents an empty node (a leaf node in the Red-Black Tree).\n */\nexport class LLRBEmptyNode {\n key: K;\n value: V;\n left: LLRBNode | LLRBEmptyNode;\n right: LLRBNode | LLRBEmptyNode;\n color: boolean;\n\n /**\n * Returns a copy of the current node.\n *\n * @return {!LLRBEmptyNode} The node copy.\n */\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode | LLRBEmptyNode | null,\n right: LLRBNode | LLRBEmptyNode | null\n ): LLRBEmptyNode {\n return this;\n }\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 insert(key: K, value: V, comparator: Comparator): LLRBNode {\n return new LLRBNode(key, value, null);\n }\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 remove(key: K, comparator: Comparator): LLRBEmptyNode {\n return this;\n }\n\n /**\n * @return {number} The total number of nodes in the tree.\n */\n count(): number {\n return 0;\n }\n\n /**\n * @return {boolean} True if the tree is empty.\n */\n isEmpty(): boolean {\n return true;\n }\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 inorderTraversal(action: (k: K, v: V) => any): boolean {\n return false;\n }\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 reverseTraversal(action: (k: K, v: V) => void): boolean {\n return false;\n }\n\n /**\n * @return {null}\n */\n minKey(): null {\n return null;\n }\n\n /**\n * @return {null}\n */\n maxKey(): null {\n return null;\n }\n\n /**\n * @private\n * @return {number} Not sure what this returns exactly. :-).\n */\n check_(): number {\n return 0;\n }\n\n /**\n * @private\n * @return {boolean} Whether this node is red.\n */\n isRed_() {\n return false;\n }\n}\n\n/**\n * An immutable sorted map implementation, based on a Left-leaning Red-Black\n * tree.\n */\nexport class SortedMap {\n /**\n * Always use the same empty node, to reduce memory.\n * @const\n */\n static EMPTY_NODE = new LLRBEmptyNode();\n\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 constructor(\n private comparator_: Comparator,\n private root_:\n | LLRBNode\n | LLRBEmptyNode = SortedMap.EMPTY_NODE as LLRBEmptyNode\n ) {}\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 insert(key: K, value: V): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .insert(key, value, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\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 remove(key: K): SortedMap {\n return new SortedMap(\n this.comparator_,\n this.root_\n .remove(key, this.comparator_)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\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 get(key: K): V | null {\n let cmp;\n let node = this.root_;\n while (!node.isEmpty()) {\n cmp = this.comparator_(key, node.key);\n if (cmp === 0) {\n return node.value;\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n node = node.right;\n }\n }\n return null;\n }\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 getPredecessorKey(key: K): K | null {\n let cmp,\n node = this.root_,\n 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()) node = node.right;\n return node.key;\n } else if (rightParent) {\n return rightParent.key;\n } else {\n return null; // first item.\n }\n } else if (cmp < 0) {\n node = node.left;\n } else if (cmp > 0) {\n rightParent = node;\n node = node.right;\n }\n }\n\n throw new Error(\n 'Attempted to find predecessor key for a nonexistent key. What gives?'\n );\n }\n\n /**\n * @return {boolean} True if the map is empty.\n */\n isEmpty(): boolean {\n return this.root_.isEmpty();\n }\n\n /**\n * @return {number} The total number of nodes in the map.\n */\n count(): number {\n return this.root_.count();\n }\n\n /**\n * @return {?K} The minimum key in the map.\n */\n minKey(): K | null {\n return this.root_.minKey();\n }\n\n /**\n * @return {?K} The maximum key in the map.\n */\n maxKey(): K | null {\n return this.root_.maxKey();\n }\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 inorderTraversal(action: (k: K, v: V) => any): boolean {\n return this.root_.inorderTraversal(action);\n }\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 reverseTraversal(action: (k: K, v: V) => void): boolean {\n return this.root_.reverseTraversal(action);\n }\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 getIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/SortedMap.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { Path } from '../util/Path';\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { ImmutableTree } from '../util/ImmutableTree';\n\nexport class AckUserWrite implements Operation {\n /** @inheritDoc */\n type = OperationType.ACK_USER_WRITE;\n\n /** @inheritDoc */\n source = OperationSource.User;\n\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 constructor(\n /**@inheritDoc */ public path: Path,\n /**@inheritDoc */ public affectedTree: ImmutableTree,\n /**@inheritDoc */ public revert: boolean\n ) {}\n\n /**\n * @inheritDoc\n */\n operationForChild(childName: string): AckUserWrite {\n if (!this.path.isEmpty()) {\n assert(\n this.path.getFront() === childName,\n 'operationForChild called for unrelated child.'\n );\n return new AckUserWrite(\n this.path.popFront(),\n this.affectedTree,\n this.revert\n );\n } else if (this.affectedTree.value != null) {\n assert(\n this.affectedTree.children.isEmpty(),\n 'affectedTree should not have overlapping affected paths.'\n );\n // All child locations are affected as well; just return same operation.\n return this;\n } else {\n const childTree = this.affectedTree.subtree(new Path(childName));\n return new AckUserWrite(Path.Empty, childTree, this.revert);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/operation/AckUserWrite.ts","/**\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\nimport { Path } from '../util/Path';\nimport { Operation, OperationSource, OperationType } from './Operation';\n\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @constructor\n * @implements {Operation}\n */\nexport class ListenComplete implements Operation {\n /** @inheritDoc */\n type = OperationType.LISTEN_COMPLETE;\n\n constructor(public source: OperationSource, public path: Path) {}\n\n operationForChild(childName: string): ListenComplete {\n if (this.path.isEmpty()) {\n return new ListenComplete(this.source, Path.Empty);\n } else {\n return new ListenComplete(this.source, this.path.popFront());\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/operation/ListenComplete.ts","/**\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\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Path } from '../util/Path';\nimport { Node } from '../snap/Node';\n\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!Node} snap\n * @constructor\n * @implements {Operation}\n */\nexport class Overwrite implements Operation {\n /** @inheritDoc */\n type = OperationType.OVERWRITE;\n\n constructor(\n public source: OperationSource,\n public path: Path,\n public snap: Node\n ) {}\n\n operationForChild(childName: string): Overwrite {\n if (this.path.isEmpty()) {\n return new Overwrite(\n this.source,\n Path.Empty,\n this.snap.getImmediateChild(childName)\n );\n } else {\n return new Overwrite(this.source, this.path.popFront(), this.snap);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/operation/Overwrite.ts","/**\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\nimport { Operation, OperationSource, OperationType } from './Operation';\nimport { Overwrite } from './Overwrite';\nimport { Path } from '../util/Path';\nimport { assert } from '../../../utils/assert';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport { Node } from '../snap/Node';\n\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.} children\n * @constructor\n * @implements {Operation}\n */\nexport class Merge implements Operation {\n /** @inheritDoc */\n type = OperationType.MERGE;\n\n constructor(\n /**@inheritDoc */ public source: OperationSource,\n /**@inheritDoc */ public path: Path,\n /**@inheritDoc */ public children: ImmutableTree\n ) {}\n\n /**\n * @inheritDoc\n */\n operationForChild(childName: string): Operation {\n if (this.path.isEmpty()) {\n const childTree = this.children.subtree(new Path(childName));\n if (childTree.isEmpty()) {\n // This child is unaffected\n return null;\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(this.source, Path.Empty, childTree.value);\n } else {\n // This is a merge at a deeper level\n return new Merge(this.source, Path.Empty, childTree);\n }\n } else {\n assert(\n this.path.getFront() === childName,\n \"Can't get a merge for a child not on the path of the operation\"\n );\n return new Merge(this.source, this.path.popFront(), this.children);\n }\n }\n\n /**\n * @inheritDoc\n */\n toString(): string {\n return (\n 'Operation(' +\n this.path +\n ': ' +\n this.source.toString() +\n ' merge: ' +\n this.children.toString() +\n ')'\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/operation/Merge.ts","/**\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\nimport { ImmutableTree } from './util/ImmutableTree';\nimport { Path } from './util/Path';\nimport { forEach } from '../../utils/obj';\nimport { Node, NamedNode } from './snap/Node';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { assert } from '../../utils/assert';\nimport { ChildrenNode } from './snap/ChildrenNode';\n\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 */\nexport class CompoundWrite {\n constructor(private writeTree_: ImmutableTree) {}\n /**\n * @type {!CompoundWrite}\n */\n static Empty = new CompoundWrite(new ImmutableTree(null));\n\n /**\n * @param {!Path} path\n * @param {!Node} node\n * @return {!CompoundWrite}\n */\n addWrite(path: Path, node: Node): CompoundWrite {\n if (path.isEmpty()) {\n return new CompoundWrite(new ImmutableTree(node));\n } else {\n const rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n const rootMostPath = rootmost.path;\n let value = rootmost.value;\n const relativePath = Path.relativePath(rootMostPath, path);\n value = value.updateChild(relativePath, node);\n return new CompoundWrite(this.writeTree_.set(rootMostPath, value));\n } else {\n const subtree = new ImmutableTree(node);\n const newWriteTree = this.writeTree_.setTree(path, subtree);\n return new CompoundWrite(newWriteTree);\n }\n }\n }\n\n /**\n * @param {!Path} path\n * @param {!Object.} updates\n * @return {!CompoundWrite}\n */\n addWrites(path: Path, updates: { [name: string]: Node }): CompoundWrite {\n let newWrite = this as CompoundWrite;\n forEach(updates, function(childKey: string, node: Node) {\n newWrite = newWrite.addWrite(path.child(childKey), node);\n });\n return newWrite;\n }\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 removeWrite(path: Path): CompoundWrite {\n if (path.isEmpty()) {\n return CompoundWrite.Empty;\n } else {\n const newWriteTree = this.writeTree_.setTree(path, ImmutableTree.Empty);\n return new CompoundWrite(newWriteTree);\n }\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 hasCompleteWrite(path: Path): boolean {\n return this.getCompleteNode(path) != null;\n }\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 getCompleteNode(path: Path): Node | null {\n const rootmost = this.writeTree_.findRootMostValueAndPath(path);\n if (rootmost != null) {\n return this.writeTree_\n .get(rootmost.path)\n .getChild(Path.relativePath(rootmost.path, path));\n } else {\n return null;\n }\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 getCompleteChildren(): Array {\n const children: NamedNode[] = [];\n let 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 as ChildrenNode).forEachChild(PRIORITY_INDEX, function(\n childName,\n childNode\n ) {\n children.push(new NamedNode(childName, childNode));\n });\n }\n } else {\n this.writeTree_.children.inorderTraversal(function(childName, childTree) {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n }\n\n /**\n * @param {!Path} path\n * @return {!CompoundWrite}\n */\n childCompoundWrite(path: Path): CompoundWrite {\n if (path.isEmpty()) {\n return this;\n } else {\n const shadowingNode = this.getCompleteNode(path);\n if (shadowingNode != null) {\n return new CompoundWrite(new ImmutableTree(shadowingNode));\n } else {\n return new CompoundWrite(this.writeTree_.subtree(path));\n }\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 isEmpty(): boolean {\n return this.writeTree_.isEmpty();\n }\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 apply(node: Node): Node {\n return CompoundWrite.applySubtreeWrite_(Path.Empty, this.writeTree_, node);\n }\n\n /**\n * @param {!Path} relativePath\n * @param {!ImmutableTree.} writeTree\n * @param {!Node} node\n * @return {!Node}\n * @private\n */\n private static applySubtreeWrite_ = function(\n relativePath: Path,\n writeTree: ImmutableTree,\n node: Node\n ): 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 } else {\n let priorityWrite = 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 assert(\n childTree.value !== null,\n 'Priority writes must always be leaf nodes'\n );\n priorityWrite = childTree.value;\n } else {\n node = CompoundWrite.applySubtreeWrite_(\n relativePath.child(childKey),\n childTree,\n node\n );\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 !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite);\n }\n return node;\n }\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/CompoundWrite.ts","/**\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\nimport { findKey, forEach, safeGet } from '../../utils/obj';\nimport { assert, assertionError } from '../../utils/assert';\nimport { Path } from './util/Path';\nimport { CompoundWrite } from './CompoundWrite';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { NamedNode, Node } from './snap/Node';\nimport { CacheNode } from './view/CacheNode';\nimport { Index } from './snap/indexes/Index';\n\n/**\n * Defines a single user-initiated write operation. May be the result of a set(), transaction(), or update() call. In\n * the case of a set() or transaction, snap wil be non-null. In the case of an update(), children will be non-null.\n */\nexport interface WriteRecord {\n writeId: number;\n path: Path;\n snap?: Node | null;\n children?: { [k: string]: Node } | null;\n visible: boolean;\n}\n\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 */\nexport class 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 private visibleWrites_: CompoundWrite = CompoundWrite.Empty;\n\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 private allWrites_: WriteRecord[] = [];\n\n private 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 childWrites(path: Path): WriteTreeRef {\n return new WriteTreeRef(path, this);\n }\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 addOverwrite(path: Path, snap: Node, writeId: number, visible?: boolean) {\n assert(\n writeId > this.lastWriteId_,\n 'Stacking an older write on top of newer ones'\n );\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\n if (visible) {\n this.visibleWrites_ = this.visibleWrites_.addWrite(path, snap);\n }\n this.lastWriteId_ = writeId;\n }\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 addMerge(\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n ) {\n assert(\n writeId > this.lastWriteId_,\n 'Stacking an older merge on top of newer ones'\n );\n this.allWrites_.push({\n path: path,\n children: changedChildren,\n writeId: writeId,\n visible: true\n });\n\n this.visibleWrites_ = this.visibleWrites_.addWrites(path, changedChildren);\n this.lastWriteId_ = writeId;\n }\n\n /**\n * @param {!number} writeId\n * @return {?WriteRecord}\n */\n getWrite(writeId: number): WriteRecord | null {\n for (let i = 0; i < this.allWrites_.length; i++) {\n const record = this.allWrites_[i];\n if (record.writeId === writeId) {\n return record;\n }\n }\n return null;\n }\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 removeWrite(writeId: number): boolean {\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\n const idx = this.allWrites_.findIndex(function(s) {\n return s.writeId === writeId;\n });\n assert(idx >= 0, 'removeWrite called with nonexistent writeId.');\n const writeToRemove = this.allWrites_[idx];\n this.allWrites_.splice(idx, 1);\n\n let removedWriteWasVisible = writeToRemove.visible;\n let removedWriteOverlapsWithOtherWrites = false;\n\n let i = this.allWrites_.length - 1;\n\n while (removedWriteWasVisible && i >= 0) {\n const currentWrite = this.allWrites_[i];\n if (currentWrite.visible) {\n if (\n i >= idx &&\n this.recordContainsPath_(currentWrite, writeToRemove.path)\n ) {\n // The removed write was completely shadowed by a subsequent write.\n removedWriteWasVisible = false;\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\n if (!removedWriteWasVisible) {\n return false;\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 } 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(\n writeToRemove.path\n );\n } else {\n const children = writeToRemove.children;\n forEach(children, (childName: string) => {\n this.visibleWrites_ = this.visibleWrites_.removeWrite(\n writeToRemove.path.child(childName)\n );\n });\n }\n return true;\n }\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 getCompleteWriteData(path: Path): Node | null {\n return this.visibleWrites_.getCompleteNode(path);\n }\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 calcCompleteEventCache(\n treePath: Path,\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n ): Node | null {\n if (!writeIdsToExclude && !includeHiddenWrites) {\n const shadowingNode = this.visibleWrites_.getCompleteNode(treePath);\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n const subMerge = this.visibleWrites_.childCompoundWrite(treePath);\n if (subMerge.isEmpty()) {\n return completeServerCache;\n } else if (\n completeServerCache == null &&\n !subMerge.hasCompleteWrite(Path.Empty)\n ) {\n // We wouldn't have a complete snapshot, since there's no underlying data and no complete shadow\n return null;\n } else {\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return subMerge.apply(layeredCache);\n }\n }\n } else {\n const merge = this.visibleWrites_.childCompoundWrite(treePath);\n if (!includeHiddenWrites && merge.isEmpty()) {\n return completeServerCache;\n } else {\n // If the server cache is null, and we don't have a complete cache, we need to return null\n if (\n !includeHiddenWrites &&\n completeServerCache == null &&\n !merge.hasCompleteWrite(Path.Empty)\n ) {\n return null;\n } else {\n const filter = function(write: WriteRecord) {\n return (\n (write.visible || includeHiddenWrites) &&\n (!writeIdsToExclude ||\n !~writeIdsToExclude.indexOf(write.writeId)) &&\n (write.path.contains(treePath) || treePath.contains(write.path))\n );\n };\n const mergeAtPath = WriteTree.layerTree_(\n this.allWrites_,\n filter,\n treePath\n );\n const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;\n return mergeAtPath.apply(layeredCache);\n }\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 calcCompleteEventChildren(\n treePath: Path,\n completeServerChildren: ChildrenNode | null\n ) {\n let completeChildren = ChildrenNode.EMPTY_NODE as Node;\n const topLevelSet = this.visibleWrites_.getCompleteNode(treePath);\n if (topLevelSet) {\n if (!topLevelSet.isLeafNode()) {\n // we're shadowing everything. Return the children.\n topLevelSet.forEachChild(PRIORITY_INDEX, function(\n childName,\n childSnap\n ) {\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n childSnap\n );\n });\n }\n return completeChildren;\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 const merge = this.visibleWrites_.childCompoundWrite(treePath);\n completeServerChildren.forEachChild(PRIORITY_INDEX, function(\n childName,\n childNode\n ) {\n const node = merge\n .childCompoundWrite(new Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n });\n // Add any complete children we have from the set\n merge.getCompleteChildren().forEach(function(namedNode) {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\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 const merge = this.visibleWrites_.childCompoundWrite(treePath);\n merge.getCompleteChildren().forEach(function(namedNode) {\n completeChildren = completeChildren.updateImmediateChild(\n namedNode.name,\n namedNode.node\n );\n });\n return completeChildren;\n }\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 calcEventCacheAfterServerOverwrite(\n treePath: Path,\n childPath: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n ): Node | null {\n assert(\n existingEventSnap || existingServerSnap,\n 'Either existingEventSnap or existingServerSnap must exist'\n );\n const 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 } else {\n // No complete shadowing. We're either partially shadowing or not shadowing at all.\n const childMerge = this.visibleWrites_.childCompoundWrite(path);\n if (childMerge.isEmpty()) {\n // We're not shadowing at all. Case 1\n return existingServerSnap.getChild(childPath);\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 /**\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 calcCompleteChild(\n treePath: Path,\n childKey: string,\n existingServerSnap: CacheNode\n ): Node | null {\n const path = treePath.child(childKey);\n const shadowingNode = this.visibleWrites_.getCompleteNode(path);\n if (shadowingNode != null) {\n return shadowingNode;\n } else {\n if (existingServerSnap.isCompleteForChild(childKey)) {\n const childMerge = this.visibleWrites_.childCompoundWrite(path);\n return childMerge.apply(\n existingServerSnap.getNode().getImmediateChild(childKey)\n );\n } else {\n return null;\n }\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 shadowingWrite(path: Path): Node | null {\n return this.visibleWrites_.getCompleteNode(path);\n }\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 calcIndexedSlice(\n treePath: Path,\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n ): NamedNode[] {\n let toIterate: Node;\n const merge = this.visibleWrites_.childCompoundWrite(treePath);\n const shadowingNode = merge.getCompleteNode(Path.Empty);\n if (shadowingNode != null) {\n toIterate = shadowingNode;\n } else if (completeServerData != null) {\n toIterate = merge.apply(completeServerData);\n } else {\n // no children to iterate on\n return [];\n }\n toIterate = toIterate.withIndex(index);\n if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {\n const nodes = [];\n const cmp = index.getCompare();\n const iter = reverse\n ? (toIterate as ChildrenNode).getReverseIteratorFrom(startPost, index)\n : (toIterate as ChildrenNode).getIteratorFrom(startPost, index);\n let 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 } else {\n return [];\n }\n }\n\n /**\n * @param {!WriteRecord} writeRecord\n * @param {!Path} path\n * @return {boolean}\n * @private\n */\n private recordContainsPath_(writeRecord: WriteRecord, path: Path): boolean {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n } else {\n // findKey can return undefined, so use !! to coerce to boolean\n return !!findKey(writeRecord.children, function(\n childSnap: Node,\n childName: string\n ) {\n return writeRecord.path.child(childName).contains(path);\n });\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 private resetTree_() {\n this.visibleWrites_ = WriteTree.layerTree_(\n this.allWrites_,\n WriteTree.DefaultFilter_,\n Path.Empty\n );\n if (this.allWrites_.length > 0) {\n this.lastWriteId_ = this.allWrites_[this.allWrites_.length - 1].writeId;\n } else {\n this.lastWriteId_ = -1;\n }\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 private static DefaultFilter_(write: WriteRecord) {\n return write.visible;\n }\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 private static layerTree_(\n writes: WriteRecord[],\n filter: (w: WriteRecord) => boolean,\n treeRoot: Path\n ): CompoundWrite {\n let compoundWrite = CompoundWrite.Empty;\n for (let i = 0; i < writes.length; ++i) {\n const 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 const writePath = write.path;\n let relativePath;\n if (write.snap) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrite(relativePath, write.snap);\n } else if (writePath.contains(treeRoot)) {\n relativePath = Path.relativePath(writePath, treeRoot);\n compoundWrite = compoundWrite.addWrite(\n Path.Empty,\n write.snap.getChild(relativePath)\n );\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else if (write.children) {\n if (treeRoot.contains(writePath)) {\n relativePath = Path.relativePath(treeRoot, writePath);\n compoundWrite = compoundWrite.addWrites(\n relativePath,\n write.children\n );\n } else if (writePath.contains(treeRoot)) {\n relativePath = Path.relativePath(writePath, treeRoot);\n if (relativePath.isEmpty()) {\n compoundWrite = compoundWrite.addWrites(\n Path.Empty,\n write.children\n );\n } else {\n const child = safeGet(write.children, relativePath.getFront());\n if (child) {\n // There exists a child in this node that matches the root path\n const deepNode = child.getChild(relativePath.popFront());\n compoundWrite = compoundWrite.addWrite(Path.Empty, deepNode);\n }\n }\n } else {\n // There is no overlap between root path and write path, ignore write\n }\n } else {\n throw assertionError('WriteRecord should have .snap or .children');\n }\n }\n }\n return compoundWrite;\n }\n}\n\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 */\nexport class WriteTreeRef {\n /**\n * The path to this particular write tree ref. Used for calling methods on writeTree_ while exposing a simpler\n * interface to callers.\n *\n * @type {!Path}\n * @private\n * @const\n */\n private readonly treePath_: Path;\n\n /**\n * * A reference to the actual tree of write data. All methods are pass-through to the tree, but with the appropriate\n * path prefixed.\n *\n * This lets us make cheap references to points in the tree for sync points without having to copy and maintain all of\n * the data.\n *\n * @type {!WriteTree}\n * @private\n * @const\n */\n private readonly writeTree_: WriteTree;\n\n /**\n * @param {!Path} path\n * @param {!WriteTree} writeTree\n */\n constructor(path: Path, writeTree: WriteTree) {\n this.treePath_ = path;\n this.writeTree_ = writeTree;\n }\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 calcCompleteEventCache(\n completeServerCache: Node | null,\n writeIdsToExclude?: number[],\n includeHiddenWrites?: boolean\n ): Node | null {\n return this.writeTree_.calcCompleteEventCache(\n this.treePath_,\n completeServerCache,\n writeIdsToExclude,\n includeHiddenWrites\n );\n }\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 calcCompleteEventChildren(completeServerChildren: ChildrenNode | null): ChildrenNode {\n return this.writeTree_.calcCompleteEventChildren(\n this.treePath_,\n completeServerChildren\n ) as ChildrenNode;\n }\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 calcEventCacheAfterServerOverwrite(\n path: Path,\n existingEventSnap: Node | null,\n existingServerSnap: Node | null\n ): Node | null {\n return this.writeTree_.calcEventCacheAfterServerOverwrite(\n this.treePath_,\n path,\n existingEventSnap,\n existingServerSnap\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 shadowingWrite(path: Path): Node | null {\n return this.writeTree_.shadowingWrite(this.treePath_.child(path));\n }\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 calcIndexedSlice(\n completeServerData: Node | null,\n startPost: NamedNode,\n count: number,\n reverse: boolean,\n index: Index\n ): NamedNode[] {\n return this.writeTree_.calcIndexedSlice(\n this.treePath_,\n completeServerData,\n startPost,\n count,\n reverse,\n index\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 {!string} childKey\n * @param {!CacheNode} existingServerCache\n * @return {?Node}\n */\n calcCompleteChild(\n childKey: string,\n existingServerCache: CacheNode\n ): Node | null {\n return this.writeTree_.calcCompleteChild(\n this.treePath_,\n childKey,\n existingServerCache\n );\n }\n\n /**\n * Return a WriteTreeRef for a child.\n *\n * @param {string} childName\n * @return {!WriteTreeRef}\n */\n child(childName: string): WriteTreeRef {\n return new WriteTreeRef(this.treePath_.child(childName), this.writeTree_);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/WriteTree.ts","/**\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\nimport { assert } from '../../utils/assert';\nimport { errorForServerCode } from './util/util';\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { forEach, safeGet } from '../../utils/obj';\nimport { ImmutableTree } from './util/ImmutableTree';\nimport { ListenComplete } from './operation/ListenComplete';\nimport { Merge } from './operation/Merge';\nimport { Operation, OperationSource } from './operation/Operation';\nimport { Overwrite } from './operation/Overwrite';\nimport { Path } from './util/Path';\nimport { SyncPoint } from './SyncPoint';\nimport { WriteTree, WriteTreeRef } from './WriteTree';\nimport { Query } from '../api/Query';\nimport { Node } from './snap/Node';\nimport { Event } from './view/Event';\nimport { EventRegistration } from './view/EventRegistration';\nimport { View } from './view/View';\n\n/**\n * @typedef {{\n * startListening: function(\n * !Query,\n * ?number,\n * function():string,\n * function(!string, *):!Array.\n * ):!Array.,\n *\n * stopListening: function(!Query, ?number)\n * }}\n */\nexport interface ListenProvider {\n startListening(\n query: Query,\n tag: number | null,\n hashFn: () => string,\n onComplete: (a: string, b?: any) => Event[]\n ): Event[];\n\n stopListening(a: Query, b: number | null): void;\n}\n\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 */\nexport class SyncTree {\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 private syncPointTree_: ImmutableTree = ImmutableTree.Empty;\n\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 private pendingWriteTree_ = new WriteTree();\n\n private tagToQueryMap_: { [k: string]: string } = {};\n private queryToTagMap_: { [k: string]: number } = {};\n\n /**\n * @param {!ListenProvider} listenProvider_ Used by SyncTree to start / stop listening\n * to server data.\n */\n constructor(private listenProvider_: ListenProvider) {}\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 applyUserOverwrite(\n path: Path,\n newData: Node,\n writeId: number,\n visible?: boolean\n ): Event[] {\n // Record pending write.\n this.pendingWriteTree_.addOverwrite(path, newData, writeId, visible);\n\n if (!visible) {\n return [];\n } else {\n return this.applyOperationToSyncPoints_(\n new Overwrite(OperationSource.User, path, newData)\n );\n }\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 applyUserMerge(\n path: Path,\n changedChildren: { [k: string]: Node },\n writeId: number\n ): Event[] {\n // Record pending merge.\n this.pendingWriteTree_.addMerge(path, changedChildren, writeId);\n\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return this.applyOperationToSyncPoints_(\n new Merge(OperationSource.User, path, changeTree)\n );\n }\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 ackUserWrite(writeId: number, revert: boolean = false) {\n const write = this.pendingWriteTree_.getWrite(writeId);\n const needToReevaluate = this.pendingWriteTree_.removeWrite(writeId);\n if (!needToReevaluate) {\n return [];\n } else {\n let affectedTree = ImmutableTree.Empty;\n if (write.snap != null) {\n // overwrite\n affectedTree = affectedTree.set(Path.Empty, true);\n } else {\n forEach(write.children, function(pathString: string, node: Node) {\n affectedTree = affectedTree.set(new Path(pathString), node);\n });\n }\n return this.applyOperationToSyncPoints_(\n new AckUserWrite(write.path, affectedTree, revert)\n );\n }\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 applyServerOverwrite(path: Path, newData: Node): Event[] {\n return this.applyOperationToSyncPoints_(\n new Overwrite(OperationSource.Server, path, newData)\n );\n }\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 applyServerMerge(\n path: Path,\n changedChildren: { [k: string]: Node }\n ): Event[] {\n const changeTree = ImmutableTree.fromObject(changedChildren);\n\n return this.applyOperationToSyncPoints_(\n new Merge(OperationSource.Server, path, changeTree)\n );\n }\n\n /**\n * Apply a listen complete for a query\n *\n * @param {!Path} path\n * @return {!Array.} Events to raise.\n */\n applyListenComplete(path: Path): Event[] {\n return this.applyOperationToSyncPoints_(\n new ListenComplete(OperationSource.Server, path)\n );\n }\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 applyTaggedQueryOverwrite(path: Path, snap: Node, tag: number): Event[] {\n const queryKey = this.queryKeyForTag_(tag);\n if (queryKey != null) {\n const r = SyncTree.parseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = Path.relativePath(queryPath, path);\n const op = new Overwrite(\n OperationSource.forServerTaggedQuery(queryId),\n relativePath,\n snap\n );\n return this.applyTaggedOperation_(queryPath, op);\n } else {\n // Query must have been removed already\n return [];\n }\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 applyTaggedQueryMerge(\n path: Path,\n changedChildren: { [k: string]: Node },\n tag: number\n ): Event[] {\n const queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n const r = SyncTree.parseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = Path.relativePath(queryPath, path);\n const changeTree = ImmutableTree.fromObject(changedChildren);\n const op = new Merge(\n OperationSource.forServerTaggedQuery(queryId),\n relativePath,\n changeTree\n );\n return this.applyTaggedOperation_(queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\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 applyTaggedListenComplete(path: Path, tag: number): Event[] {\n const queryKey = this.queryKeyForTag_(tag);\n if (queryKey) {\n const r = SyncTree.parseQueryKey_(queryKey);\n const queryPath = r.path,\n queryId = r.queryId;\n const relativePath = Path.relativePath(queryPath, path);\n const op = new ListenComplete(\n OperationSource.forServerTaggedQuery(queryId),\n relativePath\n );\n return this.applyTaggedOperation_(queryPath, op);\n } else {\n // We've already removed the query. No big deal, ignore the update\n return [];\n }\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 addEventRegistration(\n query: Query,\n eventRegistration: EventRegistration\n ): Event[] {\n const path = query.path;\n\n let serverCache: Node | null = null;\n let 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 const relativePath = Path.relativePath(pathToSyncPoint, path);\n serverCache = serverCache || sp.getCompleteServerCache(relativePath);\n foundAncestorDefaultView =\n foundAncestorDefaultView || sp.hasCompleteView();\n });\n let syncPoint = this.syncPointTree_.get(path);\n if (!syncPoint) {\n syncPoint = new SyncPoint();\n this.syncPointTree_ = this.syncPointTree_.set(path, syncPoint);\n } else {\n foundAncestorDefaultView =\n foundAncestorDefaultView || syncPoint.hasCompleteView();\n serverCache = serverCache || syncPoint.getCompleteServerCache(Path.Empty);\n }\n\n let serverCacheComplete;\n if (serverCache != null) {\n serverCacheComplete = true;\n } else {\n serverCacheComplete = false;\n serverCache = ChildrenNode.EMPTY_NODE;\n const subtree = this.syncPointTree_.subtree(path);\n subtree.foreachChild(function(childName, childSyncPoint) {\n const completeCache = childSyncPoint.getCompleteServerCache(Path.Empty);\n if (completeCache) {\n serverCache = serverCache.updateImmediateChild(\n childName,\n completeCache\n );\n }\n });\n }\n\n const viewAlreadyExists = syncPoint.viewExistsForQuery(query);\n if (!viewAlreadyExists && !query.getQueryParams().loadsAllData()) {\n // We need to track a tag for this query\n const queryKey = SyncTree.makeQueryKey_(query);\n assert(\n !(queryKey in this.queryToTagMap_),\n 'View does not exist, but we have a tag'\n );\n const tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap_[queryKey] = tag;\n // Coerce to string to avoid sparse arrays.\n this.tagToQueryMap_['_' + tag] = queryKey;\n }\n const writesCache = this.pendingWriteTree_.childWrites(path);\n let events = syncPoint.addEventRegistration(\n query,\n eventRegistration,\n writesCache,\n serverCache,\n serverCacheComplete\n );\n if (!viewAlreadyExists && !foundAncestorDefaultView) {\n const view /** @type !View */ = syncPoint.viewForQuery(query);\n events = events.concat(this.setupListener_(query, view));\n }\n return events;\n }\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 removeEventRegistration(\n query: Query,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n ): Event[] {\n // Find the syncPoint first. Then deal with whether or not it has matching listeners\n const path = query.path;\n const maybeSyncPoint = this.syncPointTree_.get(path);\n let cancelEvents: Event[] = [];\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 (\n maybeSyncPoint &&\n (query.queryIdentifier() === 'default' ||\n maybeSyncPoint.viewExistsForQuery(query))\n ) {\n /**\n * @type {{removed: !Array., events: !Array.}}\n */\n const removedAndEvents = maybeSyncPoint.removeEventRegistration(\n query,\n eventRegistration,\n cancelError\n );\n if (maybeSyncPoint.isEmpty()) {\n this.syncPointTree_ = this.syncPointTree_.remove(path);\n }\n const 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 const removingDefault =\n -1 !==\n removed.findIndex(function(query) {\n return query.getQueryParams().loadsAllData();\n });\n const covered = this.syncPointTree_.findOnPath(path, function(\n relativePath,\n parentSyncPoint\n ) {\n return parentSyncPoint.hasCompleteView();\n });\n\n if (removingDefault && !covered) {\n const 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 const newViews = this.collectDistinctViewsForSubTree_(subtree);\n\n // Ok, we've collected all the listens we need. Set them up.\n for (let i = 0; i < newViews.length; ++i) {\n const view = newViews[i],\n newQuery = view.getQuery();\n const listener = this.createListenerForView_(view);\n this.listenProvider_.startListening(\n SyncTree.queryForListening_(newQuery),\n this.tagForQuery_(newQuery),\n listener.hashFn,\n 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 const defaultTag: number | null = null;\n this.listenProvider_.stopListening(\n SyncTree.queryForListening_(query),\n defaultTag\n );\n } else {\n removed.forEach((queryToRemove: Query) => {\n const tagToRemove = this.queryToTagMap_[\n SyncTree.makeQueryKey_(queryToRemove)\n ];\n this.listenProvider_.stopListening(\n SyncTree.queryForListening_(queryToRemove),\n tagToRemove\n );\n });\n }\n }\n // Now, clear all of the tags we're tracking for the removed listens\n this.removeTags_(removed);\n } else {\n // No-op, this listener must've been already removed\n }\n return cancelEvents;\n }\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 calcCompleteEventCache(\n path: Path,\n writeIdsToExclude?: number[]\n ): Node | null {\n const includeHiddenSets = true;\n const writeTree = this.pendingWriteTree_;\n const serverCache = this.syncPointTree_.findOnPath(path, function(\n pathSoFar,\n syncPoint\n ) {\n const relativePath = Path.relativePath(pathSoFar, path);\n const serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\n });\n return writeTree.calcCompleteEventCache(\n path,\n serverCache,\n writeIdsToExclude,\n includeHiddenSets\n );\n }\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 private collectDistinctViewsForSubTree_(\n subtree: ImmutableTree\n ): View[] {\n return subtree.fold<\n View[]\n >((relativePath, maybeChildSyncPoint, childMap) => {\n if (maybeChildSyncPoint && maybeChildSyncPoint.hasCompleteView()) {\n const completeView = maybeChildSyncPoint.getCompleteView();\n return [completeView];\n } else {\n // No complete view here, flatten any deeper listens into an array\n let views: View[] = [];\n if (maybeChildSyncPoint) {\n views = maybeChildSyncPoint.getQueryViews();\n }\n forEach(childMap, function(key: string, childViews: View[]) {\n views = views.concat(childViews);\n });\n return views;\n }\n });\n }\n\n /**\n * @param {!Array.} queries\n * @private\n */\n private removeTags_(queries: Query[]) {\n for (let j = 0; j < queries.length; ++j) {\n const removedQuery = queries[j];\n if (!removedQuery.getQueryParams().loadsAllData()) {\n // We should have a tag for this\n const removedQueryKey = SyncTree.makeQueryKey_(removedQuery);\n const removedQueryTag = this.queryToTagMap_[removedQueryKey];\n delete this.queryToTagMap_[removedQueryKey];\n delete this.tagToQueryMap_['_' + removedQueryTag];\n }\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 private static queryForListening_(query: Query): Query {\n if (\n query.getQueryParams().loadsAllData() &&\n !query.getQueryParams().isDefault()\n ) {\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 } else {\n return query;\n }\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 private setupListener_(query: Query, view: View): Event[] {\n const path = query.path;\n const tag = this.tagForQuery_(query);\n const listener = this.createListenerForView_(view);\n\n const events = this.listenProvider_.startListening(\n SyncTree.queryForListening_(query),\n tag,\n listener.hashFn,\n listener.onComplete\n );\n\n const 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 assert(\n !subtree.value.hasCompleteView(),\n \"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 const queriesToStop = subtree.fold(function(\n relativePath,\n maybeChildSyncPoint,\n childMap\n ) {\n if (\n !relativePath.isEmpty() &&\n maybeChildSyncPoint &&\n maybeChildSyncPoint.hasCompleteView()\n ) {\n return [maybeChildSyncPoint.getCompleteView().getQuery()];\n } else {\n // No default listener here, flatten any deeper queries into an array\n let queries: Query[] = [];\n if (maybeChildSyncPoint) {\n queries = queries.concat(\n maybeChildSyncPoint.getQueryViews().map(view => view.getQuery())\n );\n }\n forEach(childMap, function(key: string, childQueries: Query[]) {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\n });\n for (let i = 0; i < queriesToStop.length; ++i) {\n const queryToStop = queriesToStop[i];\n this.listenProvider_.stopListening(\n SyncTree.queryForListening_(queryToStop),\n this.tagForQuery_(queryToStop)\n );\n }\n }\n return events;\n }\n\n /**\n *\n * @param {!View} view\n * @return {{hashFn: function(), onComplete: function(!string, *)}}\n * @private\n */\n private createListenerForView_(\n view: View\n ): { hashFn(): string; onComplete(a: string, b?: any): Event[] } {\n const query = view.getQuery();\n const tag = this.tagForQuery_(query);\n\n return {\n hashFn: () => {\n const cache = view.getServerCache() || ChildrenNode.EMPTY_NODE;\n return cache.hash();\n },\n onComplete: (status: string): Event[] => {\n if (status === 'ok') {\n if (tag) {\n return this.applyTaggedListenComplete(query.path, tag);\n } else {\n return this.applyListenComplete(query.path);\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 const error = errorForServerCode(status, query);\n return this.removeEventRegistration(\n query,\n /*eventRegistration*/ null,\n error\n );\n }\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 private static makeQueryKey_(query: Query): string {\n return query.path.toString() + '$' + query.queryIdentifier();\n }\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 private static parseQueryKey_(\n queryKey: string\n ): { queryId: string; path: Path } {\n const splitIndex = queryKey.indexOf('$');\n assert(\n splitIndex !== -1 && splitIndex < queryKey.length - 1,\n 'Bad queryKey.'\n );\n return {\n queryId: queryKey.substr(splitIndex + 1),\n path: new Path(queryKey.substr(0, splitIndex))\n };\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 private queryKeyForTag_(tag: number): string | null {\n return this.tagToQueryMap_['_' + tag];\n }\n\n /**\n * Return the tag associated with the given query.\n * @param {!Query} query\n * @return {?number}\n * @private\n */\n private tagForQuery_(query: Query): number | null {\n const queryKey = SyncTree.makeQueryKey_(query);\n return safeGet(this.queryToTagMap_, queryKey);\n }\n\n /**\n * Static tracker for next query tag.\n * @type {number}\n * @private\n */\n private static nextQueryTag_ = 1;\n\n /**\n * Static accessor for query tags.\n * @return {number}\n * @private\n */\n private static getNextQueryTag_(): number {\n return SyncTree.nextQueryTag_++;\n }\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 private applyTaggedOperation_(\n queryPath: Path,\n operation: Operation\n ): Event[] {\n const syncPoint = this.syncPointTree_.get(queryPath);\n assert(syncPoint, \"Missing sync point for query tag that we're tracking\");\n const writesCache = this.pendingWriteTree_.childWrites(queryPath);\n return syncPoint.applyOperation(\n operation,\n writesCache,\n /*serverCache=*/ null\n );\n }\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 private applyOperationToSyncPoints_(operation: Operation): Event[] {\n return this.applyOperationHelper_(\n operation,\n this.syncPointTree_,\n /*serverCache=*/ null,\n this.pendingWriteTree_.childWrites(Path.Empty)\n );\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 private applyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n ): Event[] {\n if (operation.path.isEmpty()) {\n return this.applyOperationDescendantsHelper_(\n operation,\n syncPointTree,\n serverCache,\n writesCache\n );\n } else {\n const syncPoint = syncPointTree.get(Path.Empty);\n\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.Empty);\n }\n\n let events: Event[] = [];\n const childName = operation.path.getFront();\n const childOperation = operation.operationForChild(childName);\n const childTree = syncPointTree.children.get(childName);\n if (childTree && childOperation) {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writesCache.child(childName);\n events = events.concat(\n this.applyOperationHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n\n if (syncPoint) {\n events = events.concat(\n syncPoint.applyOperation(operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\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 private applyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree,\n serverCache: Node | null,\n writesCache: WriteTreeRef\n ): Event[] {\n const syncPoint = syncPointTree.get(Path.Empty);\n\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.Empty);\n }\n\n let events: Event[] = [];\n syncPointTree.children.inorderTraversal((childName, childTree) => {\n const childServerCache = serverCache\n ? serverCache.getImmediateChild(childName)\n : null;\n const childWritesCache = writesCache.child(childName);\n const childOperation = operation.operationForChild(childName);\n if (childOperation) {\n events = events.concat(\n this.applyOperationDescendantsHelper_(\n childOperation,\n childTree,\n childServerCache,\n childWritesCache\n )\n );\n }\n });\n\n if (syncPoint) {\n events = events.concat(\n syncPoint.applyOperation(operation, writesCache, serverCache)\n );\n }\n\n return events;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/SyncTree.ts","/**\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\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Path } from './util/Path';\nimport { Node } from './snap/Node';\n\n/**\n * Mutable object which basically just stores a reference to the \"latest\" immutable snapshot.\n *\n * @constructor\n */\nexport class SnapshotHolder {\n private rootNode_: Node = ChildrenNode.EMPTY_NODE;\n\n getNode(path: Path): Node {\n return this.rootNode_.getChild(path);\n }\n\n updateSnapshot(path: Path, newSnapshotNode: Node) {\n this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/SnapshotHolder.ts","/**\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\nimport { log, warn } from './util/util';\nimport { FirebaseApp, FirebaseAuthTokenData } from '../../app/firebase_app';\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class AuthTokenProvider {\n /**\n * @param {!FirebaseApp} app_\n */\n constructor(private app_: FirebaseApp) {}\n\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise}\n */\n getToken(forceRefresh: boolean): Promise {\n return this.app_['INTERNAL']['getToken'](forceRefresh).then(\n 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 log('Got auth/token-not-initialized error. Treating as null token.');\n return null;\n } else {\n return Promise.reject(error);\n }\n }\n );\n }\n\n addTokenChangeListener(listener: (token: string | null) => void) {\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\n removeTokenChangeListener(listener: (token: string | null) => void) {\n this.app_['INTERNAL']['removeAuthTokenListener'](listener);\n }\n\n notifyForInvalidToken() {\n let errorMessage =\n '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 } 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 } 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 warn(errorMessage);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/AuthTokenProvider.ts","/**\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\nimport { clone, forEach } from '../../../utils/obj';\nimport { StatsCollection } from './StatsCollection';\n\n/**\n * Returns the delta from the previous call to get stats.\n *\n * @param collection_ The collection to \"listen\" to.\n * @constructor\n */\nexport class StatsListener {\n private last_: { [k: string]: number } | null = null;\n\n constructor(private collection_: StatsCollection) {}\n\n get(): { [k: string]: number } {\n const newStats = this.collection_.get();\n\n const delta: typeof newStats = clone(newStats);\n if (this.last_) {\n forEach(this.last_, (stat: string, value: number) => {\n delta[stat] = delta[stat] - value;\n });\n }\n this.last_ = newStats;\n\n return delta;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/stats/StatsListener.ts","/**\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\nimport { contains, forEach } from '../../../utils/obj';\nimport { setTimeoutNonBlocking } from '../util/util';\nimport { StatsListener } from './StatsListener';\nimport { StatsCollection } from './StatsCollection';\nimport { ServerActions } from '../ServerActions';\n\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.\nconst FIRST_STATS_MIN_TIME = 10 * 1000;\nconst FIRST_STATS_MAX_TIME = 30 * 1000;\n\n// We'll continue to report stats on average every 5 minutes.\nconst REPORT_STATS_INTERVAL = 5 * 60 * 1000;\n\n/**\n * @constructor\n */\nexport class StatsReporter {\n private statsListener_: StatsListener;\n private statsToReport_: { [k: string]: boolean } = {};\n\n /**\n * @param collection\n * @param server_\n */\n constructor(collection: StatsCollection, private server_: ServerActions) {\n this.statsListener_ = new StatsListener(collection);\n\n const timeout =\n FIRST_STATS_MIN_TIME +\n (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();\n setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));\n }\n\n includeStat(stat: string) {\n this.statsToReport_[stat] = true;\n }\n\n private reportStats_() {\n const stats = this.statsListener_.get();\n const reportedStats: typeof stats = {};\n let haveStatsToReport = false;\n\n forEach(stats, (stat: string, value: number) => {\n if (value > 0 && contains(this.statsToReport_, stat)) {\n reportedStats[stat] = value;\n haveStatsToReport = true;\n }\n });\n\n if (haveStatsToReport) {\n this.server_.reportStats(reportedStats);\n }\n\n // queue our next run.\n setTimeoutNonBlocking(\n this.reportStats_.bind(this),\n Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL)\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/stats/StatsReporter.ts","/**\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\nimport { Path } from '../util/Path';\nimport { log, logger, exceptionGuard } from '../util/util';\nimport { Event } from './Event';\n\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 */\nexport class EventQueue {\n /**\n * @private\n * @type {!Array.}\n */\n private eventLists_: EventList[] = [];\n\n /**\n * Tracks recursion depth of raiseQueuedEvents_, for debugging purposes.\n * @private\n * @type {!number}\n */\n private recursionDepth_ = 0;\n\n /**\n * @param {!Array.} eventDataList The new events to queue.\n */\n queueEvents(eventDataList: Event[]) {\n // We group events by path, storing them in a single EventList, to make it easier to skip over them quickly.\n let currList = null;\n for (let i = 0; i < eventDataList.length; i++) {\n const eventData = eventDataList[i];\n const eventPath = eventData.getPath();\n if (currList !== null && !eventPath.equals(currList.getPath())) {\n this.eventLists_.push(currList);\n currList = null;\n }\n\n if (currList === null) {\n currList = new EventList(eventPath);\n }\n\n currList.add(eventData);\n }\n if (currList) {\n this.eventLists_.push(currList);\n }\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 raiseEventsAtPath(path: Path, eventDataList: Event[]) {\n this.queueEvents(eventDataList);\n this.raiseQueuedEventsMatchingPredicate_((eventPath: Path) =>\n eventPath.equals(path)\n );\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 raiseEventsForChangedPath(changedPath: Path, eventDataList: Event[]) {\n this.queueEvents(eventDataList);\n\n this.raiseQueuedEventsMatchingPredicate_((eventPath: Path) => {\n return eventPath.contains(changedPath) || changedPath.contains(eventPath);\n });\n }\n\n /**\n * @param {!function(!Path):boolean} predicate\n * @private\n */\n private raiseQueuedEventsMatchingPredicate_(\n predicate: (path: Path) => boolean\n ) {\n this.recursionDepth_++;\n\n let sentAll = true;\n for (let i = 0; i < this.eventLists_.length; i++) {\n const eventList = this.eventLists_[i];\n if (eventList) {\n const eventPath = eventList.getPath();\n if (predicate(eventPath)) {\n this.eventLists_[i].raise();\n this.eventLists_[i] = null;\n } else {\n sentAll = false;\n }\n }\n }\n\n if (sentAll) {\n this.eventLists_ = [];\n }\n\n this.recursionDepth_--;\n }\n}\n\n/**\n * @param {!Path} path\n * @constructor\n */\nexport class EventList {\n /**\n * @type {!Array.}\n * @private\n */\n private events_: Event[] = [];\n\n constructor(private readonly path_: Path) {}\n\n /**\n * @param {!Event} eventData\n */\n add(eventData: Event) {\n this.events_.push(eventData);\n }\n\n /**\n * Iterates through the list and raises each event\n */\n raise() {\n for (let i = 0; i < this.events_.length; i++) {\n const eventData = this.events_[i];\n if (eventData !== null) {\n this.events_[i] = null;\n const eventFn = eventData.getEventRunner();\n if (logger) {\n log('event: ' + eventData.toString());\n }\n exceptionGuard(eventFn);\n }\n }\n }\n\n /**\n * @return {!Path}\n */\n getPath(): Path {\n return this.path_;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/EventQueue.ts","/**\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\nimport { forEach } from './obj';\n\n/**\n * Returns a querystring-formatted string (e.g. &arg=val&arg2=val2) from a params\n * object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n *\n * @param {!Object} querystringParams\n * @return {string}\n */\nexport const querystring = function(querystringParams) {\n var params = [];\n forEach(querystringParams, function(key, value) {\n if (Array.isArray(value)) {\n value.forEach(function(arrayVal) {\n params.push(\n encodeURIComponent(key) + '=' + encodeURIComponent(arrayVal)\n );\n });\n } else {\n params.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n }\n });\n return params.length ? '&' + params.join('&') : '';\n};\n\n/**\n * Decodes a querystring (e.g. ?arg=val&arg2=val2) into a params object (e.g. {arg: 'val', arg2: 'val2'})\n *\n * @param {string} querystring\n * @return {!Object}\n */\nexport const querystringDecode = function(querystring) {\n var obj = {};\n var tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(function(token) {\n if (token) {\n var key = token.split('=');\n obj[key[0]] = key[1];\n }\n });\n return obj;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/util.ts","/**\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\nimport { assert } from '../../utils/assert';\nimport { logWrapper, warn } from './util/util';\nimport { jsonEval } from '../../utils/json';\nimport { safeGet } from '../../utils/obj';\nimport { querystring } from '../../utils/util';\nimport { ServerActions } from './ServerActions';\nimport { RepoInfo } from './RepoInfo';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { Query } from '../api/Query';\n\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 */\nexport class ReadonlyRestClient extends ServerActions {\n reportStats(stats: { [k: string]: any }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: any[]) => void = logWrapper('p:rest:');\n\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 private listens_: { [k: string]: Object } = {};\n\n /**\n * @param {!Query} query\n * @param {?number=} tag\n * @return {string}\n * @private\n */\n static getListenId_(query: Query, tag?: number | null): string {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n assert(\n query.getQueryParams().isDefault(),\n \"should have a tag if it's not a default query.\"\n );\n return query.path.toString();\n }\n }\n\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 constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: any,\n c: boolean,\n d: number | null\n ) => void,\n private authTokenProvider_: AuthTokenProvider\n ) {\n super();\n }\n\n /** @inheritDoc */\n listen(\n query: Query,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: any) => void\n ) {\n const pathString = query.path.toString();\n this.log_(\n 'Listen called for ' + pathString + ' ' + query.queryIdentifier()\n );\n\n // Mark this listener so we can tell if it's removed.\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n const thisListen = {};\n this.listens_[listenId] = thisListen;\n\n const queryStringParamaters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParamaters,\n (error, result) => {\n let data = result;\n\n if (error === 404) {\n data = null;\n error = null;\n }\n\n if (error === null) {\n this.onDataUpdate_(pathString, data, /*isMerge=*/ false, tag);\n }\n\n if (safeGet(this.listens_, listenId) === thisListen) {\n let status;\n if (!error) {\n status = 'ok';\n } else if (error == 401) {\n status = 'permission_denied';\n } else {\n status = 'rest_error:' + error;\n }\n\n onComplete(status, null);\n }\n }\n );\n }\n\n /** @inheritDoc */\n unlisten(query: Query, tag: number | null) {\n const listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n }\n\n /** @inheritDoc */\n refreshAuthToken(token: string) {\n // no-op since we just always call getToken.\n }\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 private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: any } = {},\n callback: ((a: number | null, b?: any) => void) | null\n ) {\n queryStringParameters['format'] = 'export';\n\n this.authTokenProvider_\n .getToken(/*forceRefresh=*/ false)\n .then(authTokenData => {\n const authToken = authTokenData && authTokenData.accessToken;\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n\n const url =\n (this.repoInfo_.secure ? 'https://' : 'http://') +\n this.repoInfo_.host +\n pathString +\n '?' +\n querystring(queryStringParameters);\n\n this.log_('Sending REST request for ' + url);\n const xhr = new XMLHttpRequest();\n xhr.onreadystatechange = () => {\n if (callback && xhr.readyState === 4) {\n this.log_(\n 'REST Response for ' + url + ' received. status:',\n xhr.status,\n 'response:',\n xhr.responseText\n );\n let res = null;\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = jsonEval(xhr.responseText);\n } catch (e) {\n warn(\n 'Failed to parse JSON response for ' +\n url +\n ': ' +\n xhr.responseText\n );\n }\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn(\n 'Got unsuccessful REST response for ' +\n url +\n ' Status: ' +\n xhr.status\n );\n }\n callback(xhr.status);\n }\n callback = null;\n }\n };\n\n xhr.open('GET', url, /*asynchronous=*/ true);\n xhr.send();\n });\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/ReadonlyRestClient.ts","/**\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\nimport {\n generateWithValues,\n resolveDeferredValueSnapshot,\n resolveDeferredValueTree\n} from './util/ServerValues';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { Path } from './util/Path';\nimport { SparseSnapshotTree } from './SparseSnapshotTree';\nimport { SyncTree } from './SyncTree';\nimport { SnapshotHolder } from './SnapshotHolder';\nimport { stringify } from '../../utils/json';\nimport { beingCrawled, each, exceptionGuard, warn, log } from './util/util';\nimport { map, forEach, isEmpty } from '../../utils/obj';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { StatsManager } from './stats/StatsManager';\nimport { StatsReporter } from './stats/StatsReporter';\nimport { StatsListener } from './stats/StatsListener';\nimport { EventQueue } from './view/EventQueue';\nimport { PersistentConnection } from './PersistentConnection';\nimport { ReadonlyRestClient } from './ReadonlyRestClient';\nimport { FirebaseApp } from '../../app/firebase_app';\nimport { RepoInfo } from './RepoInfo';\nimport { Database } from '../api/Database';\nimport { ServerActions } from './ServerActions';\nimport { Query } from '../api/Query';\nimport { EventRegistration } from './view/EventRegistration';\nimport { StatsCollection } from './stats/StatsCollection';\nimport { Event } from './view/Event';\nimport { Node } from './snap/Node';\n\nconst INTERRUPT_REASON = 'repo_interrupt';\n\n/**\n * A connection to a single data repository.\n */\nexport class Repo {\n dataUpdateCount = 0;\n private infoSyncTree_: SyncTree;\n private serverSyncTree_: SyncTree;\n\n private stats_: StatsCollection;\n private statsListener_: StatsListener | null = null;\n private eventQueue_ = new EventQueue();\n private nextWriteId_ = 1;\n private server_: ServerActions;\n private statsReporter_: StatsReporter;\n private transactions_init_: () => void;\n private infoData_: SnapshotHolder;\n private abortTransactions_: (path: Path) => Path;\n private rerunTransactions_: (changedPath: Path) => Path;\n private interceptServerDataCallback_:\n | ((a: string, b: any) => void)\n | null = null;\n private __database: Database;\n\n // A list of data pieces and paths to be set when this client disconnects.\n private onDisconnect_ = new SparseSnapshotTree();\n\n /**\n * TODO: This should be @private but it's used by test_access.js and internal.js\n * @type {?PersistentConnection}\n */\n persistentConnection_: PersistentConnection | null = null;\n\n /**\n * @param {!RepoInfo} repoInfo_\n * @param {boolean} forceRestClient\n * @param {!FirebaseApp} app\n */\n constructor(\n public repoInfo_: RepoInfo,\n forceRestClient: boolean,\n public app: FirebaseApp\n ) {\n /** @type {!AuthTokenProvider} */\n const authTokenProvider = new AuthTokenProvider(app);\n\n this.stats_ = StatsManager.getCollection(repoInfo_);\n\n if (forceRestClient || beingCrawled()) {\n this.server_ = new ReadonlyRestClient(\n this.repoInfo_,\n this.onDataUpdate_.bind(this),\n authTokenProvider\n );\n\n // Minor hack: Fire onConnect immediately, since there's no actual connection.\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n } else {\n const authOverride = app.options['databaseAuthVariableOverride'];\n // Validate authOverride\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error(\n 'Only objects are supported for option databaseAuthVariableOverride'\n );\n }\n try {\n stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n this.persistentConnection_ = new PersistentConnection(\n this.repoInfo_,\n this.onDataUpdate_.bind(this),\n this.onConnectStatus_.bind(this),\n this.onServerInfoUpdate_.bind(this),\n authTokenProvider,\n authOverride\n );\n\n this.server_ = this.persistentConnection_;\n }\n\n authTokenProvider.addTokenChangeListener(token => {\n this.server_.refreshAuthToken(token);\n });\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.getOrCreateReporter(\n repoInfo_,\n () => new StatsReporter(this.stats_, this.server_)\n );\n\n this.transactions_init_();\n\n // Used for .info.\n this.infoData_ = new SnapshotHolder();\n this.infoSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n let infoEvents: Event[] = [];\n const 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(\n query.path,\n node\n );\n setTimeout(() => {\n onComplete('ok');\n }, 0);\n }\n return infoEvents;\n },\n stopListening: () => {}\n });\n this.updateInfo_('connected', false);\n\n this.serverSyncTree_ = new SyncTree({\n startListening: (query, tag, currentHashFn, onComplete) => {\n this.server_.listen(query, currentHashFn, tag, (status, data) => {\n const 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: (query, tag) => {\n this.server_.unlisten(query, tag);\n }\n });\n }\n\n /**\n * @return {string} The URL corresponding to the root of this Firebase.\n */\n toString(): string {\n return (\n (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host\n );\n }\n\n /**\n * @return {!string} The namespace represented by the repo.\n */\n name(): string {\n return this.repoInfo_.namespace;\n }\n\n /**\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\n */\n serverTime(): number {\n const offsetNode = this.infoData_.getNode(\n new Path('.info/serverTimeOffset')\n );\n const offset = (offsetNode.val() as number) || 0;\n return new Date().getTime() + offset;\n }\n\n /**\n * Generate ServerValues using some variables from the repo object.\n * @return {!Object}\n */\n generateServerValues(): Object {\n return generateWithValues({\n timestamp: this.serverTime()\n });\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 private onDataUpdate_(\n pathString: string,\n data: any,\n isMerge: boolean,\n tag: number | null\n ) {\n // For testing.\n this.dataUpdateCount++;\n const path = new Path(pathString);\n data = this.interceptServerDataCallback_\n ? this.interceptServerDataCallback_(pathString, data)\n : data;\n let events = [];\n if (tag) {\n if (isMerge) {\n const taggedChildren = map(data as { [k: string]: any }, (raw: any) =>\n nodeFromJSON(raw)\n );\n events = this.serverSyncTree_.applyTaggedQueryMerge(\n path,\n taggedChildren,\n tag\n );\n } else {\n const taggedSnap = nodeFromJSON(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(\n path,\n taggedSnap,\n tag\n );\n }\n } else if (isMerge) {\n const changedChildren = map(data as { [k: string]: any }, (raw: any) =>\n nodeFromJSON(raw)\n );\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n } else {\n const snap = nodeFromJSON(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n let 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 /**\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 interceptServerData_(callback: ((a: string, b: any) => any) | null) {\n this.interceptServerDataCallback_ = callback;\n }\n\n /**\n * @param {!boolean} connectStatus\n * @private\n */\n private onConnectStatus_(connectStatus: boolean) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n }\n\n /**\n * @param {!Object} updates\n * @private\n */\n private onServerInfoUpdate_(updates: Object) {\n each(updates, (value: any, key: string) => {\n this.updateInfo_(key, value);\n });\n }\n\n /**\n *\n * @param {!string} pathString\n * @param {*} value\n * @private\n */\n private updateInfo_(pathString: string, value: any) {\n const path = new Path('/.info/' + pathString);\n const newNode = nodeFromJSON(value);\n this.infoData_.updateSnapshot(path, newNode);\n const events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n }\n\n /**\n * @return {!number}\n * @private\n */\n private getNextWriteId_(): number {\n return this.nextWriteId_++;\n }\n\n /**\n * @param {!Path} path\n * @param {*} newVal\n * @param {number|string|null} newPriority\n * @param {?function(?Error, *=)} onComplete\n */\n setWithPriority(\n path: Path,\n newVal: any,\n newPriority: number | string | null,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n ) {\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n });\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 const serverValues = this.generateServerValues();\n const newNodeUnresolved = nodeFromJSON(newVal, newPriority);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n serverValues\n );\n\n const writeId = this.getNextWriteId_();\n const events = this.serverSyncTree_.applyUserOverwrite(\n path,\n newNode,\n writeId,\n true\n );\n this.eventQueue_.queueEvents(events);\n this.server_.put(\n path.toString(),\n newNodeUnresolved.val(/*export=*/ true),\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = this.serverSyncTree_.ackUserWrite(\n writeId,\n !success\n );\n this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n this.callOnCompleteCallback(onComplete, status, errorReason);\n }\n );\n const 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 /**\n * @param {!Path} path\n * @param {!Object} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n update(\n path: Path,\n childrenToMerge: { [k: string]: any },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n ) {\n this.log_('update', { path: path.toString(), value: childrenToMerge });\n\n // Start with our existing data and merge each child into it.\n let empty = true;\n const serverValues = this.generateServerValues();\n const changedChildren: { [k: string]: Node } = {};\n forEach(childrenToMerge, (changedKey: string, changedValue: any) => {\n empty = false;\n const newNodeUnresolved = nodeFromJSON(changedValue);\n changedChildren[changedKey] = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n serverValues\n );\n });\n\n if (!empty) {\n const writeId = this.getNextWriteId_();\n const events = this.serverSyncTree_.applyUserMerge(\n path,\n changedChildren,\n writeId\n );\n this.eventQueue_.queueEvents(events);\n this.server_.merge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n const success = status === 'ok';\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n const clearEvents = this.serverSyncTree_.ackUserWrite(\n writeId,\n !success\n );\n const affectedPath =\n clearEvents.length > 0 ? this.rerunTransactions_(path) : path;\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n this.callOnCompleteCallback(onComplete, status, errorReason);\n }\n );\n\n forEach(childrenToMerge, (changedPath: string) => {\n const affectedPath = this.abortTransactions_(path.child(changedPath));\n this.rerunTransactions_(affectedPath);\n });\n\n // We queued the events above, so just flush the queue here\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n }\n\n /**\n * Applies all of the changes stored up in the onDisconnect_ tree.\n * @private\n */\n private runOnDisconnectEvents_() {\n this.log_('onDisconnectEvents');\n\n const serverValues = this.generateServerValues();\n const resolvedOnDisconnectTree = resolveDeferredValueTree(\n this.onDisconnect_,\n serverValues\n );\n let events: Event[] = [];\n\n resolvedOnDisconnectTree.forEachTree(Path.Empty, (path, snap) => {\n events = events.concat(\n this.serverSyncTree_.applyServerOverwrite(path, snap)\n );\n const affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath);\n });\n\n this.onDisconnect_ = new SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path.Empty, events);\n }\n\n /**\n * @param {!Path} path\n * @param {?function(?Error, *=)} onComplete\n */\n onDisconnectCancel(\n path: Path,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n ) {\n this.server_.onDisconnectCancel(path.toString(), (status, errorReason) => {\n if (status === 'ok') {\n this.onDisconnect_.forget(path);\n }\n this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n }\n\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {?function(?Error, *=)} onComplete\n */\n onDisconnectSet(\n path: Path,\n value: any,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n ) {\n const newNode = nodeFromJSON(value);\n this.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n this.onDisconnect_.remember(path, newNode);\n }\n this.callOnCompleteCallback(onComplete, status, errorReason);\n }\n );\n }\n\n /**\n * @param {!Path} path\n * @param {*} value\n * @param {*} priority\n * @param {?function(?Error, *=)} onComplete\n */\n onDisconnectSetWithPriority(\n path: Path,\n value: any,\n priority: any,\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n ) {\n const newNode = nodeFromJSON(value, priority);\n this.server_.onDisconnectPut(\n path.toString(),\n newNode.val(/*export=*/ true),\n (status, errorReason) => {\n if (status === 'ok') {\n this.onDisconnect_.remember(path, newNode);\n }\n this.callOnCompleteCallback(onComplete, status, errorReason);\n }\n );\n }\n\n /**\n * @param {!Path} path\n * @param {*} childrenToMerge\n * @param {?function(?Error, *=)} onComplete\n */\n onDisconnectUpdate(\n path: Path,\n childrenToMerge: { [k: string]: any },\n onComplete: ((status: Error | null, errorReason?: string) => void) | null\n ) {\n if (isEmpty(childrenToMerge)) {\n log(\n \"onDisconnect().update() called with empty data. Don't do anything.\"\n );\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n\n this.server_.onDisconnectMerge(\n path.toString(),\n childrenToMerge,\n (status, errorReason) => {\n if (status === 'ok') {\n forEach(childrenToMerge, (childName: string, childNode: any) => {\n const newChildNode = nodeFromJSON(childNode);\n this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n this.callOnCompleteCallback(onComplete, status, errorReason);\n }\n );\n }\n\n /**\n * @param {!Query} query\n * @param {!EventRegistration} eventRegistration\n */\n addEventCallbackForQuery(query: Query, eventRegistration: EventRegistration) {\n let events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(\n query,\n eventRegistration\n );\n } else {\n events = this.serverSyncTree_.addEventRegistration(\n query,\n eventRegistration\n );\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n }\n\n /**\n * @param {!Query} query\n * @param {?EventRegistration} eventRegistration\n */\n removeEventCallbackForQuery(\n query: Query,\n eventRegistration: EventRegistration\n ) {\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 let events;\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(\n query,\n eventRegistration\n );\n } else {\n events = this.serverSyncTree_.removeEventRegistration(\n query,\n eventRegistration\n );\n }\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n }\n\n interrupt() {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n }\n\n resume() {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n }\n\n stats(showDelta: boolean = false) {\n if (typeof console === 'undefined') return;\n\n let stats: { [k: string]: any };\n if (showDelta) {\n if (!this.statsListener_)\n this.statsListener_ = new StatsListener(this.stats_);\n stats = this.statsListener_.get();\n } else {\n stats = this.stats_.get();\n }\n\n const longestName = Object.keys(stats).reduce(\n (previousValue, currentValue) =>\n Math.max(currentValue.length, previousValue),\n 0\n );\n\n forEach(stats, (stat: string, value: any) => {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) stat += ' ';\n console.log(stat + value);\n });\n }\n\n statsIncrementCounter(metric: string) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n }\n\n /**\n * @param {...*} var_args\n * @private\n */\n private log_(...var_args: any[]) {\n let prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n log(prefix, ...var_args);\n }\n\n /**\n * @param {?function(?Error, *=)} callback\n * @param {!string} status\n * @param {?string=} errorReason\n */\n callOnCompleteCallback(\n callback: ((status: Error | null, errorReason?: string) => void) | null,\n status: string,\n errorReason?: string | null\n ) {\n if (callback) {\n exceptionGuard(function() {\n if (status == 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) message += ': ' + errorReason;\n\n const error = new Error(message);\n (error as any).code = code;\n callback(error);\n }\n });\n }\n }\n\n get database(): Database {\n return this.__database || (this.__database = new Database(this));\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/Repo.ts","/**\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\nimport { assert } from './assert';\n\n// Code originally came from goog.crypt.stringToUtf8ByteArray, but for some reason they\n// automatically replaced '\\r\\n' with '\\n', and they didn't handle surrogate pairs,\n// so it's been modified.\n\n// Note that not all Unicode characters appear as single characters in JavaScript strings.\n// fromCharCode returns the UTF-16 encoding of a character - so some Unicode characters\n// use 2 characters in Javascript. All 4-byte UTF-8 characters begin with a first\n// character in the range 0xD800 - 0xDBFF (the first character of a so-called surrogate\n// pair).\n// See http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3\n\n/**\n * @param {string} str\n * @return {Array}\n */\nexport const stringToByteArray = function(str) {\n var out = [],\n p = 0;\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n var high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n var low = str.charCodeAt(i) - 0xdc00; // the low 10 bits.\n c = 0x10000 + (high << 10) + low;\n }\n\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (c < 65536) {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Calculate length without actually converting; useful for doing cheaper validation.\n * @param {string} str\n * @return {number}\n */\nexport const stringLength = function(str) {\n var p = 0;\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\n if (c < 128) {\n p++;\n } else if (c < 2048) {\n p += 2;\n } else if (c >= 0xd800 && c <= 0xdbff) {\n // Lead surrogate of a surrogate pair. The pair together will take 4 bytes to represent.\n p += 4;\n i++; // skip trail surrogate.\n } else {\n p += 3;\n }\n }\n return p;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/utf8.ts","/**\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\nimport { validateArgCount, validateCallback } from '../../utils/validation';\nimport {\n validateWritablePath,\n validateFirebaseDataArg,\n validatePriority,\n validateFirebaseMergeDataArg\n} from '../core/util/validation';\nimport { warn } from '../core/util/util';\nimport { Deferred } from '../../utils/promise';\nimport { Repo } from '../core/Repo';\nimport { Path } from '../core/util/Path';\n\n/**\n * @constructor\n */\nexport class OnDisconnect {\n /**\n * @param {!Repo} repo_\n * @param {!Path} path_\n */\n constructor(private repo_: Repo, private path_: Path) {}\n\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n cancel(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n const deferred = new Deferred();\n this.repo_.onDisconnectCancel(\n this.path_,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.remove', 0, 1, arguments.length);\n validateWritablePath('OnDisconnect.remove', this.path_);\n validateCallback('OnDisconnect.remove', 1, onComplete, true);\n const deferred = new Deferred();\n this.repo_.onDisconnectSet(\n this.path_,\n null,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {*} value\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n set(value: any, onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('OnDisconnect.set', 1, 2, arguments.length);\n validateWritablePath('OnDisconnect.set', this.path_);\n validateFirebaseDataArg('OnDisconnect.set', 1, value, this.path_, false);\n validateCallback('OnDisconnect.set', 2, onComplete, true);\n const deferred = new Deferred();\n this.repo_.onDisconnectSet(\n this.path_,\n value,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {*} value\n * @param {number|string|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n setWithPriority(\n value: any,\n priority: number | string | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.setWithPriority', 2, 3, arguments.length);\n validateWritablePath('OnDisconnect.setWithPriority', this.path_);\n validateFirebaseDataArg(\n 'OnDisconnect.setWithPriority',\n 1,\n value,\n this.path_,\n false\n );\n validatePriority('OnDisconnect.setWithPriority', 2, priority, false);\n validateCallback('OnDisconnect.setWithPriority', 3, onComplete, true);\n\n const deferred = new Deferred();\n this.repo_.onDisconnectSetWithPriority(\n this.path_,\n value,\n priority,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!firebase.Promise}\n */\n update(\n objectToMerge: object,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: any } = {};\n for (let i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n warn(\n '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 }\n validateFirebaseMergeDataArg(\n 'OnDisconnect.update',\n 1,\n objectToMerge,\n this.path_,\n false\n );\n validateCallback('OnDisconnect.update', 2, onComplete, true);\n const deferred = new Deferred();\n this.repo_.onDisconnectUpdate(\n this.path_,\n objectToMerge,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/onDisconnect.ts","/**\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\nimport { DataSnapshot } from './DataSnapshot';\nimport { validateArgCount } from '../../utils/validation';\n\nexport class TransactionResult {\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 constructor(public committed: boolean, public snapshot: DataSnapshot) {}\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): object {\n validateArgCount('TransactionResult.toJSON', 0, 1, arguments.length);\n return { committed: this.committed, snapshot: this.snapshot.toJSON() };\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/TransactionResult.ts","/**\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\nimport { assert } from '../../../utils/assert';\n\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 */\nexport const nextPushId = (function() {\n // Modeled after base64 web-safe chars, but ordered by ASCII.\n const PUSH_CHARS =\n '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz';\n\n // Timestamp of last push, used to prevent local collisions if you push twice\n // in one ms.\n let lastPushTime = 0;\n\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 const lastRandChars: number[] = [];\n\n return function(now: number) {\n const duplicateTime = now === lastPushTime;\n lastPushTime = now;\n\n let i;\n const 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 assert(now === 0, 'Cannot push at time == 0');\n\n let id = timeStampChars.join('');\n\n if (!duplicateTime) {\n for (i = 0; i < 12; i++) {\n lastRandChars[i] = Math.floor(Math.random() * 64);\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 assert(id.length === 20, 'nextPushId: Length should be 20.');\n\n return id;\n };\n})();\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/NextPushId.ts","/**\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\nimport { IndexedFilter } from './IndexedFilter';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { NamedNode, Node } from '../../../core/snap/Node';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { NodeFilter } from './NodeFilter';\nimport { QueryParams } from '../QueryParams';\nimport { Index } from '../../snap/indexes/Index';\nimport { Path } from '../../util/Path';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\n\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 */\nexport class RangedFilter implements NodeFilter {\n /**\n * @type {!IndexedFilter}\n * @const\n * @private\n */\n private indexedFilter_: IndexedFilter;\n\n /**\n * @const\n * @type {!Index}\n * @private\n */\n private index_: Index;\n\n /**\n * @const\n * @type {!NamedNode}\n * @private\n */\n private startPost_: NamedNode;\n\n /**\n * @const\n * @type {!NamedNode}\n * @private\n */\n private endPost_: NamedNode;\n\n /**\n * @param {!QueryParams} params\n */\n constructor(params: QueryParams) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n\n /**\n * @return {!NamedNode}\n */\n getStartPost(): NamedNode {\n return this.startPost_;\n }\n\n /**\n * @return {!NamedNode}\n */\n getEndPost(): NamedNode {\n return this.endPost_;\n }\n\n /**\n * @param {!NamedNode} node\n * @return {boolean}\n */\n matches(node: NamedNode): boolean {\n return (\n this.index_.compare(this.getStartPost(), node) <= 0 &&\n this.index_.compare(node, this.getEndPost()) <= 0\n );\n }\n\n /**\n * @inheritDoc\n */\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n return this.indexedFilter_.updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n }\n\n /**\n * @inheritDoc\n */\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n let filtered = newSnap.withIndex(this.index_);\n // Don't support priorities on queries\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n const self = this;\n newSnap.forEachChild(PRIORITY_INDEX, function(key, childNode) {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(\n oldSnap,\n filtered,\n optChangeAccumulator\n );\n }\n\n /**\n * @inheritDoc\n */\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n\n /**\n * @inheritDoc\n */\n filtersNodes(): boolean {\n return true;\n }\n\n /**\n * @inheritDoc\n */\n getIndexedFilter(): IndexedFilter {\n return this.indexedFilter_;\n }\n\n /**\n * @inheritDoc\n */\n getIndex(): Index {\n return this.index_;\n }\n\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n private static getStartPost_(params: QueryParams): NamedNode {\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n }\n\n /**\n * @param {!QueryParams} params\n * @return {!NamedNode}\n * @private\n */\n private static getEndPost_(params: QueryParams): NamedNode {\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/filter/RangedFilter.ts","/**\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\nimport { RangedFilter } from './RangedFilter';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { Node, NamedNode } from '../../snap/Node';\nimport { assert } from '../../../../utils/assert';\nimport { Change } from '../Change';\nimport { NodeFilter } from './NodeFilter';\nimport { Index } from '../../snap/indexes/Index';\nimport { IndexedFilter } from './IndexedFilter';\nimport { QueryParams } from '../QueryParams';\nimport { Path } from '../../util/Path';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\n\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 */\nexport class LimitedFilter implements NodeFilter {\n /**\n * @const\n * @type {RangedFilter}\n * @private\n */\n private readonly rangedFilter_: RangedFilter;\n\n /**\n * @const\n * @type {!Index}\n * @private\n */\n private readonly index_: Index;\n\n /**\n * @const\n * @type {number}\n * @private\n */\n private readonly limit_: number;\n\n /**\n * @const\n * @type {boolean}\n * @private\n */\n private readonly reverse_: boolean;\n\n /**\n * @param {!QueryParams} params\n */\n constructor(params: QueryParams) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n\n /**\n * @inheritDoc\n */\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_\n .getIndexedFilter()\n .updateChild(\n snap,\n key,\n newChild,\n affectedPath,\n source,\n optChangeAccumulator\n );\n } else {\n return this.fullLimitUpdateChild_(\n snap,\n key,\n newChild,\n source,\n optChangeAccumulator\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n let 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.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (\n this.limit_ * 2 < newSnap.numChildren() &&\n newSnap.isIndexed(this.index_)\n ) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n // anchor to the startPost, endPost, or last element as appropriate\n let iterator;\n if (this.reverse_) {\n iterator = (newSnap as ChildrenNode).getReverseIteratorFrom(\n this.rangedFilter_.getEndPost(),\n this.index_\n );\n } else {\n iterator = (newSnap as ChildrenNode).getIteratorFrom(\n this.rangedFilter_.getStartPost(),\n this.index_\n );\n }\n let count = 0;\n while (iterator.hasNext() && count < this.limit_) {\n const next = iterator.getNext();\n let inRange;\n if (this.reverse_) {\n inRange =\n this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\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 } else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\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(\n ChildrenNode.EMPTY_NODE\n ) as ChildrenNode;\n let startPost;\n let endPost;\n let cmp;\n let iterator;\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n const indexCompare = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCompare(b, a);\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\n let count = 0;\n let foundStartPost = false;\n while (iterator.hasNext()) {\n let next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n let inRange =\n foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(\n next.name,\n ChildrenNode.EMPTY_NODE\n );\n }\n }\n }\n }\n return this.rangedFilter_\n .getIndexedFilter()\n .updateFullNode(oldSnap, filtered, optChangeAccumulator);\n }\n\n /**\n * @inheritDoc\n */\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n // Don't support priorities on queries\n return oldSnap;\n }\n\n /**\n * @inheritDoc\n */\n filtersNodes(): boolean {\n return true;\n }\n\n /**\n * @inheritDoc\n */\n getIndexedFilter(): IndexedFilter {\n return this.rangedFilter_.getIndexedFilter();\n }\n\n /**\n * @inheritDoc\n */\n getIndex(): Index {\n return this.index_;\n }\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 private fullLimitUpdateChild_(\n snap: Node,\n childKey: string,\n childSnap: Node,\n source: CompleteChildSource,\n changeAccumulator: ChildChangeAccumulator | null\n ): Node {\n // TODO: rename all cache stuff etc to general snap terminology\n let cmp;\n if (this.reverse_) {\n const indexCmp = this.index_.getCompare();\n cmp = (a: NamedNode, b: NamedNode) => indexCmp(b, a);\n } else {\n cmp = this.index_.getCompare();\n }\n const oldEventCache = snap as ChildrenNode;\n assert(oldEventCache.numChildren() == this.limit_, '');\n const newChildNamedNode = new NamedNode(childKey, childSnap);\n const windowBoundary = this.reverse_\n ? oldEventCache.getFirstChild(this.index_)\n : oldEventCache.getLastChild(this.index_) as NamedNode;\n const inRange = this.rangedFilter_.matches(newChildNamedNode);\n if (oldEventCache.hasChild(childKey)) {\n const oldChildSnap = oldEventCache.getImmediateChild(childKey);\n let nextChild = source.getChildAfterChild(\n this.index_,\n windowBoundary,\n this.reverse_\n );\n while (\n nextChild != null &&\n (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))\n ) {\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(\n this.index_,\n nextChild,\n this.reverse_\n );\n }\n const compareNext =\n nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n const remainsInWindow =\n inRange && !childSnap.isEmpty() && compareNext >= 0;\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n Change.childChangedChange(childKey, childSnap, oldChildSnap)\n );\n }\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n Change.childRemovedChange(childKey, oldChildSnap)\n );\n }\n const newEventCache = oldEventCache.updateImmediateChild(\n childKey,\n ChildrenNode.EMPTY_NODE\n );\n const nextChildInRange =\n nextChild != null && this.rangedFilter_.matches(nextChild);\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n Change.childAddedChange(nextChild.name, nextChild.node)\n );\n }\n return newEventCache.updateImmediateChild(\n nextChild.name,\n nextChild.node\n );\n } else {\n return newEventCache;\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 } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(\n Change.childRemovedChange(windowBoundary.name, windowBoundary.node)\n );\n changeAccumulator.trackChildChange(\n Change.childAddedChange(childKey, childSnap)\n );\n }\n return oldEventCache\n .updateImmediateChild(childKey, childSnap)\n .updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/filter/LimitedFilter.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { MIN_NAME, MAX_NAME } from '../util/util';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../snap/indexes/ValueIndex';\nimport { PathIndex } from '../snap/indexes/PathIndex';\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { LimitedFilter } from './filter/LimitedFilter';\nimport { RangedFilter } from './filter/RangedFilter';\nimport { stringify } from '../../../utils/json';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { Index } from '../snap/indexes/Index';\n\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 */\nexport class QueryParams {\n private limitSet_ = false;\n private startSet_ = false;\n private startNameSet_ = false;\n private endSet_ = false;\n private endNameSet_ = false;\n\n private limit_ = 0;\n private viewFrom_ = '';\n private indexStartValue_: any | null = null;\n private indexStartName_ = '';\n private indexEndValue_: any | null = null;\n private indexEndName_ = '';\n\n private index_ = PRIORITY_INDEX;\n\n /**\n * Wire Protocol Constants\n * @const\n * @enum {string}\n * @private\n */\n private static readonly 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 /**\n * REST Query Constants\n * @const\n * @enum {string}\n * @private\n */\n private static readonly 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 /**\n * Default, empty query parameters\n * @type {!QueryParams}\n * @const\n */\n static readonly DEFAULT = new QueryParams();\n\n /**\n * @return {boolean}\n */\n hasStart(): boolean {\n return this.startSet_;\n }\n\n /**\n * @return {boolean} True if it would return from left.\n */\n isViewFromLeft(): boolean {\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 } else {\n return (\n this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT\n );\n }\n }\n\n /**\n * Only valid to call if hasStart() returns true\n * @return {*}\n */\n getIndexStartValue(): any {\n assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n }\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 getIndexStartName(): string {\n assert(this.startSet_, 'Only valid if start has been set');\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n }\n\n /**\n * @return {boolean}\n */\n hasEnd(): boolean {\n return this.endSet_;\n }\n\n /**\n * Only valid to call if hasEnd() returns true.\n * @return {*}\n */\n getIndexEndValue(): any {\n assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n }\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 getIndexEndName(): string {\n assert(this.endSet_, 'Only valid if end has been set');\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n }\n\n /**\n * @return {boolean}\n */\n hasLimit(): boolean {\n return this.limitSet_;\n }\n\n /**\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\n */\n hasAnchoredLimit(): boolean {\n return this.limitSet_ && this.viewFrom_ !== '';\n }\n\n /**\n * Only valid to call if hasLimit() returns true\n * @return {!number}\n */\n getLimit(): number {\n assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n }\n\n /**\n * @return {!Index}\n */\n getIndex(): Index {\n return this.index_;\n }\n\n /**\n * @return {!QueryParams}\n * @private\n */\n private copy_(): QueryParams {\n const 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 /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n limit(newLimit: number): QueryParams {\n const newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n }\n\n /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n limitToFirst(newLimit: number): QueryParams {\n const 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 /**\n * @param {!number} newLimit\n * @return {!QueryParams}\n */\n limitToLast(newLimit: number): QueryParams {\n const 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 /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n startAt(indexValue: any, key?: string | null): QueryParams {\n const 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 } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n return newParams;\n }\n\n /**\n * @param {*} indexValue\n * @param {?string=} key\n * @return {!QueryParams}\n */\n endAt(indexValue: any, key?: string | null): QueryParams {\n const 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 } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n return newParams;\n }\n\n /**\n * @param {!Index} index\n * @return {!QueryParams}\n */\n orderBy(index: Index): QueryParams {\n const newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n }\n\n /**\n * @return {!Object}\n */\n getQueryObject(): Object {\n const WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n const obj: { [k: string]: any } = {};\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 let viewFrom = this.viewFrom_;\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\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_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n return obj;\n }\n\n /**\n * @return {boolean}\n */\n loadsAllData(): boolean {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n }\n\n /**\n * @return {boolean}\n */\n isDefault(): boolean {\n return this.loadsAllData() && this.index_ == PRIORITY_INDEX;\n }\n\n /**\n * @return {!NodeFilter}\n */\n getNodeFilter(): NodeFilter {\n if (this.loadsAllData()) {\n return new IndexedFilter(this.getIndex());\n } else if (this.hasLimit()) {\n return new LimitedFilter(this);\n } else {\n return new RangedFilter(this);\n }\n }\n\n /**\n * Returns a set of REST query string parameters representing this query.\n *\n * @return {!Object.} query string parameters\n */\n toRestQueryStringParameters(): { [k: string]: any } {\n const REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n const qs: { [k: string]: string | number } = {};\n\n if (this.isDefault()) {\n return qs;\n }\n\n let orderBy;\n if (this.index_ === PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n } else if (this.index_ === VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n } else if (this.index_ === KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n } else {\n assert(this.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n qs[REST_CONSTANTS.ORDER_BY] = stringify(orderBy);\n\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = stringify(this.indexStartValue_);\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + stringify(this.indexStartName_);\n }\n }\n\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = stringify(this.indexEndValue_);\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + stringify(this.indexEndName_);\n }\n }\n\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n } else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n\n return qs;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/QueryParams.ts","/**\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\nimport { OnDisconnect } from './onDisconnect';\nimport { TransactionResult } from './TransactionResult';\nimport { warn } from '../core/util/util';\nimport { nextPushId } from '../core/util/NextPushId';\nimport { Query } from './Query';\nimport { Repo } from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport { QueryParams } from '../core/view/QueryParams';\nimport {\n validateRootPathString,\n validatePathString,\n validateFirebaseMergeDataArg,\n validateBoolean,\n validatePriority,\n validateFirebaseDataArg,\n validateWritablePath\n} from '../core/util/validation';\nimport { validateArgCount, validateCallback } from '../../utils/validation';\nimport {\n Deferred,\n attachDummyErrorHandler,\n PromiseImpl\n} from '../../utils/promise';\nimport { SyncPoint } from '../core/SyncPoint';\nimport { Database } from './Database';\nimport { DataSnapshot } from './DataSnapshot';\n\nexport interface ReferenceConstructor {\n new (repo: Repo, path: Path): Reference;\n}\n\nexport class Reference extends Query {\n public then: (a?: any) => Promise;\n public catch: (a?: Error) => Promise;\n\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 constructor(repo: Repo, path: Path) {\n if (!(repo instanceof Repo)) {\n throw new Error(\n 'new Reference() no longer supported - use app.database().'\n );\n }\n\n // call Query's constructor, passing in the repo and path.\n super(repo, path, QueryParams.DEFAULT, false);\n }\n\n /** @return {?string} */\n getKey(): string | null {\n validateArgCount('Reference.key', 0, 0, arguments.length);\n\n if (this.path.isEmpty()) return null;\n else return this.path.getBack();\n }\n\n /**\n * @param {!(string|Path)} pathString\n * @return {!Reference}\n */\n child(pathString: string | Path): Reference {\n validateArgCount('Reference.child', 1, 1, arguments.length);\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n } else if (!(pathString instanceof Path)) {\n if (this.path.getFront() === null)\n validateRootPathString('Reference.child', 1, pathString, false);\n else validatePathString('Reference.child', 1, pathString, false);\n }\n\n return new Reference(this.repo, this.path.child(pathString));\n }\n\n /** @return {?Reference} */\n getParent(): Reference | null {\n validateArgCount('Reference.parent', 0, 0, arguments.length);\n\n const parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n }\n\n /** @return {!Reference} */\n getRoot(): Reference {\n validateArgCount('Reference.root', 0, 0, arguments.length);\n\n let ref = this as any;\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n return ref;\n }\n\n /** @return {!Database} */\n databaseProp(): Database {\n return this.repo.database;\n }\n\n /**\n * @param {*} newVal\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n set(newVal: any, onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('Reference.set', 1, 2, arguments.length);\n validateWritablePath('Reference.set', this.path);\n validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n validateCallback('Reference.set', 2, onComplete, true);\n\n const deferred = new Deferred();\n this.repo.setWithPriority(\n this.path,\n newVal,\n /*priority=*/ null,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {!Object} objectToMerge\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n update(\n objectToMerge: Object,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.update', 1, 2, arguments.length);\n validateWritablePath('Reference.update', this.path);\n\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: any } = {};\n for (let i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n objectToMerge = newObjectToMerge;\n warn(\n '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 }\n validateFirebaseMergeDataArg(\n 'Reference.update',\n 1,\n objectToMerge,\n this.path,\n false\n );\n validateCallback('Reference.update', 2, onComplete, true);\n const deferred = new Deferred();\n this.repo.update(\n this.path,\n objectToMerge,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {*} newVal\n * @param {string|number|null} newPriority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n setWithPriority(\n newVal: any,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateWritablePath('Reference.setWithPriority', this.path);\n validateFirebaseDataArg(\n 'Reference.setWithPriority',\n 1,\n newVal,\n this.path,\n false\n );\n validatePriority('Reference.setWithPriority', 2, newPriority, false);\n validateCallback('Reference.setWithPriority', 3, onComplete, true);\n\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.setWithPriority failed: ' +\n this.getKey() +\n ' is a read-only object.';\n\n const deferred = new Deferred();\n this.repo.setWithPriority(\n this.path,\n newVal,\n newPriority,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n remove(onComplete?: (a: Error | null) => void): Promise {\n validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateWritablePath('Reference.remove', this.path);\n validateCallback('Reference.remove', 1, onComplete, true);\n\n return this.set(null, onComplete);\n }\n\n /**\n * @param {function(*):*} transactionUpdate\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\n * @param {boolean=} applyLocally\n * @return {!Promise}\n */\n transaction(\n transactionUpdate: (a: any) => any,\n onComplete?: (a: Error | null, b: boolean, c: DataSnapshot | null) => void,\n applyLocally?: boolean\n ): Promise {\n validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateWritablePath('Reference.transaction', this.path);\n validateCallback('Reference.transaction', 1, transactionUpdate, false);\n 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 validateBoolean('Reference.transaction', 3, applyLocally, true);\n\n if (this.getKey() === '.length' || this.getKey() === '.keys')\n throw 'Reference.transaction failed: ' +\n this.getKey() +\n ' is a read-only object.';\n\n if (applyLocally === undefined) applyLocally = true;\n\n const deferred = new Deferred();\n if (typeof onComplete === 'function') {\n attachDummyErrorHandler(deferred.promise);\n }\n\n const promiseComplete = function(\n error: Error,\n committed: boolean,\n snapshot: DataSnapshot\n ) {\n if (error) {\n deferred.reject(error);\n } else {\n deferred.resolve(new TransactionResult(committed, snapshot));\n }\n if (typeof onComplete === 'function') {\n onComplete(error, committed, snapshot);\n }\n };\n this.repo.startTransaction(\n this.path,\n transactionUpdate,\n promiseComplete,\n applyLocally\n );\n\n return deferred.promise;\n }\n\n /**\n * @param {string|number|null} priority\n * @param {function(?Error)=} onComplete\n * @return {!Promise}\n */\n setPriority(\n priority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise {\n validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateWritablePath('Reference.setPriority', this.path);\n validatePriority('Reference.setPriority', 1, priority, false);\n validateCallback('Reference.setPriority', 2, onComplete, true);\n\n const deferred = new Deferred();\n this.repo.setWithPriority(\n this.path.child('.priority'),\n priority,\n null,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n\n /**\n * @param {*=} value\n * @param {function(?Error)=} onComplete\n * @return {!Reference}\n */\n push(value?: any, onComplete?: (a: Error | null) => void): Reference {\n validateArgCount('Reference.push', 0, 2, arguments.length);\n validateWritablePath('Reference.push', this.path);\n validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n validateCallback('Reference.push', 2, onComplete, true);\n\n const now = this.repo.serverTime();\n const name = nextPushId(now);\n\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 const thennablePushRef = this.child(name);\n const pushRef = this.child(name);\n\n let promise;\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(() => pushRef);\n } else {\n promise = PromiseImpl.resolve(pushRef);\n }\n\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n\n if (typeof onComplete === 'function') {\n attachDummyErrorHandler(promise);\n }\n\n return thennablePushRef;\n }\n\n /**\n * @return {!OnDisconnect}\n */\n onDisconnect(): OnDisconnect {\n validateWritablePath('Reference.onDisconnect', this.path);\n return new OnDisconnect(this.repo, this.path);\n }\n\n get database(): Database {\n return this.databaseProp();\n }\n\n get key(): string | null {\n return this.getKey();\n }\n\n get parent(): Reference | null {\n return this.getParent();\n }\n\n get root(): Reference {\n return this.getRoot();\n }\n}\n\n/**\n * Define reference constructor in various modules\n *\n * We are doing this here to avoid several circular\n * dependency issues\n */\nQuery.__referenceConstructor = Reference;\nSyncPoint.__referenceConstructor = Reference;\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/Reference.ts","/**\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\nimport { SortedMap } from './SortedMap';\nimport { Path } from './Path';\nimport { stringCompare } from './util';\nimport { forEach } from '../../../utils/obj';\n\nlet emptyChildrenSingleton: SortedMap>;\n\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.>}\n */\nconst EmptyChildren = (): SortedMap> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree {\n static Empty = new ImmutableTree(null);\n\n /**\n * @template T\n * @param {!Object.} obj\n * @return {!ImmutableTree.}\n */\n static fromObject(obj: { [k: string]: T }): ImmutableTree {\n let tree: ImmutableTree = ImmutableTree.Empty;\n forEach(obj, (childPath: string, childSnap: T) => {\n tree = tree.set(new Path(childPath), childSnap);\n });\n return tree;\n }\n\n /**\n * @template T\n * @param {?T} value\n * @param {SortedMap.>=} children\n */\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree\n > = EmptyChildren()\n ) {}\n\n /**\n * True if the value is empty and there are no children\n * @return {boolean}\n */\n isEmpty(): boolean {\n return this.value === null && this.children.isEmpty();\n }\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 findRootMostMatchingPathAndValue(\n relativePath: Path,\n predicate: (a: T) => boolean\n ): { path: Path; value: T } | null {\n if (this.value != null && predicate(this.value)) {\n return { path: Path.Empty, value: this.value };\n } else {\n if (relativePath.isEmpty()) {\n return null;\n } else {\n const front = relativePath.getFront();\n const child = this.children.get(front);\n if (child !== null) {\n const childExistingPathAndValue = child.findRootMostMatchingPathAndValue(\n relativePath.popFront(),\n predicate\n );\n if (childExistingPathAndValue != null) {\n const fullPath = new Path(front).child(\n childExistingPathAndValue.path\n );\n return { path: fullPath, value: childExistingPathAndValue.value };\n } else {\n return null;\n }\n } else {\n return null;\n }\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 findRootMostValueAndPath(\n relativePath: Path\n ): { path: Path; value: T } | null {\n return this.findRootMostMatchingPathAndValue(relativePath, () => true);\n }\n\n /**\n * @param {!Path} relativePath\n * @return {!ImmutableTree.} The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree {\n if (relativePath.isEmpty()) {\n return this;\n } else {\n const front = relativePath.getFront();\n const childTree = this.children.get(front);\n if (childTree !== null) {\n return childTree.subtree(relativePath.popFront());\n } else {\n return ImmutableTree.Empty;\n }\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 set(relativePath: Path, toSet: T | null): ImmutableTree {\n if (relativePath.isEmpty()) {\n return new ImmutableTree(toSet, this.children);\n } else {\n const front = relativePath.getFront();\n const child = this.children.get(front) || ImmutableTree.Empty;\n const newChild = child.set(relativePath.popFront(), toSet);\n const newChildren = this.children.insert(front, newChild);\n return new ImmutableTree(this.value, newChildren);\n }\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 remove(relativePath: Path): ImmutableTree {\n if (relativePath.isEmpty()) {\n if (this.children.isEmpty()) {\n return ImmutableTree.Empty;\n } else {\n return new ImmutableTree(null, this.children);\n }\n } else {\n const front = relativePath.getFront();\n const child = this.children.get(front);\n if (child) {\n const newChild = child.remove(relativePath.popFront());\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n if (this.value === null && newChildren.isEmpty()) {\n return ImmutableTree.Empty;\n } else {\n return new ImmutableTree(this.value, newChildren);\n }\n } else {\n return this;\n }\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 get(relativePath: Path): T | null {\n if (relativePath.isEmpty()) {\n return this.value;\n } else {\n const front = relativePath.getFront();\n const child = this.children.get(front);\n if (child) {\n return child.get(relativePath.popFront());\n } else {\n return null;\n }\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 setTree(relativePath: Path, newTree: ImmutableTree): ImmutableTree {\n if (relativePath.isEmpty()) {\n return newTree;\n } else {\n const front = relativePath.getFront();\n const child = this.children.get(front) || ImmutableTree.Empty;\n const newChild = child.setTree(relativePath.popFront(), newTree);\n let newChildren;\n if (newChild.isEmpty()) {\n newChildren = this.children.remove(front);\n } else {\n newChildren = this.children.insert(front, newChild);\n }\n return new ImmutableTree(this.value, newChildren);\n }\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 fold(fn: (path: Path, value: T, children: { [k: string]: V }) => V): V {\n return this.fold_(Path.Empty, fn);\n }\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 private fold_(\n pathSoFar: Path,\n fn: (path: Path, value: T | null, children: { [k: string]: V }) => V\n ): V {\n const accum: { [k: string]: V } = {};\n this.children.inorderTraversal(function(\n childKey: string,\n childTree: ImmutableTree\n ) {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n });\n return fn(pathSoFar, this.value, accum);\n }\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 findOnPath(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, Path.Empty, f);\n }\n\n private findOnPath_(\n pathToFollow: Path,\n pathSoFar: Path,\n f: (path: Path, value: T) => V | null\n ): V | null {\n const result = this.value ? f(pathSoFar, this.value) : false;\n if (result) {\n return result;\n } else {\n if (pathToFollow.isEmpty()) {\n return null;\n } else {\n const front = pathToFollow.getFront()!;\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.findOnPath_(\n pathToFollow.popFront(),\n pathSoFar.child(front),\n f\n );\n } else {\n return null;\n }\n }\n }\n }\n\n /**\n *\n * @param {!Path} path\n * @param {!function(!Path, !T)} f\n * @returns {!ImmutableTree.}\n */\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n return this.foreachOnPath_(path, Path.Empty, f);\n }\n\n private foreachOnPath_(\n pathToFollow: Path,\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree {\n if (pathToFollow.isEmpty()) {\n return this;\n } else {\n if (this.value) {\n f(currentRelativePath, this.value);\n }\n const front = pathToFollow.getFront();\n const nextChild = this.children.get(front);\n if (nextChild) {\n return nextChild.foreachOnPath_(\n pathToFollow.popFront(),\n currentRelativePath.child(front),\n f\n );\n } else {\n return ImmutableTree.Empty;\n }\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 foreach(f: (path: Path, value: T) => void) {\n this.foreach_(Path.Empty, f);\n }\n\n private foreach_(\n currentRelativePath: Path,\n f: (path: Path, value: T) => void\n ) {\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 *\n * @param {function(string, !T)} f\n */\n foreachChild(f: (name: string, value: T) => void) {\n this.children.inorderTraversal(\n (childName: string, childTree: ImmutableTree) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/ImmutableTree.ts","/**\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\nimport { assert } from '../../../../utils/assert';\nimport { Change } from '../Change';\nimport { ChildrenNode } from '../../snap/ChildrenNode';\nimport { PRIORITY_INDEX } from '../../snap/indexes/PriorityIndex';\nimport { NodeFilter } from './NodeFilter';\nimport { Index } from '../../snap/indexes/Index';\nimport { Path } from '../../util/Path';\nimport { CompleteChildSource } from '../CompleteChildSource';\nimport { ChildChangeAccumulator } from '../ChildChangeAccumulator';\nimport { Node } from '../../snap/Node';\n\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 */\nexport class IndexedFilter implements NodeFilter {\n constructor(private readonly index_: Index) {}\n\n updateChild(\n snap: Node,\n key: string,\n newChild: Node,\n affectedPath: Path,\n source: CompleteChildSource,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n assert(\n snap.isIndexed(this.index_),\n 'A node must be indexed if only a child is updated'\n );\n const oldChild = snap.getImmediateChild(key);\n // Check if anything actually changed.\n if (\n oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))\n ) {\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\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\n if (optChangeAccumulator != null) {\n if (newChild.isEmpty()) {\n if (snap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n Change.childRemovedChange(key, oldChild)\n );\n } else {\n assert(\n snap.isLeafNode(),\n 'A child remove without an old child only makes sense on a leaf node'\n );\n }\n } else if (oldChild.isEmpty()) {\n optChangeAccumulator.trackChildChange(\n Change.childAddedChange(key, newChild)\n );\n } else {\n optChangeAccumulator.trackChildChange(\n Change.childChangedChange(key, newChild, oldChild)\n );\n }\n }\n if (snap.isLeafNode() && newChild.isEmpty()) {\n return snap;\n } else {\n // Make sure the node is indexed\n return snap.updateImmediateChild(key, newChild).withIndex(this.index_);\n }\n }\n\n /**\n * @inheritDoc\n */\n updateFullNode(\n oldSnap: Node,\n newSnap: Node,\n optChangeAccumulator: ChildChangeAccumulator | null\n ): Node {\n if (optChangeAccumulator != null) {\n if (!oldSnap.isLeafNode()) {\n oldSnap.forEachChild(PRIORITY_INDEX, function(key, childNode) {\n if (!newSnap.hasChild(key)) {\n optChangeAccumulator.trackChildChange(\n Change.childRemovedChange(key, childNode)\n );\n }\n });\n }\n if (!newSnap.isLeafNode()) {\n newSnap.forEachChild(PRIORITY_INDEX, function(key, childNode) {\n if (oldSnap.hasChild(key)) {\n const oldChild = oldSnap.getImmediateChild(key);\n if (!oldChild.equals(childNode)) {\n optChangeAccumulator.trackChildChange(\n Change.childChangedChange(key, childNode, oldChild)\n );\n }\n } else {\n optChangeAccumulator.trackChildChange(\n Change.childAddedChange(key, childNode)\n );\n }\n });\n }\n }\n return newSnap.withIndex(this.index_);\n }\n\n /**\n * @inheritDoc\n */\n updatePriority(oldSnap: Node, newPriority: Node): Node {\n if (oldSnap.isEmpty()) {\n return ChildrenNode.EMPTY_NODE;\n } else {\n return oldSnap.updatePriority(newPriority);\n }\n }\n\n /**\n * @inheritDoc\n */\n filtersNodes(): boolean {\n return false;\n }\n\n /**\n * @inheritDoc\n */\n getIndexedFilter(): IndexedFilter {\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getIndex(): Index {\n return this.index_;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/filter/IndexedFilter.ts","/**\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\nimport { deepCopy } from '../../../utils/deep_copy';\nimport { contains } from '../../../utils/obj';\n\n/**\n * Tracks a collection of stats.\n *\n * @constructor\n */\nexport class StatsCollection {\n private counters_: { [k: string]: number } = {};\n\n incrementCounter(name: string, amount: number = 1) {\n if (!contains(this.counters_, name)) this.counters_[name] = 0;\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/stats/StatsCollection.ts","/**\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\nimport { StatsCollection } from './StatsCollection';\nimport { RepoInfo } from '../RepoInfo';\n\nexport class StatsManager {\n private static collections_: { [k: string]: StatsCollection } = {};\n private static reporters_: { [k: string]: any } = {};\n\n static getCollection(repoInfo: RepoInfo): StatsCollection {\n const hashString = repoInfo.toString();\n\n if (!this.collections_[hashString]) {\n this.collections_[hashString] = new StatsCollection();\n }\n\n return this.collections_[hashString];\n }\n\n static getOrCreateReporter(\n repoInfo: RepoInfo,\n creatorFunction: () => T\n ): T {\n const hashString = repoInfo.toString();\n\n if (!this.reporters_[hashString]) {\n this.reporters_[hashString] = creatorFunction();\n }\n\n return this.reporters_[hashString];\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/stats/StatsManager.ts","/**\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\nimport { assert } from '../../utils/assert';\nimport { Reference } from '../api/Reference';\nimport { DataSnapshot } from '../api/DataSnapshot';\nimport { Path } from './util/Path';\nimport { Tree } from './util/Tree';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { Node } from './snap/Node';\nimport { LUIDGenerator, warn, exceptionGuard } from './util/util';\nimport { resolveDeferredValueSnapshot } from './util/ServerValues';\nimport { isValidPriority, validateFirebaseData } from './util/validation';\nimport { contains, safeGet } from '../../utils/obj';\nimport { nodeFromJSON } from './snap/nodeFromJSON';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { Repo } from './Repo';\nimport { Event } from './view/Event';\n\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/**\n * @enum {number}\n */\nexport enum 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 RUN,\n\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 SENT,\n\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 COMPLETED,\n\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 SENT_NEEDS_ABORT,\n\n // Temporary state used to mark transactions that need to be aborted.\n NEEDS_ABORT\n}\n\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 */\n(Repo as any).MAX_TRANSACTION_RETRIES_ = 25;\n\n/**\n * @typedef {{\n * path: !Path,\n * update: function(*):*,\n * onComplete: ?function(?Error, boolean, ?DataSnapshot),\n * status: ?TransactionStatus,\n * order: !number,\n * applyLocally: boolean,\n * retryCount: !number,\n * unwatcher: function(),\n * abortReason: ?string,\n * currentWriteId: !number,\n * currentInputSnapshot: ?Node,\n * currentOutputSnapshotRaw: ?Node,\n * currentOutputSnapshotResolved: ?Node\n * }}\n */\ntype Transaction = {\n path: Path;\n update: (a: any) => any;\n onComplete: (a: Error | null, b: boolean, c: DataSnapshot | null) => void;\n status: TransactionStatus;\n order: number;\n applyLocally: boolean;\n retryCount: number;\n unwatcher: () => void;\n abortReason: string | null;\n currentWriteId: number;\n currentInputSnapshot: Node | null;\n currentOutputSnapshotRaw: Node | null;\n currentOutputSnapshotResolved: Node | null;\n};\n\n/**\n * Setup the transaction data structures\n * @private\n */\n(Repo.prototype as any).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();\n};\n\ndeclare module './Repo' {\n interface Repo {\n startTransaction(\n path: Path,\n transactionUpdate: (a: any) => void,\n onComplete: ((a: Error, b: boolean, c: DataSnapshot) => void) | null,\n applyLocally: boolean\n ): void;\n }\n}\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.prototype.startTransaction = function(\n path: Path,\n transactionUpdate: (a: any) => any,\n onComplete: ((a: Error, b: boolean, c: DataSnapshot) => void) | null,\n applyLocally: boolean\n) {\n this.log_('transaction on ' + path);\n\n // Add a watch to make sure we get server updates.\n const valueCallback = function() {};\n const watchRef = new Reference(this, path);\n watchRef.on('value', valueCallback);\n const unwatcher = function() {\n watchRef.off('value', valueCallback);\n };\n\n // Initialize transaction.\n const transaction: Transaction = {\n path,\n update: transactionUpdate,\n onComplete,\n\n // One of TransactionStatus enums.\n status: null,\n\n // Used when combining transactions at different locations to figure out which one goes first.\n order: LUIDGenerator(),\n\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n\n // Function to call to clean up our .on() listener.\n unwatcher,\n\n // Stores why a transaction was aborted.\n abortReason: null,\n\n currentWriteId: null,\n\n currentInputSnapshot: null,\n\n currentOutputSnapshotRaw: null,\n\n currentOutputSnapshotResolved: null\n };\n\n // Run transaction initially.\n const currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n const 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 const snapshot = new DataSnapshot(\n transaction.currentInputSnapshot,\n new Reference(this, transaction.path),\n PRIORITY_INDEX\n );\n transaction.onComplete(null, false, snapshot);\n }\n } else {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newVal,\n transaction.path\n );\n\n // Mark as run and add to our queue.\n transaction.status = TransactionStatus.RUN;\n const queueNode = this.transactionQueueTree_.subTree(path);\n const nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n\n queueNode.setValue(nodeQueue);\n\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 let priorityForNode;\n if (\n typeof newVal === 'object' &&\n newVal !== null &&\n contains(newVal, '.priority')\n ) {\n priorityForNode = safeGet(newVal, '.priority');\n assert(\n isValidPriority(priorityForNode),\n 'Invalid priority returned by transaction. ' +\n 'Priority must be a valid string, finite number, server value, or null.'\n );\n } else {\n const currentNode =\n this.serverSyncTree_.calcCompleteEventCache(path) ||\n ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n priorityForNode /** @type {null|number|string} */ = priorityForNode;\n\n const serverValues = this.generateServerValues();\n const newNodeUnresolved = nodeFromJSON(newVal, priorityForNode);\n const newNode = resolveDeferredValueSnapshot(\n newNodeUnresolved,\n serverValues\n );\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n\n const events = this.serverSyncTree_.applyUserOverwrite(\n path,\n newNode,\n transaction.currentWriteId,\n transaction.applyLocally\n );\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n\n this.sendReadyTransactions_();\n }\n};\n\n/**\n * @param {!Path} path\n * @param {Array.=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\n(Repo.prototype as any).getLatestState_ = function(\n path: Path,\n excludeSets?: number[]\n): Node {\n return (\n this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) ||\n ChildrenNode.EMPTY_NODE\n );\n};\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 */\n(Repo.prototype as any).sendReadyTransactions_ = function(\n node: Tree = this.transactionQueueTree_\n) {\n // Before recursing, make sure any completed transactions are removed.\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n\n if (node.getValue() !== null) {\n const queue = this.buildTransactionQueue_(node);\n assert(queue.length > 0, 'Sending zero length transaction queue');\n\n const allRun = queue.every(\n (transaction: Transaction) => transaction.status === TransactionStatus.RUN\n );\n\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 } else if (node.hasChildren()) {\n node.forEachChild(childNode => {\n this.sendReadyTransactions_(childNode);\n });\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 */\n(Repo.prototype as any).sendTransactionQueue_ = function(\n path: Path,\n queue: Array\n) {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(function(txn) {\n return txn.currentWriteId;\n });\n const latestState = this.getLatestState_(path, setsToIgnore);\n let snapToSend = latestState;\n const latestHash = latestState.hash();\n for (let i = 0; i < queue.length; i++) {\n const txn = queue[i];\n assert(\n txn.status === TransactionStatus.RUN,\n 'tryToSendTransactionQueue_: items in queue should all be run.'\n );\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n const relativePath = Path.relativePath(path, txn.path);\n // If we've gotten to this point, the output snapshot must be defined.\n snapToSend = snapToSend.updateChild(\n relativePath /**@type {!Node} */,\n txn.currentOutputSnapshotRaw\n );\n }\n\n const dataToSend = snapToSend.val(true);\n const pathToSend = path;\n\n // Send the put.\n this.server_.put(\n pathToSend.toString(),\n dataToSend,\n (status: string) => {\n this.log_('transaction put response', {\n path: pathToSend.toString(),\n status\n });\n\n let events: Event[] = [];\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 const callbacks = [];\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(\n this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId)\n );\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n const node = queue[i].currentOutputSnapshotResolved as Node;\n const ref = new Reference(this, queue[i].path);\n const snapshot = new DataSnapshot(node, ref, PRIORITY_INDEX);\n callbacks.push(\n queue[i].onComplete.bind(null, null, true, snapshot)\n );\n }\n queue[i].unwatcher();\n }\n\n // Now remove the completed transactions.\n this.pruneCompletedTransactionsBelowNode_(\n this.transactionQueueTree_.subTree(path)\n );\n // There may be pending transactions that we can now send.\n this.sendReadyTransactions_();\n\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n\n // Finally, trigger onComplete callbacks.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT)\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n else queue[i].status = TransactionStatus.RUN;\n }\n } else {\n warn(\n 'transaction at ' + pathToSend.toString() + ' failed: ' + status\n );\n for (let i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n this.rerunTransactions_(path);\n }\n },\n latestHash\n );\n};\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 */\n(Repo.prototype as any).rerunTransactions_ = function(changedPath: Path): Path {\n const rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n const path = rootMostTransactionNode.path();\n\n const queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n\n return path;\n};\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 */\n(Repo.prototype as any).rerunTransactionQueue_ = function(\n queue: Array,\n path: Path\n) {\n if (queue.length === 0) {\n return; // Nothing to do!\n }\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 const callbacks = [];\n let events: Event[] = [];\n // Ignore all of the sets we're going to re-run.\n const txnsToRerun = queue.filter(function(q) {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(function(q) {\n return q.currentWriteId;\n });\n for (let i = 0; i < queue.length; i++) {\n const transaction = queue[i];\n const relativePath = Path.relativePath(path, transaction.path);\n let abortTransaction = false,\n abortReason;\n assert(\n relativePath !== null,\n 'rerunTransactionsUnderNode_: relativePath should not be null.'\n );\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(\n this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)\n );\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= (Repo as any).MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(\n this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)\n );\n } else {\n // This code reruns a transaction\n const currentNode = this.getLatestState_(\n transaction.path,\n setsToIgnore\n );\n transaction.currentInputSnapshot = currentNode;\n const newData = queue[i].update(currentNode.val());\n if (newData !== undefined) {\n validateFirebaseData(\n 'transaction failed: Data returned ',\n newData,\n transaction.path\n );\n let newDataNode = nodeFromJSON(newData);\n const hasExplicitPriority =\n typeof newData === 'object' &&\n newData != null &&\n 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\n const oldWriteId = transaction.currentWriteId;\n const serverValues = this.generateServerValues();\n const newNodeResolved = resolveDeferredValueSnapshot(\n newDataNode,\n serverValues\n );\n\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(\n this.serverSyncTree_.applyUserOverwrite(\n transaction.path,\n newNodeResolved,\n transaction.currentWriteId,\n transaction.applyLocally\n )\n );\n events = events.concat(\n this.serverSyncTree_.ackUserWrite(oldWriteId, true)\n );\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(\n this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true)\n );\n }\n }\n }\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED;\n\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\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n const ref = new Reference(this, queue[i].path);\n // We set this field immediately, so it's safe to cast to an actual snapshot\n const lastInput /** @type {!Node} */ = queue[i].currentInputSnapshot;\n const snapshot = new DataSnapshot(lastInput, ref, PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n } else {\n callbacks.push(\n queue[i].onComplete.bind(null, new Error(abortReason), false, null)\n );\n }\n }\n }\n }\n\n // Clean up completed transactions.\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_);\n\n // Now fire callbacks, now that we're in a good, known state.\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n\n // Try to send the transaction result to the server.\n this.sendReadyTransactions_();\n};\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 */\n(Repo.prototype as any).getAncestorTransactionNode_ = function(\n path: Path\n): Tree {\n let front;\n\n // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n let transactionNode = this.transactionQueueTree_;\n while (\n (front = path.getFront()) !== null &&\n transactionNode.getValue() === null\n ) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n\n return transactionNode;\n};\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 */\n(Repo.prototype as any).buildTransactionQueue_ = function(\n transactionNode: Tree\n): Array {\n // Walk any child transaction queues and aggregate them into a single queue.\n const transactionQueue: Transaction[] = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue);\n\n // Sort them by the order the transactions were created.\n transactionQueue.sort(function(a, b) {\n return a.order - b.order;\n });\n\n return transactionQueue;\n};\n\n/**\n * @param {!Tree.>} node\n * @param {Array.} queue\n * @private\n */\n(Repo.prototype as any).aggregateTransactionQueuesForNode_ = function(\n node: Tree,\n queue: Array\n) {\n const nodeQueue = node.getValue();\n if (nodeQueue !== null) {\n for (let i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n node.forEachChild(child => {\n this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n\n/**\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\n *\n * @param {!Tree.>} node\n * @private\n */\n(Repo.prototype as any).pruneCompletedTransactionsBelowNode_ = function(\n node: Tree\n) {\n const queue = node.getValue();\n if (queue) {\n let to = 0;\n for (let 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\n node.forEachChild(childNode => {\n this.pruneCompletedTransactionsBelowNode_(childNode);\n });\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 */\n(Repo.prototype as any).abortTransactions_ = function(path: Path): Path {\n const affectedPath = this.getAncestorTransactionNode_(path).path();\n\n const transactionNode = this.transactionQueueTree_.subTree(path);\n\n transactionNode.forEachAncestor((node: Tree) => {\n this.abortTransactionsOnNode_(node);\n });\n\n this.abortTransactionsOnNode_(transactionNode);\n\n transactionNode.forEachDescendant((node: Tree) => {\n this.abortTransactionsOnNode_(node);\n });\n\n return affectedPath;\n};\n\n/**\n * Abort transactions stored in this transaction queue node.\n *\n * @param {!Tree.>} node Node to abort transactions for.\n * @private\n */\n(Repo.prototype as any).abortTransactionsOnNode_ = function(\n node: Tree\n) {\n const 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 const callbacks = [];\n\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 let events: Event[] = [];\n let lastSent = -1;\n for (let i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {\n // Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n assert(\n lastSent === i - 1,\n 'All SENT items should be at beginning of queue.'\n );\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 } else {\n assert(\n queue[i].status === TransactionStatus.RUN,\n 'Unexpected transaction status in abort'\n );\n // We can abort it immediately.\n queue[i].unwatcher();\n events = events.concat(\n this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true)\n );\n if (queue[i].onComplete) {\n const snapshot: DataSnapshot | null = null;\n callbacks.push(\n queue[i].onComplete.bind(null, new Error('set'), false, snapshot)\n );\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 } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n }\n\n // Now fire the callbacks.\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n for (let i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/Repo_transaction.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { Path } from './Path';\nimport { forEach, contains, safeGet } from '../../../utils/obj';\n\n/**\n * Node in a Tree.\n */\nexport class TreeNode {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: { [name: string]: TreeNode } = {};\n childCount = 0;\n value: T | null = null;\n}\n\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 */\nexport class Tree {\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 constructor(\n private name_: string = '',\n private parent_: Tree | null = null,\n private node_: TreeNode = new TreeNode()\n ) {}\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 subTree(pathObj: string | Path): Tree {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = this as any,\n next;\n while ((next = path.getFront()) !== null) {\n const childNode = safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n\n return child;\n }\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 getValue(): T | null {\n return this.node_.value;\n }\n\n /**\n * Sets data to this tree node.\n *\n * @param {!T} value Value to set.\n */\n setValue(value: T) {\n assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n }\n\n /**\n * Clears the contents of the tree node (its value and all children).\n */\n clear() {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n }\n\n /**\n * @return {boolean} Whether the tree has any children.\n */\n hasChildren(): boolean {\n return this.node_.childCount > 0;\n }\n\n /**\n * @return {boolean} Whether the tree is empty (no value or children).\n */\n isEmpty(): boolean {\n return this.getValue() === null && !this.hasChildren();\n }\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 forEachChild(action: (tree: Tree) => void) {\n forEach(this.node_.children, (child: string, childTree: TreeNode) => {\n action(new Tree(child, this, childTree));\n });\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 forEachDescendant(\n action: (tree: Tree) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n ) {\n if (includeSelf && !childrenFirst) action(this);\n\n this.forEachChild(function(child) {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) action(this);\n }\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 forEachAncestor(\n action: (tree: Tree) => void,\n includeSelf?: boolean\n ): boolean {\n let 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 /**\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 forEachImmediateDescendantWithValue(action: (tree: Tree) => void) {\n this.forEachChild(function(child) {\n if (child.getValue() !== null) action(child);\n else child.forEachImmediateDescendantWithValue(action);\n });\n }\n\n /**\n * @return {!Path} The path of this tree node, as a Path.\n */\n path(): Path {\n return new Path(\n this.parent_ === null\n ? this.name_\n : this.parent_.path() + '/' + this.name_\n );\n }\n\n /**\n * @return {string} The name of the tree node.\n */\n name(): string {\n return this.name_;\n }\n\n /**\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\n */\n parent(): Tree | null {\n return this.parent_;\n }\n\n /**\n * Adds or removes this child from its parent based on whether it's empty or not.\n *\n * @private\n */\n private updateParents_() {\n if (this.parent_ !== null) this.parent_.updateChild_(this.name_, this);\n }\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 private updateChild_(childName: string, child: Tree) {\n const childEmpty = child.isEmpty();\n const childExists = contains(this.node_.children, childName);\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n } else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/Tree.ts","/**\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\nimport { FirebaseApp } from '../../app/firebase_app';\nimport { safeGet } from '../../utils/obj';\nimport { Repo } from './Repo';\nimport { fatal } from './util/util';\nimport { parseRepoInfo } from './util/libs/parser';\nimport { validateUrl } from './util/validation';\nimport './Repo_transaction';\nimport { Database } from '../api/Database';\nimport { RepoInfo } from './RepoInfo';\n\n/** @const {string} */\nconst DATABASE_URL_OPTION = 'databaseURL';\n\nlet _staticInstance: RepoManager;\n\n/**\n * Creates and caches Repo instances.\n */\nexport class RepoManager {\n /**\n * @private {!Object.>}\n */\n private repos_: {\n [appName: string]: {\n [dbUrl: string]: Repo;\n };\n } = {};\n\n /**\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\n * @private {boolean}\n */\n private useRestClient_: boolean = false;\n\n static getInstance(): RepoManager {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n return _staticInstance;\n }\n\n // TODO(koss): Remove these functions unless used in tests?\n interrupt() {\n for (const appName in this.repos_) {\n for (const dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n }\n\n resume() {\n for (const appName in this.repos_) {\n for (const dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\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 databaseFromApp(app: FirebaseApp, url?: string): Database {\n const dbUrl: string = url || app.options[DATABASE_URL_OPTION];\n if (dbUrl === undefined) {\n fatal(\n \"Can't determine Firebase Database URL. Be sure to include \" +\n DATABASE_URL_OPTION +\n ' option when calling firebase.intializeApp().'\n );\n }\n\n const parsedUrl = parseRepoInfo(dbUrl);\n const repoInfo = parsedUrl.repoInfo;\n\n validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n if (!parsedUrl.path.isEmpty()) {\n fatal(\n 'Database URL must point to the root of a Firebase Database ' +\n '(not including a child path).'\n );\n }\n\n const repo = this.createRepo(repoInfo, app);\n\n return repo.database;\n }\n\n /**\n * Remove the repo and make sure it is disconnected.\n *\n * @param {!Repo} repo\n */\n deleteRepo(repo: Repo) {\n const appRepos = safeGet(this.repos_, repo.app.name);\n // This should never happen...\n if (!appRepos || safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n fatal(\n `Database ${repo.app.name}(${repo.repoInfo_}) has already been deleted.`\n );\n }\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n }\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 createRepo(repoInfo: RepoInfo, app: FirebaseApp): Repo {\n let appRepos = safeGet(this.repos_, app.name);\n\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n\n let repo = safeGet(appRepos, repoInfo.toURLString());\n if (repo) {\n fatal(\n 'Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.'\n );\n }\n repo = new Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n\n return repo;\n }\n\n /**\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\n * @param {boolean} forceRestClient\n */\n forceRestClient(forceRestClient: boolean) {\n this.useRestClient_ = forceRestClient;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/RepoManager.ts","/**\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\nimport { fatal } from '../core/util/util';\nimport { parseRepoInfo } from '../core/util/libs/parser';\nimport { Path } from '../core/util/Path';\nimport { PromiseImpl } from '../../utils/promise';\nimport { Reference } from './Reference';\nimport { Repo } from '../core/Repo';\nimport { RepoManager } from '../core/RepoManager';\nimport { validateArgCount } from '../../utils/validation';\nimport { validateUrl } from '../core/util/validation';\nimport { FirebaseApp, FirebaseService } from '../../app/firebase_app';\nimport { RepoInfo } from '../core/RepoInfo';\n\n/**\n * Class representing a firebase database.\n * @implements {FirebaseService}\n */\nexport class Database implements FirebaseService {\n INTERNAL: DatabaseInternals;\n private root_: Reference;\n\n static readonly ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n\n /**\n * The constructor should not be called by users of our public API.\n * @param {!Repo} repo_\n */\n constructor(private repo_: Repo) {\n if (!(repo_ instanceof Repo)) {\n fatal(\n \"Don't call new Database() directly - please use firebase.database().\"\n );\n }\n\n /** @type {Reference} */\n this.root_ = new Reference(repo_, Path.Empty);\n\n this.INTERNAL = new DatabaseInternals(this);\n }\n\n get app(): FirebaseApp {\n return this.repo_.app;\n }\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 ref(pathString?: string): Reference {\n this.checkDeleted_('ref');\n validateArgCount('database.ref', 0, 1, arguments.length);\n\n return pathString !== undefined ? this.root_.child(pathString) : this.root_;\n }\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 refFromURL(url: string): Reference {\n /** @const {string} */\n const apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n validateArgCount(apiName, 1, 1, arguments.length);\n const parsedURL = parseRepoInfo(url);\n validateUrl(apiName, 1, parsedURL);\n\n const repoInfo = parsedURL.repoInfo;\n if (repoInfo.host !== ((this.repo_ as any).repoInfo_ as RepoInfo).host) {\n fatal(\n apiName +\n ': Host name does not match the current database: ' +\n '(found ' +\n repoInfo.host +\n ' but expected ' +\n ((this.repo_ as any).repoInfo_ as RepoInfo).host +\n ')'\n );\n }\n\n return this.ref(parsedURL.path.toString());\n }\n\n /**\n * @param {string} apiName\n */\n private checkDeleted_(apiName: string) {\n if (this.repo_ === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }\n\n // Make individual repo go offline.\n goOffline() {\n validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n }\n\n goOnline() {\n validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n }\n}\n\nexport class DatabaseInternals {\n /** @param {!Database} database */\n constructor(public database: Database) {}\n\n /** @return {Promise} */\n delete(): Promise {\n (this.database as any).checkDeleted_('delete');\n RepoManager.getInstance().deleteRepo((this.database as any).repo_ as Repo);\n\n (this.database as any).repo_ = null;\n (this.database as any).root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return PromiseImpl.resolve();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/Database.ts","/**\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\nimport { Path } from '../Path';\nimport { RepoInfo } from '../../RepoInfo';\nimport { warnIfPageIsSecure, fatal } from '../util';\n\n/**\n * @param {!string} pathString\n * @return {string}\n */\nfunction decodePath(pathString: string): string {\n let pathStringDecoded = '';\n const pieces = pathString.split('/');\n for (let i = 0; i < pieces.length; i++) {\n if (pieces[i].length > 0) {\n let piece = pieces[i];\n try {\n piece = decodeURIComponent(piece.replace(/\\+/g, ' '));\n } catch (e) {}\n pathStringDecoded += '/' + piece;\n }\n }\n return pathStringDecoded;\n}\n\n/**\n *\n * @param {!string} dataURL\n * @return {{repoInfo: !RepoInfo, path: !Path}}\n */\nexport const parseRepoInfo = function(\n dataURL: string\n): { repoInfo: RepoInfo; path: Path } {\n const parsedUrl = parseURL(dataURL),\n namespace = parsedUrl.subdomain;\n\n if (parsedUrl.domain === 'firebase') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use .firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (!namespace || namespace == 'undefined') {\n fatal(\n 'Cannot parse Firebase url. Please use https://.firebaseio.com'\n );\n }\n\n if (!parsedUrl.secure) {\n warnIfPageIsSecure();\n }\n\n const webSocketOnly = parsedUrl.scheme === 'ws' || parsedUrl.scheme === 'wss';\n\n return {\n repoInfo: new RepoInfo(\n parsedUrl.host,\n parsedUrl.secure,\n namespace,\n webSocketOnly\n ),\n path: new Path(parsedUrl.pathString)\n };\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 */\nexport const parseURL = function(\n dataURL: string\n): {\n host: string;\n port: number;\n domain: string;\n subdomain: string;\n secure: boolean;\n scheme: string;\n pathString: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '';\n\n // Always default to SSL, unless otherwise specified.\n let secure = true,\n scheme = 'https',\n port = 443;\n\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 let colonInd = dataURL.indexOf('//');\n if (colonInd >= 0) {\n scheme = dataURL.substring(0, colonInd - 1);\n dataURL = dataURL.substring(colonInd + 2);\n }\n\n // Parse host and path.\n let 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\n const 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 } else if (parts.length === 2) {\n domain = parts[0];\n }\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\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString\n };\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/libs/parser.ts","/**\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\nimport { assert } from '../../utils/assert';\nimport { forEach } from '../../utils/obj';\nimport { PersistentStorage } from './storage/storage';\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\n\n/**\n * A class that holds metadata about a Repo object\n *\n * @constructor\n */\nexport class RepoInfo {\n host: string;\n domain: string;\n internalHost: string;\n\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 constructor(\n host: string,\n public secure: boolean,\n public namespace: string,\n public webSocketOnly: boolean,\n public persistenceKey: string = ''\n ) {\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost = PersistentStorage.get('host:' + host) || this.host;\n }\n\n needsQueryParam(): boolean {\n return this.host !== this.internalHost;\n }\n\n isCacheableHost(): boolean {\n return this.internalHost.substr(0, 2) === 's-';\n }\n\n isDemoHost() {\n return this.domain === 'firebaseio-demo.com';\n }\n\n isCustomHost() {\n return (\n this.domain !== 'firebaseio.com' && this.domain !== 'firebaseio-demo.com'\n );\n }\n\n updateHost(newHost: string) {\n if (newHost !== this.internalHost) {\n this.internalHost = newHost;\n if (this.isCacheableHost()) {\n PersistentStorage.set('host:' + this.host, this.internalHost);\n }\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 connectionURL(type: string, params: { [k: string]: string }): string {\n assert(typeof type === 'string', 'typeof type must == string');\n assert(typeof params === 'object', 'typeof params must == object');\n\n let connURL: string;\n if (type === WEBSOCKET) {\n connURL =\n (this.secure ? 'wss://' : 'ws://') + this.internalHost + '/.ws?';\n } else if (type === LONG_POLLING) {\n connURL =\n (this.secure ? 'https://' : 'http://') + this.internalHost + '/.lp?';\n } else {\n throw new Error('Unknown connection type: ' + type);\n }\n if (this.needsQueryParam()) {\n params['ns'] = this.namespace;\n }\n\n const pairs: string[] = [];\n\n forEach(params, (key: string, value: string) => {\n pairs.push(key + '=' + value);\n });\n\n return connURL + pairs.join('&');\n }\n\n /** @return {string} */\n toString(): string {\n let str = this.toURLString();\n if (this.persistenceKey) {\n str += '<' + this.persistenceKey + '>';\n }\n return str;\n }\n\n /** @return {string} */\n toURLString(): string {\n return (this.secure ? 'https://' : 'http://') + this.host;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/RepoInfo.ts","/**\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\nimport { stringify } from '../../../utils/json';\nimport { Path } from '../util/Path';\nimport { EventRegistration } from './EventRegistration';\nimport { DataSnapshot } from '../../api/DataSnapshot';\n\n/**\n * Encapsulates the data needed to raise an event\n * @interface\n */\nexport interface Event {\n /**\n * @return {!Path}\n */\n getPath(): Path;\n\n /**\n * @return {!string}\n */\n getEventType(): string;\n\n /**\n * @return {!function()}\n */\n getEventRunner(): () => void;\n\n /**\n * @return {!string}\n */\n toString(): string;\n}\n\n/**\n * Encapsulates the data needed to raise an event\n * @implements {Event}\n */\nexport class DataEvent implements Event {\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 constructor(\n public eventType:\n | 'value'\n | ' child_added'\n | ' child_changed'\n | ' child_moved'\n | ' child_removed',\n public eventRegistration: EventRegistration,\n public snapshot: DataSnapshot,\n public prevName?: string | null\n ) {}\n\n /**\n * @inheritDoc\n */\n getPath(): Path {\n const ref = this.snapshot.getRef();\n if (this.eventType === 'value') {\n return ref.path;\n } else {\n return ref.getParent().path;\n }\n }\n\n /**\n * @inheritDoc\n */\n getEventType(): string {\n return this.eventType;\n }\n\n /**\n * @inheritDoc\n */\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n\n /**\n * @inheritDoc\n */\n toString(): string {\n return (\n this.getPath().toString() +\n ':' +\n this.eventType +\n ':' +\n stringify(this.snapshot.exportVal())\n );\n }\n}\n\nexport class CancelEvent implements Event {\n /**\n * @param {EventRegistration} eventRegistration\n * @param {Error} error\n * @param {!Path} path\n */\n constructor(\n public eventRegistration: EventRegistration,\n public error: Error,\n public path: Path\n ) {}\n\n /**\n * @inheritDoc\n */\n getPath(): Path {\n return this.path;\n }\n\n /**\n * @inheritDoc\n */\n getEventType(): string {\n return 'cancel';\n }\n\n /**\n * @inheritDoc\n */\n getEventRunner(): () => void {\n return this.eventRegistration.getEventRunner(this);\n }\n\n /**\n * @inheritDoc\n */\n toString(): string {\n return this.path.toString() + ':cancel';\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/Event.ts","/**\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\nimport { DataSnapshot } from '../../api/DataSnapshot';\nimport { DataEvent, CancelEvent, Event } from './Event';\nimport { contains, getCount, getAnyKey, every } from '../../../utils/obj';\nimport { assert } from '../../../utils/assert';\nimport { Path } from '../util/Path';\nimport { Change } from './Change';\nimport { Query } from '../../api/Query';\n\n/**\n * An EventRegistration is basically an event type ('value', 'child_added', etc.) and a callback\n * to be notified of that type of event.\n *\n * That said, it can also contain a cancel callback to be notified if the event is canceled. And\n * currently, this code is organized around the idea that you would register multiple child_ callbacks\n * together, as a single EventRegistration. Though currently we don't do that.\n */\nexport interface EventRegistration {\n /**\n * True if this container has a callback to trigger for this event type\n * @param {!string} eventType\n * @return {boolean}\n */\n respondsTo(eventType: string): boolean;\n\n /**\n * @param {!Change} change\n * @param {!Query} query\n * @return {!Event}\n */\n createEvent(change: Change, query: Query): Event;\n\n /**\n * Given event data, return a function to trigger the user's callback\n * @param {!Event} eventData\n * @return {function()}\n */\n getEventRunner(eventData: Event): () => void;\n\n /**\n * @param {!Error} error\n * @param {!Path} path\n * @return {?CancelEvent}\n */\n createCancelEvent(error: Error, path: Path): CancelEvent | null;\n\n /**\n * @param {!EventRegistration} other\n * @return {boolean}\n */\n matches(other: EventRegistration): boolean;\n\n /**\n * False basically means this is a \"dummy\" callback container being used as a sentinel\n * to remove all callback containers of a particular type. (e.g. if the user does\n * ref.off('value') without specifying a specific callback).\n *\n * (TODO: Rework this, since it's hacky)\n *\n * @return {boolean}\n */\n hasAnyCallback(): boolean;\n}\n\n/**\n * Represents registration for 'value' events.\n */\nexport class ValueEventRegistration implements EventRegistration {\n /**\n * @param {?function(!DataSnapshot)} callback_\n * @param {?function(Error)} cancelCallback_\n * @param {?Object} context_\n */\n constructor(\n private callback_: ((d: DataSnapshot) => void) | null,\n private cancelCallback_: ((e: Error) => void) | null,\n private context_: Object | null\n ) {}\n\n /**\n * @inheritDoc\n */\n respondsTo(eventType: string): boolean {\n return eventType === 'value';\n }\n\n /**\n * @inheritDoc\n */\n createEvent(change: Change, query: Query): DataEvent {\n const index = query.getQueryParams().getIndex();\n return new DataEvent(\n 'value',\n this,\n new DataSnapshot(change.snapshotNode, query.getRef(), index)\n );\n }\n\n /**\n * @inheritDoc\n */\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n const ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n assert(\n this.cancelCallback_,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n const cancelCB = this.cancelCallback_;\n return function() {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB.call(ctx, (eventData as CancelEvent).error);\n };\n } else {\n const cb = this.callback_;\n return function() {\n cb.call(ctx, (eventData as DataEvent).snapshot);\n };\n }\n }\n\n /**\n * @inheritDoc\n */\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.cancelCallback_) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n matches(other: EventRegistration): boolean {\n if (!(other instanceof ValueEventRegistration)) {\n return false;\n } else if (!other.callback_ || !this.callback_) {\n // If no callback specified, we consider it to match any callback.\n return true;\n } else {\n return (\n other.callback_ === this.callback_ && other.context_ === this.context_\n );\n }\n }\n\n /**\n * @inheritDoc\n */\n hasAnyCallback(): boolean {\n return this.callback_ !== null;\n }\n}\n\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 */\nexport class ChildEventRegistration implements EventRegistration {\n /**\n * @param {?Object.} callbacks_\n * @param {?function(Error)} cancelCallback_\n * @param {Object=} context_\n */\n constructor(\n private callbacks_:\n | ({ [k: string]: (d: DataSnapshot, s?: string | null) => void })\n | null,\n private cancelCallback_: ((e: Error) => void) | null,\n private context_?: Object\n ) {}\n\n /**\n * @inheritDoc\n */\n respondsTo(eventType: string): boolean {\n let eventToCheck =\n eventType === 'children_added' ? 'child_added' : eventType;\n eventToCheck =\n eventToCheck === 'children_removed' ? 'child_removed' : eventToCheck;\n return contains(this.callbacks_, eventToCheck);\n }\n\n /**\n * @inheritDoc\n */\n createCancelEvent(error: Error, path: Path): CancelEvent | null {\n if (this.cancelCallback_) {\n return new CancelEvent(this, error, path);\n } else {\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n createEvent(change: Change, query: Query): DataEvent {\n assert(change.childName != null, 'Child events should have a childName.');\n const ref = query.getRef().child /** @type {!string} */(change.childName);\n const index = query.getQueryParams().getIndex();\n return new DataEvent(\n change.type as any,\n this,\n new DataSnapshot(change.snapshotNode, ref, index as any),\n change.prevName\n );\n }\n\n /**\n * @inheritDoc\n */\n getEventRunner(eventData: CancelEvent | DataEvent): () => void {\n const ctx = this.context_;\n if (eventData.getEventType() === 'cancel') {\n assert(\n this.cancelCallback_,\n 'Raising a cancel event on a listener with no cancel callback'\n );\n const cancelCB = this.cancelCallback_;\n return function() {\n // We know that error exists, we checked above that this is a cancel event\n cancelCB.call(ctx, (eventData as CancelEvent).error);\n };\n } else {\n const cb = this.callbacks_[(eventData as DataEvent).eventType];\n return function() {\n cb.call(\n ctx,\n (eventData as DataEvent).snapshot,\n (eventData as DataEvent).prevName\n );\n };\n }\n }\n\n /**\n * @inheritDoc\n */\n matches(other: EventRegistration): boolean {\n if (other instanceof ChildEventRegistration) {\n if (!this.callbacks_ || !other.callbacks_) {\n return true;\n } else if (this.context_ === other.context_) {\n const otherCount = getCount(other.callbacks_);\n const thisCount = 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\n if (otherCount === 1) {\n const otherKey /** @type {!string} */ = getAnyKey(other.callbacks_);\n const thisKey /** @type {!string} */ = getAnyKey(this.callbacks_);\n return (\n 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 every(\n this.callbacks_,\n (eventType, cb) => other.callbacks_[eventType] === cb\n );\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * @inheritDoc\n */\n hasAnyCallback(): boolean {\n return this.callbacks_ !== null;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/EventRegistration.ts","/**\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\nimport { assert } from '../../utils/assert';\nimport { KEY_INDEX } from '../core/snap/indexes/KeyIndex';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { VALUE_INDEX } from '../core/snap/indexes/ValueIndex';\nimport { PathIndex } from '../core/snap/indexes/PathIndex';\nimport { MIN_NAME, MAX_NAME, ObjectToUniqueKey } from '../core/util/util';\nimport { Path } from '../core/util/Path';\nimport {\n isValidPriority,\n validateEventType,\n validatePathString,\n validateFirebaseDataArg,\n validateKey\n} from '../core/util/validation';\nimport {\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject\n} from '../../utils/validation';\nimport {\n ValueEventRegistration,\n ChildEventRegistration,\n EventRegistration\n} from '../core/view/EventRegistration';\nimport { Deferred, attachDummyErrorHandler } from '../../utils/promise';\nimport { Repo } from '../core/Repo';\nimport { QueryParams } from '../core/view/QueryParams';\nimport { Reference } from './Reference';\nimport { DataSnapshot } from './DataSnapshot';\n\nlet __referenceConstructor: new (repo: Repo, path: Path) => Query;\n\nexport interface SnapshotCallback {\n (a: DataSnapshot, b?: string): any;\n}\n\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 */\nexport class Query {\n static set __referenceConstructor(val) {\n __referenceConstructor = val;\n }\n\n static get __referenceConstructor() {\n assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n }\n\n constructor(\n public repo: Repo,\n public path: Path,\n private queryParams_: QueryParams,\n private orderByCalled_: boolean\n ) {}\n\n /**\n * Validates start/end values for queries.\n * @param {!QueryParams} params\n * @private\n */\n private static validateQueryEndpoints_(params: QueryParams) {\n let startNode = null;\n let endNode = null;\n if (params.hasStart()) {\n startNode = params.getIndexStartValue();\n }\n if (params.hasEnd()) {\n endNode = params.getIndexEndValue();\n }\n\n if (params.getIndex() === KEY_INDEX) {\n const tooManyArgsError =\n 'Query: When ordering by key, you may only pass one argument to ' +\n 'startAt(), endAt(), or equalTo().';\n const wrongArgTypeError =\n 'Query: When ordering by key, the argument passed to startAt(), endAt(),' +\n 'or equalTo() must be a string.';\n if (params.hasStart()) {\n const startName = params.getIndexStartName();\n if (startName != MIN_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof startNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n if (params.hasEnd()) {\n const endName = params.getIndexEndName();\n if (endName != MAX_NAME) {\n throw new Error(tooManyArgsError);\n } else if (typeof endNode !== 'string') {\n throw new Error(wrongArgTypeError);\n }\n }\n } else if (params.getIndex() === PRIORITY_INDEX) {\n if (\n (startNode != null && !isValidPriority(startNode)) ||\n (endNode != null && !isValidPriority(endNode))\n ) {\n throw new Error(\n '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 assert(\n params.getIndex() instanceof PathIndex ||\n params.getIndex() === VALUE_INDEX,\n 'unknown index type.'\n );\n if (\n (startNode != null && typeof startNode === 'object') ||\n (endNode != null && typeof endNode === 'object')\n ) {\n throw new Error(\n 'Query: First argument passed to startAt(), endAt(), or equalTo() cannot be ' +\n 'an object.'\n );\n }\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 private static validateLimit_(params: QueryParams) {\n if (\n params.hasStart() &&\n params.hasEnd() &&\n params.hasLimit() &&\n !params.hasAnchoredLimit()\n ) {\n throw new Error(\n \"Query: Can't combine startAt(), endAt(), and limit(). Use limitToFirst() or limitToLast() instead.\"\n );\n }\n }\n\n /**\n * Validates that no other order by call has been made\n * @param {!string} fnName\n * @private\n */\n private validateNoPreviousOrderByCall_(fnName: string) {\n if (this.orderByCalled_ === true) {\n throw new Error(fnName + \": You can't combine multiple orderBy calls.\");\n }\n }\n\n /**\n * @return {!QueryParams}\n */\n getQueryParams(): QueryParams {\n return this.queryParams_;\n }\n\n /**\n * @return {!Reference}\n */\n getRef(): Reference {\n 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) as Reference;\n }\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 on(\n eventType: string,\n callback: SnapshotCallback,\n cancelCallbackOrContext?: ((a: Error) => any) | Object,\n context?: Object\n ): SnapshotCallback {\n validateArgCount('Query.on', 2, 4, arguments.length);\n validateEventType('Query.on', 1, eventType, false);\n validateCallback('Query.on', 2, callback, false);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.on',\n cancelCallbackOrContext,\n context\n );\n\n if (eventType === 'value') {\n this.onValueEvent(callback, ret.cancel, ret.context);\n } else {\n const callbacks: { [k: string]: typeof callback } = {};\n callbacks[eventType] = callback;\n this.onChildEvent(callbacks, ret.cancel, ret.context);\n }\n return callback;\n }\n\n /**\n * @param {!function(!DataSnapshot)} callback\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n protected onValueEvent(\n callback: (a: DataSnapshot) => void,\n cancelCallback: ((a: Error) => void) | null,\n context: Object | null\n ) {\n const container = new ValueEventRegistration(\n callback,\n cancelCallback || null,\n context || null\n );\n this.repo.addEventCallbackForQuery(this, container);\n }\n\n /**\n * @param {!Object.} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n onChildEvent(\n callbacks: { [k: string]: SnapshotCallback },\n cancelCallback: ((a: Error) => any) | null,\n context: Object | null\n ) {\n const container = new ChildEventRegistration(\n callbacks,\n cancelCallback,\n context\n );\n this.repo.addEventCallbackForQuery(this, container);\n }\n\n /**\n * @param {string=} eventType\n * @param {(function(!DataSnapshot, ?string=))=} callback\n * @param {Object=} context\n */\n off(eventType?: string, callback?: SnapshotCallback, context?: Object) {\n validateArgCount('Query.off', 0, 3, arguments.length);\n validateEventType('Query.off', 1, eventType, true);\n validateCallback('Query.off', 2, callback, true);\n validateContextObject('Query.off', 3, context, true);\n\n let container: EventRegistration | null = null;\n let callbacks: { [k: string]: typeof callback } | null = null;\n if (eventType === 'value') {\n const valueCallback = callback || null;\n container = new ValueEventRegistration(\n valueCallback,\n null,\n context || null\n );\n } else if (eventType) {\n if (callback) {\n callbacks = {};\n callbacks[eventType] = callback;\n }\n container = new ChildEventRegistration(callbacks, null, context || null);\n }\n this.repo.removeEventCallbackForQuery(this, container);\n }\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 once(\n eventType: string,\n userCallback?: SnapshotCallback,\n cancelOrContext?: ((a: Error) => void) | Object,\n context?: Object\n ): Promise {\n validateArgCount('Query.once', 1, 4, arguments.length);\n validateEventType('Query.once', 1, eventType, false);\n validateCallback('Query.once', 2, userCallback, true);\n\n const ret = Query.getCancelAndContextArgs_(\n 'Query.once',\n cancelOrContext,\n context\n );\n\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 let firstCall = true;\n const deferred = new Deferred();\n attachDummyErrorHandler(deferred.promise);\n\n const onceCallback = (snapshot: DataSnapshot) => {\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\n if (userCallback) {\n userCallback.bind(ret.context)(snapshot);\n }\n deferred.resolve(snapshot);\n }\n };\n\n this.on(\n eventType,\n onceCallback,\n /*cancel=*/ err => {\n this.off(eventType, onceCallback);\n\n if (ret.cancel) ret.cancel.bind(ret.context)(err);\n deferred.reject(err);\n }\n );\n return deferred.promise;\n }\n\n /**\n * Set a limit and anchor it to the start of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n limitToFirst(limit: number): Query {\n validateArgCount('Query.limitToFirst', 1, 1, arguments.length);\n if (\n typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0\n ) {\n throw new Error(\n 'Query.limitToFirst: First argument must be a positive integer.'\n );\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error(\n 'Query.limitToFirst: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).'\n );\n }\n\n return new Query(\n this.repo,\n this.path,\n this.queryParams_.limitToFirst(limit),\n this.orderByCalled_\n );\n }\n\n /**\n * Set a limit and anchor it to the end of the window.\n * @param {!number} limit\n * @return {!Query}\n */\n limitToLast(limit: number): Query {\n validateArgCount('Query.limitToLast', 1, 1, arguments.length);\n if (\n typeof limit !== 'number' ||\n Math.floor(limit) !== limit ||\n limit <= 0\n ) {\n throw new Error(\n 'Query.limitToLast: First argument must be a positive integer.'\n );\n }\n if (this.queryParams_.hasLimit()) {\n throw new Error(\n 'Query.limitToLast: Limit was already set (by another call to limit, ' +\n 'limitToFirst, or limitToLast).'\n );\n }\n\n return new Query(\n this.repo,\n this.path,\n this.queryParams_.limitToLast(limit),\n this.orderByCalled_\n );\n }\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 orderByChild(path: string): Query {\n validateArgCount('Query.orderByChild', 1, 1, arguments.length);\n if (path === '$key') {\n throw new Error(\n 'Query.orderByChild: \"$key\" is invalid. Use Query.orderByKey() instead.'\n );\n } else if (path === '$priority') {\n throw new Error(\n 'Query.orderByChild: \"$priority\" is invalid. Use Query.orderByPriority() instead.'\n );\n } else if (path === '$value') {\n throw new Error(\n 'Query.orderByChild: \"$value\" is invalid. Use Query.orderByValue() instead.'\n );\n }\n validatePathString('Query.orderByChild', 1, path, false);\n this.validateNoPreviousOrderByCall_('Query.orderByChild');\n const parsedPath = new Path(path);\n if (parsedPath.isEmpty()) {\n throw new Error(\n 'Query.orderByChild: cannot pass in empty path. Use Query.orderByValue() instead.'\n );\n }\n const index = new PathIndex(parsedPath);\n const newParams = this.queryParams_.orderBy(index);\n Query.validateQueryEndpoints_(newParams);\n\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n }\n\n /**\n * Return a new query ordered by the KeyIndex\n * @return {!Query}\n */\n orderByKey(): Query {\n validateArgCount('Query.orderByKey', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByKey');\n const newParams = this.queryParams_.orderBy(KEY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n }\n\n /**\n * Return a new query ordered by the PriorityIndex\n * @return {!Query}\n */\n orderByPriority(): Query {\n validateArgCount('Query.orderByPriority', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByPriority');\n const newParams = this.queryParams_.orderBy(PRIORITY_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n }\n\n /**\n * Return a new query ordered by the ValueIndex\n * @return {!Query}\n */\n orderByValue(): Query {\n validateArgCount('Query.orderByValue', 0, 0, arguments.length);\n this.validateNoPreviousOrderByCall_('Query.orderByValue');\n const newParams = this.queryParams_.orderBy(VALUE_INDEX);\n Query.validateQueryEndpoints_(newParams);\n return new Query(this.repo, this.path, newParams, /*orderByCalled=*/ true);\n }\n\n /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n startAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.startAt', 0, 2, arguments.length);\n validateFirebaseDataArg('Query.startAt', 1, value, this.path, true);\n validateKey('Query.startAt', 2, name, true);\n\n const newParams = this.queryParams_.startAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasStart()) {\n throw new Error(\n 'Query.startAt: Starting point was already set (by another call to startAt ' +\n 'or equalTo).'\n );\n }\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 /**\n * @param {number|string|boolean|null} value\n * @param {?string=} name\n * @return {!Query}\n */\n endAt(\n value: number | string | boolean | null = null,\n name?: string | null\n ): Query {\n validateArgCount('Query.endAt', 0, 2, arguments.length);\n validateFirebaseDataArg('Query.endAt', 1, value, this.path, true);\n validateKey('Query.endAt', 2, name, true);\n\n const newParams = this.queryParams_.endAt(value, name);\n Query.validateLimit_(newParams);\n Query.validateQueryEndpoints_(newParams);\n if (this.queryParams_.hasEnd()) {\n throw new Error(\n 'Query.endAt: Ending point was already set (by another call to endAt or ' +\n 'equalTo).'\n );\n }\n\n return new Query(this.repo, this.path, newParams, this.orderByCalled_);\n }\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 equalTo(value: number | string | boolean | null, name?: string) {\n validateArgCount('Query.equalTo', 1, 2, arguments.length);\n validateFirebaseDataArg('Query.equalTo', 1, value, this.path, false);\n validateKey('Query.equalTo', 2, name, true);\n if (this.queryParams_.hasStart()) {\n throw new Error(\n 'Query.equalTo: Starting point was already set (by another call to startAt or ' +\n 'equalTo).'\n );\n }\n if (this.queryParams_.hasEnd()) {\n throw new Error(\n 'Query.equalTo: Ending point was already set (by another call to endAt or ' +\n 'equalTo).'\n );\n }\n return this.startAt(value, name).endAt(value, name);\n }\n\n /**\n * @return {!string} URL for this location.\n */\n toString(): string {\n validateArgCount('Query.toString', 0, 0, arguments.length);\n\n return this.repo.toString() + this.path.toUrlEncodedString();\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users.\n toJSON() {\n // An optional spacer argument is unnecessary for a string.\n validateArgCount('Query.toJSON', 0, 1, arguments.length);\n return this.toString();\n }\n\n /**\n * An object representation of the query parameters used by this Query.\n * @return {!Object}\n */\n queryObject(): Object {\n return this.queryParams_.getQueryObject();\n }\n\n /**\n * @return {!string}\n */\n queryIdentifier(): string {\n const obj = this.queryObject();\n const id = ObjectToUniqueKey(obj);\n return id === '{}' ? 'default' : id;\n }\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 isEqual(other: Query): boolean {\n validateArgCount('Query.isEqual', 1, 1, arguments.length);\n if (!(other instanceof Query)) {\n const error =\n 'Query.isEqual failed: First argument must be an instance of firebase.database.Query.';\n throw new Error(error);\n }\n\n const sameRepo = this.repo === other.repo;\n const samePath = this.path.equals(other.path);\n const sameQueryIdentifier =\n this.queryIdentifier() === other.queryIdentifier();\n\n return sameRepo && samePath && sameQueryIdentifier;\n }\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 private static getCancelAndContextArgs_(\n fnName: string,\n cancelOrContext?: ((a: Error) => void) | Object,\n context?: Object\n ): { cancel: ((a: Error) => void) | null; context: Object | null } {\n const ret: {\n cancel: ((a: Error) => void) | null;\n context: Object | null;\n } = { cancel: null, context: null };\n if (cancelOrContext && context) {\n ret.cancel = cancelOrContext as (a: Error) => void;\n validateCallback(fnName, 3, ret.cancel, true);\n\n ret.context = context;\n validateContextObject(fnName, 4, ret.context, true);\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 } else if (typeof cancelOrContext === 'function') {\n ret.cancel = cancelOrContext;\n } else {\n throw new Error(\n errorPrefix(fnName, 3, true) +\n ' must either be a cancel callback or a context object.'\n );\n }\n }\n return ret;\n }\n\n get ref(): Reference {\n return this.getRef();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/Query.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { doubleToIEEE754String } from '../util/util';\nimport { contains } from '../../../utils/obj';\nimport { Node } from './Node';\n\nlet MAX_NODE: Node;\n\nexport function setMaxNode(val: Node) {\n MAX_NODE = val;\n}\n\n/**\n * @param {(!string|!number)} priority\n * @return {!string}\n */\nexport const priorityHashText = function(priority: string | number): string {\n if (typeof priority === 'number')\n return 'number:' + doubleToIEEE754String(priority);\n else return 'string:' + priority;\n};\n\n/**\n * Validates that a priority snapshot Node is valid.\n *\n * @param {!Node} priorityNode\n */\nexport const validatePriorityNode = function(priorityNode: Node) {\n if (priorityNode.isLeafNode()) {\n const val = priorityNode.val();\n assert(\n typeof val === 'string' ||\n typeof val === 'number' ||\n (typeof val === 'object' && contains(val, '.sv')),\n 'Priority must be a string or number.'\n );\n } else {\n assert(\n priorityNode === MAX_NODE || priorityNode.isEmpty(),\n 'priority of unexpected type.'\n );\n }\n // Don't call getPriority() on MAX_NODE to avoid hitting assertion.\n assert(\n priorityNode === MAX_NODE || priorityNode.getPriority().isEmpty(),\n \"Priority nodes can't have a priority of their own.\"\n );\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/snap.ts","/**\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\nimport { Index } from './Index';\nimport { NamedNode, Node } from '../Node';\nimport { nameCompare } from '../../util/util';\nimport { nodeFromJSON } from '../nodeFromJSON';\n\n/**\n * @constructor\n * @extends {Index}\n * @private\n */\nexport class ValueIndex extends Index {\n /**\n * @inheritDoc\n */\n compare(a: NamedNode, b: NamedNode): number {\n const indexCmp = a.node.compareTo(b.node);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n\n /**\n * @inheritDoc\n */\n isDefinedOn(node: Node): boolean {\n return true;\n }\n\n /**\n * @inheritDoc\n */\n indexedValueChanged(oldNode: Node, newNode: Node): boolean {\n return !oldNode.equals(newNode);\n }\n\n /**\n * @inheritDoc\n */\n minPost(): NamedNode {\n return (NamedNode as any).MIN;\n }\n\n /**\n * @inheritDoc\n */\n maxPost(): NamedNode {\n return (NamedNode as any).MAX;\n }\n\n /**\n * @param {*} indexValue\n * @param {string} name\n * @return {!NamedNode}\n */\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n return new NamedNode(name, valueNode);\n }\n\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n toString(): string {\n return '.value';\n }\n}\n\nexport const VALUE_INDEX = new ValueIndex();\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/indexes/ValueIndex.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { buildChildSet } from './childSet';\nimport { contains, clone, map, safeGet } from '../../../utils/obj';\nimport { NamedNode, Node } from './Node';\nimport { PRIORITY_INDEX } from './indexes/PriorityIndex';\nimport { KEY_INDEX } from './indexes/KeyIndex';\nimport { SortedMap } from '../util/SortedMap';\nimport { Index } from './indexes/Index';\n\nlet _defaultIndexMap: IndexMap;\n\nconst fallbackObject = {};\n\n/**\n *\n * @param {Object.>} indexes\n * @param {Object.} indexSet\n * @constructor\n */\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\n * @type {!IndexMap}\n * @const\n */\n static get Default(): IndexMap {\n assert(\n fallbackObject && PRIORITY_INDEX,\n 'ChildrenNode.ts has not been loaded'\n );\n _defaultIndexMap =\n _defaultIndexMap ||\n new IndexMap(\n { '.priority': fallbackObject },\n { '.priority': PRIORITY_INDEX }\n );\n return _defaultIndexMap;\n }\n\n constructor(\n private indexes_: {\n [k: string]: SortedMap | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n /**\n *\n * @param {!string} indexKey\n * @return {?SortedMap.}\n */\n get(indexKey: string): SortedMap | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) throw new Error('No index defined for ' + indexKey);\n\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 } else {\n return sortedMap;\n }\n }\n\n /**\n * @param {!Index} indexDefinition\n * @return {boolean}\n */\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n /**\n * @param {!Index} indexDefinition\n * @param {!SortedMap.} existingChildren\n * @return {!IndexMap}\n */\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap\n ): IndexMap {\n assert(\n indexDefinition !== KEY_INDEX,\n \"KeyIndex always exists and isn't meant to be added to the IndexMap.\"\n );\n const childList = [];\n let sawIndexedValue = false;\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let next = iter.getNext();\n while (next) {\n sawIndexedValue =\n sawIndexedValue || indexDefinition.isDefinedOn(next.node);\n childList.push(next);\n next = iter.getNext();\n }\n let newIndex;\n if (sawIndexedValue) {\n newIndex = buildChildSet(childList, indexDefinition.getCompare());\n } else {\n newIndex = fallbackObject;\n }\n const indexName = indexDefinition.toString();\n const newIndexSet = clone(this.indexSet_);\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = clone(this.indexes_);\n newIndexes[indexName] = newIndex;\n return new IndexMap(newIndexes, newIndexSet);\n }\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 addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap, indexName: string) => {\n const index = safeGet(this.indexSet_, indexName);\n 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 const childList = [];\n const iter = existingChildren.getIterator(NamedNode.Wrap);\n let 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 buildChildSet(childList, index.getCompare());\n } else {\n // No change, this remains a fallback\n return fallbackObject;\n }\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n let newChildren = indexedChildren;\n if (existingSnap) {\n newChildren = newChildren.remove(\n new NamedNode(namedNode.name, existingSnap)\n );\n }\n return newChildren.insert(namedNode, namedNode.node);\n }\n }\n );\n return new IndexMap(newIndexes, this.indexSet_);\n }\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 removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap\n ): IndexMap {\n const newIndexes = map(this.indexes_, function(\n indexedChildren: SortedMap\n ) {\n if (indexedChildren === fallbackObject) {\n // This is the fallback. Just return it, nothing to do in this case\n return indexedChildren;\n } else {\n const existingSnap = existingChildren.get(namedNode.name);\n if (existingSnap) {\n return indexedChildren.remove(\n new 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}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/IndexMap.ts","/**\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\nimport { LLRBNode } from '../util/SortedMap';\nimport { SortedMap } from '../util/SortedMap';\nimport { NamedNode } from './Node';\n\nconst LOG_2 = Math.log(2);\n\n/**\n * @constructor\n */\nclass Base12Num {\n count: number;\n private current_: number;\n private bits_: number;\n\n /**\n * @param {number} length\n */\n constructor(length: number) {\n const logBase2 = (num: number) =>\n parseInt((Math.log(num) / LOG_2) as any, 10);\n const bitMask = (bits: number) => parseInt(Array(bits + 1).join('1'), 2);\n this.count = logBase2(length + 1);\n this.current_ = this.count - 1;\n const mask = bitMask(this.count);\n this.bits_ = (length + 1) & mask;\n }\n\n /**\n * @return {boolean}\n */\n nextBitIsOne(): boolean {\n //noinspection JSBitwiseOperatorUsage\n const result = !(this.bits_ & (0x1 << this.current_));\n this.current_--;\n return result;\n }\n}\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 */\nexport const buildChildSet = function(\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap {\n childList.sort(cmp);\n\n const buildBalancedTree = function(\n low: number,\n high: number\n ): LLRBNode | null {\n const length = high - low;\n let namedNode: NamedNode;\n let key: K;\n if (length == 0) {\n return null;\n } else if (length == 1) {\n namedNode = childList[low];\n key = keyFn ? keyFn(namedNode) : (namedNode as any) as K;\n return new LLRBNode(\n key,\n (namedNode.node as any) as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n const middle = parseInt((length / 2) as any, 10) + low;\n const left = buildBalancedTree(low, middle);\n const right = buildBalancedTree(middle + 1, high);\n namedNode = childList[middle];\n key = keyFn ? keyFn(namedNode) : (namedNode as any) as K;\n return new LLRBNode(\n key,\n (namedNode.node as any) as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function(base12: Base12Num): LLRBNode {\n let node: LLRBNode = null;\n let root = null;\n let index = childList.length;\n\n const buildPennant = function(chunkSize: number, color: boolean) {\n const low = index - chunkSize;\n const high = index;\n index -= chunkSize;\n const childTree = buildBalancedTree(low + 1, high);\n const namedNode = childList[low];\n const key: K = keyFn ? keyFn(namedNode) : (namedNode as any) as K;\n attachPennant(\n new LLRBNode(key, (namedNode.node as any) as V, color, null, childTree)\n );\n };\n\n const attachPennant = function(pennant: LLRBNode) {\n if (node) {\n node.left = pennant;\n node = pennant;\n } else {\n root = pennant;\n node = pennant;\n }\n };\n\n for (let i = 0; i < base12.count; ++i) {\n const isOne = base12.nextBitIsOne();\n // The number of nodes taken in each slice is 2^(arr.length - (i + 1))\n const chunkSize = Math.pow(2, base12.count - (i + 1));\n if (isOne) {\n buildPennant(chunkSize, LLRBNode.BLACK);\n } else {\n // current == 2\n buildPennant(chunkSize, LLRBNode.BLACK);\n buildPennant(chunkSize, LLRBNode.RED);\n }\n }\n return root;\n };\n\n const base12 = new Base12Num(childList.length);\n const root = buildFrom12Array(base12);\n\n return new SortedMap(mapSortFn || (cmp as any), root);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/childSet.ts","/**\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\nimport { nameCompare } from '../util/util';\nimport { NamedNode } from './Node';\n\nexport function NAME_ONLY_COMPARATOR(left: NamedNode, right: NamedNode) {\n return nameCompare(left.name, right.name);\n}\n\nexport function NAME_COMPARATOR(left: string, right: string) {\n return nameCompare(left, right);\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/comparators.ts","/**\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\nimport { assert } from '../../../../utils/assert';\nimport { nameCompare, MAX_NAME } from '../../util/util';\nimport { Index } from './Index';\nimport { ChildrenNode, MAX_NODE } from '../ChildrenNode';\nimport { NamedNode, Node } from '../Node';\nimport { nodeFromJSON } from '../nodeFromJSON';\nimport { Path } from '../../util/Path';\n\n/**\n * @param {!Path} indexPath\n * @constructor\n * @extends {Index}\n */\nexport class PathIndex extends Index {\n constructor(private indexPath_: Path) {\n super();\n\n assert(\n !indexPath_.isEmpty() && indexPath_.getFront() !== '.priority',\n \"Can't create PathIndex with empty path or .priority key\"\n );\n }\n\n /**\n * @param {!Node} snap\n * @return {!Node}\n * @protected\n */\n protected extractChild(snap: Node): Node {\n return snap.getChild(this.indexPath_);\n }\n\n /**\n * @inheritDoc\n */\n isDefinedOn(node: Node): boolean {\n return !node.getChild(this.indexPath_).isEmpty();\n }\n\n /**\n * @inheritDoc\n */\n compare(a: NamedNode, b: NamedNode): number {\n const aChild = this.extractChild(a.node);\n const bChild = this.extractChild(b.node);\n const indexCmp = aChild.compareTo(bChild);\n if (indexCmp === 0) {\n return nameCompare(a.name, b.name);\n } else {\n return indexCmp;\n }\n }\n\n /**\n * @inheritDoc\n */\n makePost(indexValue: object, name: string): NamedNode {\n const valueNode = nodeFromJSON(indexValue);\n const node = ChildrenNode.EMPTY_NODE.updateChild(\n this.indexPath_,\n valueNode\n );\n return new NamedNode(name, node);\n }\n\n /**\n * @inheritDoc\n */\n maxPost(): NamedNode {\n const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);\n return new NamedNode(MAX_NAME, node);\n }\n\n /**\n * @inheritDoc\n */\n toString(): string {\n return this.indexPath_.slice().join('/');\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/snap/indexes/PathIndex.ts","/**\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\nimport { validateArgCount, validateCallback } from '../../utils/validation';\nimport { validatePathString } from '../core/util/validation';\nimport { Path } from '../core/util/Path';\nimport { PRIORITY_INDEX } from '../core/snap/indexes/PriorityIndex';\nimport { Node } from '../core/snap/Node';\nimport { Reference } from './Reference';\nimport { Index } from '../core/snap/indexes/Index';\nimport { ChildrenNode } from '../core/snap/ChildrenNode';\n\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 */\nexport class DataSnapshot {\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 constructor(\n private readonly node_: Node,\n private readonly ref_: Reference,\n private readonly index_: Index\n ) {}\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 val(): any {\n validateArgCount('DataSnapshot.val', 0, 0, arguments.length);\n return this.node_.val();\n }\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 exportVal(): any {\n validateArgCount('DataSnapshot.exportVal', 0, 0, arguments.length);\n return this.node_.val(true);\n }\n\n // Do not create public documentation. This is intended to make JSON serialization work but is otherwise unnecessary\n // for end-users\n toJSON(): any {\n // Optional spacer argument is unnecessary because we're depending on recursion rather than stringifying the content\n validateArgCount('DataSnapshot.toJSON', 0, 1, arguments.length);\n return this.exportVal();\n }\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 exists(): boolean {\n validateArgCount('DataSnapshot.exists', 0, 0, arguments.length);\n return !this.node_.isEmpty();\n }\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 child(childPathString: string): DataSnapshot {\n validateArgCount('DataSnapshot.child', 0, 1, arguments.length);\n // Ensure the childPath is a string (can be a number)\n childPathString = String(childPathString);\n validatePathString('DataSnapshot.child', 1, childPathString, false);\n\n const childPath = new Path(childPathString);\n const childRef = this.ref_.child(childPath);\n return new DataSnapshot(\n this.node_.getChild(childPath),\n childRef,\n PRIORITY_INDEX\n );\n }\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 hasChild(childPathString: string): boolean {\n validateArgCount('DataSnapshot.hasChild', 1, 1, arguments.length);\n validatePathString('DataSnapshot.hasChild', 1, childPathString, false);\n\n const childPath = new Path(childPathString);\n return !this.node_.getChild(childPath).isEmpty();\n }\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 getPriority(): string | number | null {\n validateArgCount('DataSnapshot.getPriority', 0, 0, arguments.length);\n\n // typecast here because we never return deferred values or internal priorities (MAX_PRIORITY)\n return this.node_.getPriority().val() as string | number | null;\n }\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 forEach(action: (d: DataSnapshot) => void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 1, action, false);\n\n if (this.node_.isLeafNode()) return false;\n\n const childrenNode = this.node_ as ChildrenNode;\n // Sanitize the return value to a boolean. ChildrenNode.forEachChild has a weird return type...\n return !!childrenNode.forEachChild(this.index_, (key, node) => {\n return action(\n new DataSnapshot(node, this.ref_.child(key), PRIORITY_INDEX)\n );\n });\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 hasChildren(): boolean {\n validateArgCount('DataSnapshot.hasChildren', 0, 0, arguments.length);\n\n if (this.node_.isLeafNode()) return false;\n else return !this.node_.isEmpty();\n }\n\n get key() {\n return this.ref_.getKey();\n }\n\n /**\n * Returns the number of children for this DataSnapshot.\n * @return {number} The number of children that this DataSnapshot contains.\n */\n numChildren(): number {\n validateArgCount('DataSnapshot.numChildren', 0, 0, arguments.length);\n\n return this.node_.numChildren();\n }\n\n /**\n * @return {Reference} The Firebase reference for the location this snapshot's data came from.\n */\n getRef(): Reference {\n validateArgCount('DataSnapshot.ref', 0, 0, arguments.length);\n\n return this.ref_;\n }\n\n get ref() {\n return this.getRef();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/DataSnapshot.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { Path } from './Path';\nimport { SparseSnapshotTree } from '../SparseSnapshotTree';\nimport { LeafNode } from '../snap/LeafNode';\nimport { nodeFromJSON } from '../snap/nodeFromJSON';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Node } from '../snap/Node';\nimport { ChildrenNode } from '../snap/ChildrenNode';\n\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexport const generateWithValues = function(values: {\n [k: string]: any;\n} | null): { [k: string]: any } {\n values = values || {};\n values['timestamp'] = values['timestamp'] || new Date().getTime();\n return values;\n};\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 */\nexport const resolveDeferredValue = function(\n value: { [k: string]: any } | string | number | boolean,\n serverValues: { [k: string]: any }\n): string | number | boolean {\n if (!value || typeof value !== 'object') {\n return value as string | number | boolean;\n } else {\n assert('.sv' in value, 'Unexpected leaf node or priority contents');\n return serverValues[value['.sv']];\n }\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 */\nexport const resolveDeferredValueTree = function(\n tree: SparseSnapshotTree,\n serverValues: Object\n): SparseSnapshotTree {\n const resolvedTree = new SparseSnapshotTree();\n tree.forEachTree(new Path(''), function(path, node) {\n resolvedTree.remember(\n path,\n resolveDeferredValueSnapshot(node, serverValues)\n );\n });\n return resolvedTree;\n};\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 */\nexport const resolveDeferredValueSnapshot = function(\n node: Node,\n serverValues: Object\n): Node {\n const rawPri = node.getPriority().val() as\n | object\n | boolean\n | null\n | number\n | string;\n const priority = resolveDeferredValue(rawPri, serverValues);\n let newNode: Node;\n\n if (node.isLeafNode()) {\n const leafNode = node as LeafNode;\n const value = resolveDeferredValue(leafNode.getValue(), serverValues);\n if (\n value !== leafNode.getValue() ||\n priority !== leafNode.getPriority().val()\n ) {\n return new LeafNode(value, nodeFromJSON(priority));\n } else {\n return node;\n }\n } else {\n const childrenNode = node as ChildrenNode;\n newNode = childrenNode;\n if (priority !== childrenNode.getPriority().val()) {\n newNode = newNode.updatePriority(new LeafNode(priority));\n }\n childrenNode.forEachChild(PRIORITY_INDEX, function(childName, childNode) {\n const newChildNode = resolveDeferredValueSnapshot(\n childNode,\n serverValues\n );\n if (newChildNode !== childNode) {\n newNode = newNode.updateImmediateChild(childName, newChildNode);\n }\n });\n return newNode;\n }\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/ServerValues.ts","/**\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\nimport { Path } from './util/Path';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { CountedSet } from './util/CountedSet';\nimport { Node } from './snap/Node';\n\n/**\n * Helper class to store a sparse set of snapshots.\n *\n * @constructor\n */\nexport class SparseSnapshotTree {\n /**\n * @private\n * @type {Node}\n */\n private value_: Node | null = null;\n\n /**\n * @private\n * @type {CountedSet}\n */\n private children_: CountedSet | null = 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 find(path: Path): Node | null {\n if (this.value_ != null) {\n return this.value_.getChild(path);\n } else if (!path.isEmpty() && this.children_ != null) {\n const childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n const childTree = this.children_.get(childKey) as SparseSnapshotTree;\n return childTree.find(path);\n } else {\n return null;\n }\n } else {\n return null;\n }\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 remember(path: Path, data: Node) {\n if (path.isEmpty()) {\n this.value_ = data;\n this.children_ = null;\n } else if (this.value_ !== null) {\n this.value_ = this.value_.updateChild(path, data);\n } else {\n if (this.children_ == null) {\n this.children_ = new CountedSet();\n }\n\n const childKey = path.getFront();\n if (!this.children_.contains(childKey)) {\n this.children_.add(childKey, new SparseSnapshotTree());\n }\n\n const child = this.children_.get(childKey) as SparseSnapshotTree;\n path = path.popFront();\n child.remember(path, data);\n }\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 forget(path: Path): boolean {\n if (path.isEmpty()) {\n this.value_ = null;\n this.children_ = null;\n return true;\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 } else {\n const value = this.value_;\n this.value_ = null;\n\n const self = this;\n value.forEachChild(PRIORITY_INDEX, function(key, tree) {\n self.remember(new Path(key), tree);\n });\n\n return this.forget(path);\n }\n } else if (this.children_ !== null) {\n const childKey = path.getFront();\n path = path.popFront();\n if (this.children_.contains(childKey)) {\n const safeToRemove = (this.children_.get(\n childKey\n ) as SparseSnapshotTree).forget(path);\n if (safeToRemove) {\n this.children_.remove(childKey);\n }\n }\n\n if (this.children_.isEmpty()) {\n this.children_ = null;\n return true;\n } else {\n return false;\n }\n } else {\n return true;\n }\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 forEachTree(prefixPath: Path, func: (a: Path, b: Node) => any) {\n if (this.value_ !== null) {\n func(prefixPath, this.value_);\n } else {\n this.forEachChild((key, tree) => {\n const path = new Path(prefixPath.toString() + '/' + key);\n tree.forEachTree(path, func);\n });\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 forEachChild(func: (a: string, b: SparseSnapshotTree) => void) {\n if (this.children_ !== null) {\n this.children_.each((key, tree) => {\n func(key, tree);\n });\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/SparseSnapshotTree.ts","/**\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\nimport { isEmpty, getCount, forEach, contains } from '../../../utils/obj';\n\n/**\n * Implements a set with a count of elements.\n *\n * @template K, V\n */\nexport class CountedSet {\n set: { [k: string]: V } = {};\n\n /**\n * @param {!K} item\n * @param {V} val\n */\n add(item: K, val: V) {\n this.set[item as any] = val !== null ? val : true as any;\n }\n\n /**\n * @param {!K} key\n * @return {boolean}\n */\n contains(key: K) {\n return contains(this.set, key);\n }\n\n /**\n * @param {!K} item\n * @return {V}\n */\n get(item: K): V | void {\n return this.contains(item) ? this.set[item as any] : undefined;\n }\n\n /**\n * @param {!K} item\n */\n remove(item: K) {\n delete this.set[item as any];\n }\n\n /**\n * Deletes everything in the set\n */\n clear() {\n this.set = {};\n }\n\n /**\n * True if there's nothing in the set\n * @return {boolean}\n */\n isEmpty(): boolean {\n return isEmpty(this.set);\n }\n\n /**\n * @return {number} The number of items in the set\n */\n count(): number {\n return getCount(this.set);\n }\n\n /**\n * Run a function on each k,v pair in the set\n * @param {function(K, V)} fn\n */\n each(fn: (k: K, v: V) => void) {\n forEach(this.set, (k: K, v: V) => fn(k, v));\n }\n\n /**\n * Mostly for debugging\n * @return {Array.} The keys present in this CountedSet\n */\n keys(): K[] {\n const keys: K[] = [];\n forEach(this.set, (k: K) => {\n keys.push(k);\n });\n return keys;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/CountedSet.ts","/**\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\nimport { Node } from '../snap/Node';\nimport { Path } from '../util/Path';\n\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 */\nexport class CacheNode {\n /**\n * @param {!Node} node_\n * @param {boolean} fullyInitialized_\n * @param {boolean} filtered_\n */\n constructor(\n private node_: Node,\n private fullyInitialized_: boolean,\n private filtered_: boolean\n ) {}\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 isFullyInitialized(): boolean {\n return this.fullyInitialized_;\n }\n\n /**\n * Returns whether this node is potentially missing children due to a filter applied to the node\n * @return {boolean}\n */\n isFiltered(): boolean {\n return this.filtered_;\n }\n\n /**\n * @param {!Path} path\n * @return {boolean}\n */\n isCompleteForPath(path: Path): boolean {\n if (path.isEmpty()) {\n return this.isFullyInitialized() && !this.filtered_;\n }\n\n const childKey = path.getFront();\n return this.isCompleteForChild(childKey);\n }\n\n /**\n * @param {!string} key\n * @return {boolean}\n */\n isCompleteForChild(key: string): boolean {\n return (\n (this.isFullyInitialized() && !this.filtered_) || this.node_.hasChild(key)\n );\n }\n\n /**\n * @return {!Node}\n */\n getNode(): Node {\n return this.node_;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/CacheNode.ts","/**\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\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { CacheNode } from './CacheNode';\nimport { Node } from '../snap/Node';\n\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 */\nexport class ViewCache {\n /**\n *\n * @param {!CacheNode} eventCache_\n * @param {!CacheNode} serverCache_\n */\n constructor(\n private readonly eventCache_: CacheNode,\n private readonly serverCache_: CacheNode\n ) {}\n\n /**\n * @const\n * @type {ViewCache}\n */\n static Empty = new ViewCache(\n new CacheNode(\n ChildrenNode.EMPTY_NODE,\n /*fullyInitialized=*/ false,\n /*filtered=*/ false\n ),\n new CacheNode(\n ChildrenNode.EMPTY_NODE,\n /*fullyInitialized=*/ false,\n /*filtered=*/ false\n )\n );\n\n /**\n * @param {!Node} eventSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n updateEventSnap(\n eventSnap: Node,\n complete: boolean,\n filtered: boolean\n ): ViewCache {\n return new ViewCache(\n new CacheNode(eventSnap, complete, filtered),\n this.serverCache_\n );\n }\n\n /**\n * @param {!Node} serverSnap\n * @param {boolean} complete\n * @param {boolean} filtered\n * @return {!ViewCache}\n */\n updateServerSnap(\n serverSnap: Node,\n complete: boolean,\n filtered: boolean\n ): ViewCache {\n return new ViewCache(\n this.eventCache_,\n new CacheNode(serverSnap, complete, filtered)\n );\n }\n\n /**\n * @return {!CacheNode}\n */\n getEventCache(): CacheNode {\n return this.eventCache_;\n }\n\n /**\n * @return {?Node}\n */\n getCompleteEventSnap(): Node | null {\n return this.eventCache_.isFullyInitialized()\n ? this.eventCache_.getNode()\n : null;\n }\n\n /**\n * @return {!CacheNode}\n */\n getServerCache(): CacheNode {\n return this.serverCache_;\n }\n\n /**\n * @return {?Node}\n */\n getCompleteServerSnap(): Node | null {\n return this.serverCache_.isFullyInitialized()\n ? this.serverCache_.getNode()\n : null;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/ViewCache.ts","/**\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\nimport { getValues, safeGet } from '../../../utils/obj';\nimport { Change } from './Change';\nimport { assert, assertionError } from '../../../utils/assert';\n\n/**\n * @constructor\n */\nexport class ChildChangeAccumulator {\n private changeMap_: { [k: string]: Change } = {};\n\n /**\n * @param {!Change} change\n */\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey /** @type {!string} */ = change.childName;\n assert(\n type == Change.CHILD_ADDED ||\n type == Change.CHILD_CHANGED ||\n type == Change.CHILD_REMOVED,\n 'Only child changes supported for tracking'\n );\n assert(\n childKey !== '.priority',\n 'Only non-priority child changes can be tracked.'\n );\n const oldChange = safeGet(this.changeMap_, childKey) as Change;\n if (oldChange) {\n const oldType = oldChange.type;\n if (type == Change.CHILD_ADDED && oldType == Change.CHILD_REMOVED) {\n this.changeMap_[childKey] = Change.childChangedChange(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n );\n } else if (\n type == Change.CHILD_REMOVED &&\n oldType == Change.CHILD_ADDED\n ) {\n delete this.changeMap_[childKey];\n } else if (\n type == Change.CHILD_REMOVED &&\n oldType == Change.CHILD_CHANGED\n ) {\n this.changeMap_[childKey] = Change.childRemovedChange(\n childKey,\n oldChange.oldSnap\n );\n } else if (\n type == Change.CHILD_CHANGED &&\n oldType == Change.CHILD_ADDED\n ) {\n this.changeMap_[childKey] = Change.childAddedChange(\n childKey,\n change.snapshotNode\n );\n } else if (\n type == Change.CHILD_CHANGED &&\n oldType == Change.CHILD_CHANGED\n ) {\n this.changeMap_[childKey] = Change.childChangedChange(\n childKey,\n change.snapshotNode,\n oldChange.oldSnap\n );\n } else {\n throw assertionError(\n 'Illegal combination of changes: ' +\n change +\n ' occurred after ' +\n oldChange\n );\n }\n } else {\n this.changeMap_[childKey] = change;\n }\n }\n\n /**\n * @return {!Array.}\n */\n getChanges(): Change[] {\n return getValues(this.changeMap_);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/ChildChangeAccumulator.ts","/**\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\nimport { CacheNode } from './CacheNode';\nimport { NamedNode, Node } from '../snap/Node';\nimport { Index } from '../snap/indexes/Index';\nimport { WriteTreeRef } from '../WriteTree';\nimport { ViewCache } from './ViewCache';\n\n/**\n * Since updates to filtered nodes might require nodes to be pulled in from \"outside\" the node, this interface\n * can help to get complete children that can be pulled in.\n * A class implementing this interface takes potentially multiple sources (e.g. user writes, server data from\n * other views etc.) to try it's best to get a complete child that might be useful in pulling into the view.\n *\n * @interface\n */\nexport interface CompleteChildSource {\n /**\n * @param {!string} childKey\n * @return {?Node}\n */\n getCompleteChild(childKey: string): Node | null;\n\n /**\n * @param {!Index} index\n * @param {!NamedNode} child\n * @param {boolean} reverse\n * @return {?NamedNode}\n */\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null;\n}\n\n/**\n * An implementation of CompleteChildSource that never returns any additional children\n *\n * @private\n * @constructor\n * @implements CompleteChildSource\n */\nexport class NoCompleteChildSource_ implements CompleteChildSource {\n /**\n * @inheritDoc\n */\n getCompleteChild(childKey?: string): Node | null {\n return null;\n }\n\n /**\n * @inheritDoc\n */\n getChildAfterChild(\n index?: Index,\n child?: NamedNode,\n reverse?: boolean\n ): NamedNode | null {\n return null;\n }\n}\n\n/**\n * Singleton instance.\n * @const\n * @type {!CompleteChildSource}\n */\nexport const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();\n\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 */\nexport class WriteTreeCompleteChildSource implements CompleteChildSource {\n /**\n * @param {!WriteTreeRef} writes_\n * @param {!ViewCache} viewCache_\n * @param {?Node} optCompleteServerCache_\n */\n constructor(\n private writes_: WriteTreeRef,\n private viewCache_: ViewCache,\n private optCompleteServerCache_: Node | null = null\n ) {}\n\n /**\n * @inheritDoc\n */\n getCompleteChild(childKey: string): Node | null {\n const node = this.viewCache_.getEventCache();\n if (node.isCompleteForChild(childKey)) {\n return node.getNode().getImmediateChild(childKey);\n } else {\n const serverNode =\n this.optCompleteServerCache_ != null\n ? new CacheNode(this.optCompleteServerCache_, true, false)\n : this.viewCache_.getServerCache();\n return this.writes_.calcCompleteChild(childKey, serverNode);\n }\n }\n\n /**\n * @inheritDoc\n */\n getChildAfterChild(\n index: Index,\n child: NamedNode,\n reverse: boolean\n ): NamedNode | null {\n const completeServerData =\n this.optCompleteServerCache_ != null\n ? this.optCompleteServerCache_\n : this.viewCache_.getCompleteServerSnap();\n const nodes = this.writes_.calcIndexedSlice(\n completeServerData,\n child,\n 1,\n reverse,\n index\n );\n if (nodes.length === 0) {\n return null;\n } else {\n return nodes[0];\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/CompleteChildSource.ts","/**\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\nimport { Operation, OperationType } from '../operation/Operation';\nimport { assert, assertionError } from '../../../utils/assert';\nimport { ChildChangeAccumulator } from './ChildChangeAccumulator';\nimport { Change } from './Change';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { KEY_INDEX } from '../snap/indexes/KeyIndex';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport { Path } from '../util/Path';\nimport {\n WriteTreeCompleteChildSource,\n NO_COMPLETE_CHILD_SOURCE,\n CompleteChildSource\n} from './CompleteChildSource';\nimport { ViewCache } from './ViewCache';\nimport { NodeFilter } from './filter/NodeFilter';\nimport { WriteTreeRef } from '../WriteTree';\nimport { Overwrite } from '../operation/Overwrite';\nimport { Merge } from '../operation/Merge';\nimport { AckUserWrite } from '../operation/AckUserWrite';\nimport { Node } from '../snap/Node';\n\n/**\n * @constructor\n * @struct\n */\nexport class ProcessorResult {\n /**\n * @param {!ViewCache} viewCache\n * @param {!Array.} changes\n */\n constructor(\n public readonly viewCache: ViewCache,\n public readonly changes: Change[]\n ) {}\n}\n\n/**\n * @constructor\n */\nexport class ViewProcessor {\n /**\n * @param {!NodeFilter} filter_\n */\n constructor(private readonly filter_: NodeFilter) {}\n\n /**\n * @param {!ViewCache} viewCache\n */\n assertIndexed(viewCache: ViewCache) {\n assert(\n viewCache.getEventCache().getNode().isIndexed(this.filter_.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache.getServerCache().getNode().isIndexed(this.filter_.getIndex()),\n 'Server snap not indexed'\n );\n }\n\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} completeCache\n * @return {!ProcessorResult}\n */\n applyOperation(\n oldViewCache: ViewCache,\n operation: Operation,\n writesCache: WriteTreeRef,\n completeCache: Node | null\n ): ProcessorResult {\n const accumulator = new ChildChangeAccumulator();\n let newViewCache, filterServerNode;\n if (operation.type === OperationType.OVERWRITE) {\n const overwrite = operation as Overwrite;\n if (overwrite.source.fromUser) {\n newViewCache = this.applyUserOverwrite_(\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n 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_(\n oldViewCache,\n overwrite.path,\n overwrite.snap,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.MERGE) {\n const merge = operation as Merge;\n if (merge.source.fromUser) {\n newViewCache = this.applyUserMerge_(\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n 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_(\n oldViewCache,\n merge.path,\n merge.children,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\n } else if (operation.type === OperationType.ACK_USER_WRITE) {\n const ackUserWrite = operation as AckUserWrite;\n if (!ackUserWrite.revert) {\n newViewCache = this.ackUserWrite_(\n oldViewCache,\n ackUserWrite.path,\n ackUserWrite.affectedTree,\n writesCache,\n completeCache,\n accumulator\n );\n } else {\n newViewCache = this.revertUserWrite_(\n oldViewCache,\n ackUserWrite.path,\n writesCache,\n completeCache,\n accumulator\n );\n }\n } else if (operation.type === OperationType.LISTEN_COMPLETE) {\n newViewCache = this.listenComplete_(\n oldViewCache,\n operation.path,\n writesCache,\n accumulator\n );\n } else {\n throw assertionError('Unknown operation type: ' + operation.type);\n }\n const changes = accumulator.getChanges();\n ViewProcessor.maybeAddValueEvent_(oldViewCache, newViewCache, changes);\n return new ProcessorResult(newViewCache, changes);\n }\n\n /**\n * @param {!ViewCache} oldViewCache\n * @param {!ViewCache} newViewCache\n * @param {!Array.} accumulator\n * @private\n */\n private static maybeAddValueEvent_(\n oldViewCache: ViewCache,\n newViewCache: ViewCache,\n accumulator: Change[]\n ) {\n const eventSnap = newViewCache.getEventCache();\n if (eventSnap.isFullyInitialized()) {\n const isLeafOrEmpty =\n eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();\n const oldCompleteSnap = oldViewCache.getCompleteEventSnap();\n if (\n accumulator.length > 0 ||\n !oldViewCache.getEventCache().isFullyInitialized() ||\n (isLeafOrEmpty &&\n !eventSnap.getNode().equals /** @type {!Node} */(oldCompleteSnap)) ||\n !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())\n ) {\n accumulator.push(\n Change.valueChange(\n /** @type {!Node} */ newViewCache.getCompleteEventSnap()\n )\n );\n }\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 private generateEventCacheAfterServerEvent_(\n viewCache: ViewCache,\n changePath: Path,\n writesCache: WriteTreeRef,\n source: CompleteChildSource,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\n const oldEventSnap = viewCache.getEventCache();\n if (writesCache.shadowingWrite(changePath) != null) {\n // we have a shadowing write, ignore changes\n return viewCache;\n } else {\n let newEventCache, serverNode;\n if (changePath.isEmpty()) {\n // TODO: figure out how this plays with \"sliding ack windows\"\n assert(\n viewCache.getServerCache().isFullyInitialized(),\n 'If change path is empty, we must have complete server data'\n );\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 const serverCache = viewCache.getCompleteServerSnap();\n const completeChildren =\n serverCache instanceof ChildrenNode\n ? serverCache\n : ChildrenNode.EMPTY_NODE;\n const completeEventChildren = writesCache.calcCompleteEventChildren(\n completeChildren\n );\n newEventCache = this.filter_.updateFullNode(\n viewCache.getEventCache().getNode(),\n completeEventChildren,\n accumulator\n );\n } else {\n const completeNode = writesCache.calcCompleteEventCache(\n viewCache.getCompleteServerSnap()\n );\n newEventCache = this.filter_.updateFullNode(\n viewCache.getEventCache().getNode(),\n completeNode,\n accumulator\n );\n }\n } else {\n const childKey = changePath.getFront();\n if (childKey == '.priority') {\n assert(\n changePath.getLength() == 1,\n \"Can't have a priority with additional path components\"\n );\n const oldEventNode = oldEventSnap.getNode();\n serverNode = viewCache.getServerCache().getNode();\n // we might have overwrites for this priority\n const updatedPriority = writesCache.calcEventCacheAfterServerOverwrite(\n changePath,\n oldEventNode,\n serverNode\n );\n if (updatedPriority != null) {\n newEventCache = this.filter_.updatePriority(\n oldEventNode,\n updatedPriority\n );\n } else {\n // priority didn't change, keep old node\n newEventCache = oldEventSnap.getNode();\n }\n } else {\n const childChangePath = changePath.popFront();\n // update child\n let newEventChild;\n if (oldEventSnap.isCompleteForChild(childKey)) {\n serverNode = viewCache.getServerCache().getNode();\n const eventChildUpdate = writesCache.calcEventCacheAfterServerOverwrite(\n changePath,\n oldEventSnap.getNode(),\n serverNode\n );\n if (eventChildUpdate != null) {\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey)\n .updateChild(childChangePath, eventChildUpdate);\n } else {\n // Nothing changed, just keep the old child\n newEventChild = oldEventSnap\n .getNode()\n .getImmediateChild(childKey);\n }\n } else {\n newEventChild = writesCache.calcCompleteChild(\n childKey,\n viewCache.getServerCache()\n );\n }\n if (newEventChild != null) {\n newEventCache = this.filter_.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newEventChild,\n childChangePath,\n source,\n accumulator\n );\n } else {\n // no complete child available or no change\n newEventCache = oldEventSnap.getNode();\n }\n }\n }\n return viewCache.updateEventSnap(\n newEventCache,\n oldEventSnap.isFullyInitialized() || changePath.isEmpty(),\n this.filter_.filtersNodes()\n );\n }\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 applyServerOverwrite_(\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\n const oldServerSnap = oldViewCache.getServerCache();\n let newServerCache;\n const serverFilter = filterServerNode\n ? this.filter_\n : this.filter_.getIndexedFilter();\n if (changePath.isEmpty()) {\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n changedSnap,\n 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 const newServerNode = oldServerSnap\n .getNode()\n .updateChild(changePath, changedSnap);\n newServerCache = serverFilter.updateFullNode(\n oldServerSnap.getNode(),\n newServerNode,\n null\n );\n } else {\n const childKey = changePath.getFront();\n if (\n !oldServerSnap.isCompleteForPath(changePath) &&\n changePath.getLength() > 1\n ) {\n // We don't update incomplete nodes with updates intended for other listeners\n return oldViewCache;\n }\n const childChangePath = changePath.popFront();\n const childNode = oldServerSnap.getNode().getImmediateChild(childKey);\n const newChildNode = childNode.updateChild(childChangePath, changedSnap);\n if (childKey == '.priority') {\n newServerCache = serverFilter.updatePriority(\n oldServerSnap.getNode(),\n newChildNode\n );\n } else {\n newServerCache = serverFilter.updateChild(\n oldServerSnap.getNode(),\n childKey,\n newChildNode,\n childChangePath,\n NO_COMPLETE_CHILD_SOURCE,\n null\n );\n }\n }\n const newViewCache = oldViewCache.updateServerSnap(\n newServerCache,\n oldServerSnap.isFullyInitialized() || changePath.isEmpty(),\n serverFilter.filtersNodes()\n );\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n newViewCache,\n completeCache\n );\n return this.generateEventCacheAfterServerEvent_(\n newViewCache,\n changePath,\n writesCache,\n source,\n accumulator\n );\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 {!ChildChangeAccumulator} accumulator\n * @return {!ViewCache}\n * @private\n */\n applyUserOverwrite_(\n oldViewCache: ViewCache,\n changePath: Path,\n changedSnap: Node,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\n const oldEventSnap = oldViewCache.getEventCache();\n let newViewCache, newEventCache;\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n oldViewCache,\n completeCache\n );\n if (changePath.isEmpty()) {\n newEventCache = this.filter_.updateFullNode(\n oldViewCache.getEventCache().getNode(),\n changedSnap,\n accumulator\n );\n newViewCache = oldViewCache.updateEventSnap(\n newEventCache,\n true,\n this.filter_.filtersNodes()\n );\n } else {\n const childKey = changePath.getFront();\n if (childKey === '.priority') {\n newEventCache = this.filter_.updatePriority(\n oldViewCache.getEventCache().getNode(),\n changedSnap\n );\n newViewCache = oldViewCache.updateEventSnap(\n newEventCache,\n oldEventSnap.isFullyInitialized(),\n oldEventSnap.isFiltered()\n );\n } else {\n const childChangePath = changePath.popFront();\n const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);\n let newChild;\n if (childChangePath.isEmpty()) {\n // Child overwrite, we can replace the child\n newChild = changedSnap;\n } else {\n const childNode = source.getCompleteChild(childKey);\n if (childNode != null) {\n if (\n childChangePath.getBack() === '.priority' &&\n childNode.getChild(childChangePath.parent()).isEmpty()\n ) {\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 } else {\n newChild = childNode.updateChild(childChangePath, changedSnap);\n }\n } else {\n // There is no complete child node available\n newChild = ChildrenNode.EMPTY_NODE;\n }\n }\n if (!oldChild.equals(newChild)) {\n const newEventSnap = this.filter_.updateChild(\n oldEventSnap.getNode(),\n childKey,\n newChild,\n childChangePath,\n source,\n accumulator\n );\n newViewCache = oldViewCache.updateEventSnap(\n newEventSnap,\n oldEventSnap.isFullyInitialized(),\n this.filter_.filtersNodes()\n );\n } else {\n newViewCache = oldViewCache;\n }\n }\n }\n return newViewCache;\n }\n\n /**\n * @param {!ViewCache} viewCache\n * @param {string} childKey\n * @return {boolean}\n * @private\n */\n private static cacheHasChild_(\n viewCache: ViewCache,\n childKey: string\n ): boolean {\n return viewCache.getEventCache().isCompleteForChild(childKey);\n }\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 private applyUserMerge_(\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\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 let curViewCache = viewCache;\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = path.child(relativePath);\n if (ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = this.applyUserOverwrite_(\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n changedChildren.foreach((relativePath, childNode) => {\n const writePath = path.child(relativePath);\n if (!ViewProcessor.cacheHasChild_(viewCache, writePath.getFront())) {\n curViewCache = this.applyUserOverwrite_(\n curViewCache,\n writePath,\n childNode,\n writesCache,\n serverCache,\n accumulator\n );\n }\n });\n\n return curViewCache;\n }\n\n /**\n * @param {!Node} node\n * @param {ImmutableTree.} merge\n * @return {!Node}\n * @private\n */\n private applyMerge_(node: Node, merge: ImmutableTree): Node {\n merge.foreach(function(relativePath, childNode) {\n node = node.updateChild(relativePath, childNode);\n });\n return node;\n }\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 private applyServerMerge_(\n viewCache: ViewCache,\n path: Path,\n changedChildren: ImmutableTree,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n filterServerNode: boolean,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\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 (\n viewCache.getServerCache().getNode().isEmpty() &&\n !viewCache.getServerCache().isFullyInitialized()\n ) {\n return viewCache;\n }\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 let curViewCache = viewCache;\n let viewMergeTree;\n if (path.isEmpty()) {\n viewMergeTree = changedChildren;\n } else {\n viewMergeTree = ImmutableTree.Empty.setTree(path, changedChildren);\n }\n const serverNode = viewCache.getServerCache().getNode();\n viewMergeTree.children.inorderTraversal((childKey, childTree) => {\n if (serverNode.hasChild(childKey)) {\n const serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n const newChild = this.applyMerge_(serverChild, childTree);\n curViewCache = this.applyServerOverwrite_(\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {\n const isUnknownDeepMerge =\n !viewCache.getServerCache().isCompleteForChild(childKey) &&\n childMergeTree.value == null;\n if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {\n const serverChild = viewCache\n .getServerCache()\n .getNode()\n .getImmediateChild(childKey);\n const newChild = this.applyMerge_(serverChild, childMergeTree);\n curViewCache = this.applyServerOverwrite_(\n curViewCache,\n new Path(childKey),\n newChild,\n writesCache,\n serverCache,\n filterServerNode,\n accumulator\n );\n }\n });\n\n return curViewCache;\n }\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 private ackUserWrite_(\n viewCache: ViewCache,\n ackPath: Path,\n affectedTree: ImmutableTree,\n writesCache: WriteTreeRef,\n completeCache: Node | null,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\n if (writesCache.shadowingWrite(ackPath) != null) {\n return viewCache;\n }\n\n // Only filter server node if it is currently filtered\n const filterServerNode = viewCache.getServerCache().isFiltered();\n\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 const serverCache = viewCache.getServerCache();\n if (affectedTree.value != null) {\n // This is an overwrite.\n if (\n (ackPath.isEmpty() && serverCache.isFullyInitialized()) ||\n serverCache.isCompleteForPath(ackPath)\n ) {\n return this.applyServerOverwrite_(\n viewCache,\n ackPath,\n serverCache.getNode().getChild(ackPath),\n writesCache,\n completeCache,\n filterServerNode,\n 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 let changedChildren = ImmutableTree.Empty;\n serverCache.getNode().forEachChild(KEY_INDEX, function(name, node) {\n changedChildren = changedChildren.set(new Path(name), node);\n });\n return this.applyServerMerge_(\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n } else {\n return viewCache;\n }\n } else {\n // This is a merge.\n let changedChildren = ImmutableTree.Empty;\n affectedTree.foreach(function(mergePath, value) {\n const serverCachePath = ackPath.child(mergePath);\n if (serverCache.isCompleteForPath(serverCachePath)) {\n changedChildren = changedChildren.set(\n mergePath,\n serverCache.getNode().getChild(serverCachePath)\n );\n }\n });\n return this.applyServerMerge_(\n viewCache,\n ackPath,\n changedChildren,\n writesCache,\n completeCache,\n filterServerNode,\n accumulator\n );\n }\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 private listenComplete_(\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\n const oldServerNode = viewCache.getServerCache();\n const newViewCache = viewCache.updateServerSnap(\n oldServerNode.getNode(),\n oldServerNode.isFullyInitialized() || path.isEmpty(),\n oldServerNode.isFiltered()\n );\n return this.generateEventCacheAfterServerEvent_(\n newViewCache,\n path,\n writesCache,\n NO_COMPLETE_CHILD_SOURCE,\n accumulator\n );\n }\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 private revertUserWrite_(\n viewCache: ViewCache,\n path: Path,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null,\n accumulator: ChildChangeAccumulator\n ): ViewCache {\n let complete;\n if (writesCache.shadowingWrite(path) != null) {\n return viewCache;\n } else {\n const source = new WriteTreeCompleteChildSource(\n writesCache,\n viewCache,\n completeServerCache\n );\n const oldEventCache = viewCache.getEventCache().getNode();\n let newEventCache;\n if (path.isEmpty() || path.getFront() === '.priority') {\n let newNode;\n if (viewCache.getServerCache().isFullyInitialized()) {\n newNode = writesCache.calcCompleteEventCache(\n viewCache.getCompleteServerSnap()\n );\n } else {\n const serverChildren = viewCache.getServerCache().getNode();\n assert(\n serverChildren instanceof ChildrenNode,\n 'serverChildren would be complete if leaf node'\n );\n newNode = writesCache.calcCompleteEventChildren(\n serverChildren as ChildrenNode\n );\n }\n newNode = newNode as Node;\n newEventCache = this.filter_.updateFullNode(\n oldEventCache,\n newNode,\n accumulator\n );\n } else {\n const childKey = path.getFront();\n let newChild = writesCache.calcCompleteChild(\n childKey,\n viewCache.getServerCache()\n );\n if (\n newChild == null &&\n viewCache.getServerCache().isCompleteForChild(childKey)\n ) {\n newChild = oldEventCache.getImmediateChild(childKey);\n }\n if (newChild != null) {\n newEventCache = this.filter_.updateChild(\n oldEventCache,\n childKey,\n newChild,\n path.popFront(),\n source,\n accumulator\n );\n } else if (viewCache.getEventCache().getNode().hasChild(childKey)) {\n // No complete child available, delete the existing one, if any\n newEventCache = this.filter_.updateChild(\n oldEventCache,\n childKey,\n ChildrenNode.EMPTY_NODE,\n path.popFront(),\n source,\n accumulator\n );\n } else {\n newEventCache = oldEventCache;\n }\n if (\n newEventCache.isEmpty() &&\n viewCache.getServerCache().isFullyInitialized()\n ) {\n // We might have reverted all child writes. Maybe the old event was a leaf node\n complete = writesCache.calcCompleteEventCache(\n viewCache.getCompleteServerSnap()\n );\n if (complete.isLeafNode()) {\n newEventCache = this.filter_.updateFullNode(\n newEventCache,\n complete,\n accumulator\n );\n }\n }\n }\n complete =\n viewCache.getServerCache().isFullyInitialized() ||\n writesCache.shadowingWrite(Path.Empty) != null;\n return viewCache.updateEventSnap(\n newEventCache,\n complete,\n this.filter_.filtersNodes()\n );\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/ViewProcessor.ts","/**\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\nimport { NamedNode, Node } from '../snap/Node';\nimport { Change } from './Change';\nimport { assertionError } from '../../../utils/assert';\nimport { Query } from '../../api/Query';\nimport { Index } from '../snap/indexes/Index';\nimport { EventRegistration } from './EventRegistration';\nimport { Event } from './Event';\n\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 */\nexport class EventGenerator {\n private index_: Index;\n\n /**\n *\n * @param {!Query} query_\n */\n constructor(private query_: Query) {\n /**\n * @private\n * @type {!Index}\n */\n this.index_ = this.query_.getQueryParams().getIndex();\n }\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 generateEventsForChanges(\n changes: Change[],\n eventCache: Node,\n eventRegistrations: EventRegistration[]\n ): Event[] {\n const events: Event[] = [];\n const moves: Change[] = [];\n\n changes.forEach(change => {\n if (\n change.type === Change.CHILD_CHANGED &&\n this.index_.indexedValueChanged(\n change.oldSnap as Node,\n change.snapshotNode\n )\n ) {\n moves.push(\n Change.childMovedChange(\n change.childName as string,\n change.snapshotNode\n )\n );\n }\n });\n\n this.generateEventsForType_(\n events,\n Change.CHILD_REMOVED,\n changes,\n eventRegistrations,\n eventCache\n );\n this.generateEventsForType_(\n events,\n Change.CHILD_ADDED,\n changes,\n eventRegistrations,\n eventCache\n );\n this.generateEventsForType_(\n events,\n Change.CHILD_MOVED,\n moves,\n eventRegistrations,\n eventCache\n );\n this.generateEventsForType_(\n events,\n Change.CHILD_CHANGED,\n changes,\n eventRegistrations,\n eventCache\n );\n this.generateEventsForType_(\n events,\n Change.VALUE,\n changes,\n eventRegistrations,\n eventCache\n );\n\n return events;\n }\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 private generateEventsForType_(\n events: Event[],\n eventType: string,\n changes: Change[],\n registrations: EventRegistration[],\n eventCache: Node\n ) {\n const filteredChanges = changes.filter(change => change.type === eventType);\n\n filteredChanges.sort(this.compareChanges_.bind(this));\n filteredChanges.forEach(change => {\n const materializedChange = this.materializeSingleChange_(\n change,\n eventCache\n );\n registrations.forEach(registration => {\n if (registration.respondsTo(change.type)) {\n events.push(\n registration.createEvent(materializedChange, this.query_)\n );\n }\n });\n });\n }\n\n /**\n * @param {!Change} change\n * @param {!Node} eventCache\n * @return {!Change}\n * @private\n */\n private materializeSingleChange_(change: Change, eventCache: Node): Change {\n if (change.type === 'value' || change.type === 'child_removed') {\n return change;\n } else {\n change.prevName = eventCache.getPredecessorChildName(\n /** @type {!string} */\n change.childName,\n change.snapshotNode,\n this.index_\n );\n return change;\n }\n }\n\n /**\n * @param {!Change} a\n * @param {!Change} b\n * @return {number}\n * @private\n */\n private compareChanges_(a: Change, b: Change) {\n if (a.childName == null || b.childName == null) {\n throw assertionError('Should only compare child_ events.');\n }\n const aWrapped = new NamedNode(a.childName, a.snapshotNode);\n const bWrapped = new NamedNode(b.childName, b.snapshotNode);\n return this.index_.compare(aWrapped, bWrapped);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/EventGenerator.ts","/**\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\nimport { IndexedFilter } from './filter/IndexedFilter';\nimport { ViewProcessor } from './ViewProcessor';\nimport { ChildrenNode } from '../snap/ChildrenNode';\nimport { CacheNode } from './CacheNode';\nimport { ViewCache } from './ViewCache';\nimport { EventGenerator } from './EventGenerator';\nimport { assert } from '../../../utils/assert';\nimport { Operation, OperationType } from '../operation/Operation';\nimport { Change } from './Change';\nimport { PRIORITY_INDEX } from '../snap/indexes/PriorityIndex';\nimport { Query } from '../../api/Query';\nimport { EventRegistration } from './EventRegistration';\nimport { Node } from '../snap/Node';\nimport { Path } from '../util/Path';\nimport { WriteTreeRef } from '../WriteTree';\nimport { CancelEvent, Event } from './Event';\n\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 */\nexport class View {\n private processor_: ViewProcessor;\n private viewCache_: ViewCache;\n private eventRegistrations_: EventRegistration[] = [];\n private eventGenerator_: EventGenerator;\n\n /**\n *\n * @param {!Query} query_\n * @param {!ViewCache} initialViewCache\n */\n constructor(private query_: Query, initialViewCache: ViewCache) {\n const params = this.query_.getQueryParams();\n\n const indexFilter = new IndexedFilter(params.getIndex());\n const filter = params.getNodeFilter();\n\n /**\n * @type {ViewProcessor}\n * @private\n */\n this.processor_ = new ViewProcessor(filter);\n\n const initialServerCache = initialViewCache.getServerCache();\n const initialEventCache = initialViewCache.getEventCache();\n\n // Don't filter server node with other filter than index, wait for tagged listen\n const serverSnap = indexFilter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialServerCache.getNode(),\n null\n );\n const eventSnap = filter.updateFullNode(\n ChildrenNode.EMPTY_NODE,\n initialEventCache.getNode(),\n null\n );\n const newServerCache = new CacheNode(\n serverSnap,\n initialServerCache.isFullyInitialized(),\n indexFilter.filtersNodes()\n );\n const newEventCache = new CacheNode(\n eventSnap,\n initialEventCache.isFullyInitialized(),\n filter.filtersNodes()\n );\n\n /**\n * @type {!ViewCache}\n * @private\n */\n this.viewCache_ = new ViewCache(newEventCache, newServerCache);\n\n /**\n * @type {!EventGenerator}\n * @private\n */\n this.eventGenerator_ = new EventGenerator(this.query_);\n }\n\n /**\n * @return {!Query}\n */\n getQuery(): Query {\n return this.query_;\n }\n\n /**\n * @return {?Node}\n */\n getServerCache(): Node | null {\n return this.viewCache_.getServerCache().getNode();\n }\n\n /**\n * @param {!Path} path\n * @return {?Node}\n */\n getCompleteServerCache(path: Path): Node | null {\n const 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 (\n this.query_.getQueryParams().loadsAllData() ||\n (!path.isEmpty() && !cache.getImmediateChild(path.getFront()).isEmpty())\n ) {\n return cache.getChild(path);\n }\n }\n return null;\n }\n\n /**\n * @return {boolean}\n */\n isEmpty(): boolean {\n return this.eventRegistrations_.length === 0;\n }\n\n /**\n * @param {!EventRegistration} eventRegistration\n */\n addEventRegistration(eventRegistration: EventRegistration) {\n this.eventRegistrations_.push(eventRegistration);\n }\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 removeEventRegistration(\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n ): Event[] {\n const cancelEvents: CancelEvent[] = [];\n if (cancelError) {\n assert(\n eventRegistration == null,\n 'A cancel should cancel all event registrations.'\n );\n const path = this.query_.path;\n this.eventRegistrations_.forEach(function(registration) {\n cancelError /** @type {!Error} */ = cancelError;\n const maybeEvent = registration.createCancelEvent(cancelError, path);\n if (maybeEvent) {\n cancelEvents.push(maybeEvent);\n }\n });\n }\n\n if (eventRegistration) {\n let remaining = [];\n for (let i = 0; i < this.eventRegistrations_.length; ++i) {\n const existing = this.eventRegistrations_[i];\n if (!existing.matches(eventRegistration)) {\n remaining.push(existing);\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 } else {\n this.eventRegistrations_ = [];\n }\n return cancelEvents;\n }\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 applyOperation(\n operation: Operation,\n writesCache: WriteTreeRef,\n completeServerCache: Node | null\n ): Event[] {\n if (\n operation.type === OperationType.MERGE &&\n operation.source.queryId !== null\n ) {\n assert(\n this.viewCache_.getCompleteServerSnap(),\n 'We should always have a full cache before handling merges'\n );\n assert(\n this.viewCache_.getCompleteEventSnap(),\n 'Missing event cache, even though we have a server cache'\n );\n }\n\n const oldViewCache = this.viewCache_;\n const result = this.processor_.applyOperation(\n oldViewCache,\n operation,\n writesCache,\n completeServerCache\n );\n this.processor_.assertIndexed(result.viewCache);\n\n assert(\n result.viewCache.getServerCache().isFullyInitialized() ||\n !oldViewCache.getServerCache().isFullyInitialized(),\n 'Once a server snap is complete, it should never go back'\n );\n\n this.viewCache_ = result.viewCache;\n\n return this.generateEventsForChanges_(\n result.changes,\n result.viewCache.getEventCache().getNode(),\n null\n );\n }\n\n /**\n * @param {!EventRegistration} registration\n * @return {!Array.}\n */\n getInitialEvents(registration: EventRegistration): Event[] {\n const eventSnap = this.viewCache_.getEventCache();\n const initialChanges: Change[] = [];\n if (!eventSnap.getNode().isLeafNode()) {\n const eventNode = eventSnap.getNode() as ChildrenNode;\n eventNode.forEachChild(PRIORITY_INDEX, function(key, childNode) {\n initialChanges.push(Change.childAddedChange(key, childNode));\n });\n }\n if (eventSnap.isFullyInitialized()) {\n initialChanges.push(Change.valueChange(eventSnap.getNode()));\n }\n return this.generateEventsForChanges_(\n initialChanges,\n eventSnap.getNode(),\n registration\n );\n }\n\n /**\n * @private\n * @param {!Array.} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.}\n */\n generateEventsForChanges_(\n changes: Change[],\n eventCache: Node,\n eventRegistration?: EventRegistration\n ): Event[] {\n const registrations = eventRegistration\n ? [eventRegistration]\n : this.eventRegistrations_;\n return this.eventGenerator_.generateEventsForChanges(\n changes,\n eventCache,\n registrations\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/view/View.ts","/**\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\nimport { CacheNode } from './view/CacheNode';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { assert } from '../../utils/assert';\nimport { isEmpty, forEach, findValue, safeGet } from '../../utils/obj';\nimport { ViewCache } from './view/ViewCache';\nimport { View } from './view/View';\nimport { Operation } from './operation/Operation';\nimport { WriteTreeRef } from './WriteTree';\nimport { Query } from '../api/Query';\nimport { EventRegistration } from './view/EventRegistration';\nimport { Node } from './snap/Node';\nimport { Path } from './util/Path';\nimport { Event } from './view/Event';\nimport { Reference, ReferenceConstructor } from '../api/Reference';\n\nlet __referenceConstructor: ReferenceConstructor;\n\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 */\nexport class SyncPoint {\n static set __referenceConstructor(val: ReferenceConstructor) {\n assert(\n !__referenceConstructor,\n '__referenceConstructor has already been defined'\n );\n __referenceConstructor = val;\n }\n\n static get __referenceConstructor() {\n assert(__referenceConstructor, 'Reference.ts has not been loaded');\n return __referenceConstructor;\n }\n\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 private views_: { [k: string]: View } = {};\n\n /**\n * @return {boolean}\n */\n isEmpty(): boolean {\n return isEmpty(this.views_);\n }\n\n /**\n *\n * @param {!Operation} operation\n * @param {!WriteTreeRef} writesCache\n * @param {?Node} optCompleteServerCache\n * @return {!Array.}\n */\n applyOperation(\n operation: Operation,\n writesCache: WriteTreeRef,\n optCompleteServerCache: Node | null\n ): Event[] {\n const queryId = operation.source.queryId;\n if (queryId !== null) {\n const view = safeGet(this.views_, queryId);\n assert(view != null, 'SyncTree gave us an op for an invalid query.');\n return view.applyOperation(\n operation,\n writesCache,\n optCompleteServerCache\n );\n } else {\n let events: Event[] = [];\n\n forEach(this.views_, function(key: string, view: View) {\n events = events.concat(\n view.applyOperation(operation, writesCache, optCompleteServerCache)\n );\n });\n\n return events;\n }\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 addEventRegistration(\n query: Query,\n eventRegistration: EventRegistration,\n writesCache: WriteTreeRef,\n serverCache: Node | null,\n serverCacheComplete: boolean\n ): Event[] {\n const queryId = query.queryIdentifier();\n let view = safeGet(this.views_, queryId);\n if (!view) {\n // TODO: make writesCache take flag for complete server node\n let eventCache = writesCache.calcCompleteEventCache(\n serverCacheComplete ? serverCache : null\n );\n let eventCacheComplete = false;\n if (eventCache) {\n eventCacheComplete = true;\n } else if (serverCache instanceof ChildrenNode) {\n eventCache = writesCache.calcCompleteEventChildren(serverCache);\n eventCacheComplete = false;\n } else {\n eventCache = ChildrenNode.EMPTY_NODE;\n eventCacheComplete = false;\n }\n const viewCache = new ViewCache(\n new CacheNode /** @type {!Node} */(\n eventCache,\n eventCacheComplete,\n false\n ),\n new CacheNode /** @type {!Node} */(\n serverCache,\n serverCacheComplete,\n false\n )\n );\n view = new View(query, viewCache);\n this.views_[queryId] = view;\n }\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 /**\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 removeEventRegistration(\n query: Query,\n eventRegistration: EventRegistration | null,\n cancelError?: Error\n ): { removed: Query[]; events: Event[] } {\n const queryId = query.queryIdentifier();\n const removed: Query[] = [];\n let cancelEvents: Event[] = [];\n const hadCompleteView = this.hasCompleteView();\n if (queryId === 'default') {\n // When you do ref.off(...), we search all views for the registration to remove.\n const self = this;\n forEach(this.views_, function(viewQueryId: string, view: View) {\n cancelEvents = cancelEvents.concat(\n view.removeEventRegistration(eventRegistration, cancelError)\n );\n if (view.isEmpty()) {\n delete self.views_[viewQueryId];\n\n // We'll deal with complete views later.\n if (!view.getQuery().getQueryParams().loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n });\n } else {\n // remove the callback from the specific view.\n const view = safeGet(this.views_, queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n view.removeEventRegistration(eventRegistration, cancelError)\n );\n if (view.isEmpty()) {\n delete this.views_[queryId];\n\n // We'll deal with complete views later.\n if (!view.getQuery().getQueryParams().loadsAllData()) {\n removed.push(view.getQuery());\n }\n }\n }\n }\n\n if (hadCompleteView && !this.hasCompleteView()) {\n // We removed our last complete view.\n removed.push(\n new SyncPoint.__referenceConstructor(query.repo, query.path)\n );\n }\n\n return { removed: removed, events: cancelEvents };\n }\n\n /**\n * @return {!Array.}\n */\n getQueryViews(): View[] {\n const values = Object.keys(this.views_).map(key => this.views_[key]);\n return values.filter(function(view) {\n return !view.getQuery().getQueryParams().loadsAllData();\n });\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 getCompleteServerCache(path: Path): Node | null {\n let serverCache: Node | null = null;\n forEach(this.views_, (key: string, view: View) => {\n serverCache = serverCache || view.getCompleteServerCache(path);\n });\n return serverCache;\n }\n\n /**\n * @param {!Query} query\n * @return {?View}\n */\n viewForQuery(query: Query): View | null {\n const params = query.getQueryParams();\n if (params.loadsAllData()) {\n return this.getCompleteView();\n } else {\n const queryId = query.queryIdentifier();\n return safeGet(this.views_, queryId);\n }\n }\n\n /**\n * @param {!Query} query\n * @return {boolean}\n */\n viewExistsForQuery(query: Query): boolean {\n return this.viewForQuery(query) != null;\n }\n\n /**\n * @return {boolean}\n */\n hasCompleteView(): boolean {\n return this.getCompleteView() != null;\n }\n\n /**\n * @return {?View}\n */\n getCompleteView(): View | null {\n const completeView = findValue(this.views_, (view: View) =>\n view.getQuery().getQueryParams().loadsAllData()\n );\n return completeView || null;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/SyncPoint.ts","/**\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\nimport { assert } from '../../../utils/assert';\n\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 */\nexport abstract class EventEmitter {\n private listeners_: {\n [eventType: string]: Array<{\n callback(...args: any[]): void;\n context: any;\n }>;\n } = {};\n\n /**\n * @param {!Array.} allowedEvents_\n */\n constructor(private allowedEvents_: Array) {\n assert(\n Array.isArray(allowedEvents_) && allowedEvents_.length > 0,\n 'Requires a non-empty array'\n );\n }\n\n /**\n * To be overridden by derived classes in order to fire an initial event when\n * somebody subscribes for data.\n *\n * @param {!string} eventType\n * @return {Array.<*>} Array of parameters to trigger initial event with.\n */\n abstract getInitialEvent(eventType: string): any[];\n\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} var_args\n */\n protected trigger(eventType: string, ...var_args: any[]) {\n if (Array.isArray(this.listeners_[eventType])) {\n // Clone the list, since callbacks could add/remove listeners.\n const listeners = [...this.listeners_[eventType]];\n\n for (let i = 0; i < listeners.length; i++) {\n listeners[i].callback.apply(listeners[i].context, var_args);\n }\n }\n }\n\n on(eventType: string, callback: (a: any) => void, context: any) {\n this.validateEventType_(eventType);\n this.listeners_[eventType] = this.listeners_[eventType] || [];\n this.listeners_[eventType].push({ callback, context });\n\n const eventData = this.getInitialEvent(eventType);\n if (eventData) {\n callback.apply(context, eventData);\n }\n }\n\n off(eventType: string, callback: (a: any) => void, context: any) {\n this.validateEventType_(eventType);\n const listeners = this.listeners_[eventType] || [];\n for (let i = 0; i < listeners.length; i++) {\n if (\n listeners[i].callback === callback &&\n (!context || context === listeners[i].context)\n ) {\n listeners.splice(i, 1);\n return;\n }\n }\n }\n\n private validateEventType_(eventType: string) {\n assert(\n this.allowedEvents_.find(function(et) {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/EventEmitter.ts","/**\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\nimport { EventEmitter } from './EventEmitter';\nimport { assert } from '../../../utils/assert';\n\ndeclare const document: any;\n\n/**\n * @extends {EventEmitter}\n */\nexport class VisibilityMonitor extends EventEmitter {\n private visible_: boolean;\n\n static getInstance() {\n return new VisibilityMonitor();\n }\n\n constructor() {\n super(['visible']);\n let hidden: string;\n let visibilityChange: string;\n if (\n typeof document !== 'undefined' &&\n typeof document.addEventListener !== 'undefined'\n ) {\n if (typeof document['hidden'] !== 'undefined') {\n // Opera 12.10 and Firefox 18 and later support\n visibilityChange = 'visibilitychange';\n hidden = 'hidden';\n } else if (typeof document['mozHidden'] !== 'undefined') {\n visibilityChange = 'mozvisibilitychange';\n hidden = 'mozHidden';\n } else if (typeof document['msHidden'] !== 'undefined') {\n visibilityChange = 'msvisibilitychange';\n hidden = 'msHidden';\n } else if (typeof document['webkitHidden'] !== 'undefined') {\n visibilityChange = 'webkitvisibilitychange';\n hidden = 'webkitHidden';\n }\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\n if (visibilityChange) {\n document.addEventListener(\n visibilityChange,\n () => {\n const visible = !document[hidden];\n if (visible !== this.visible_) {\n this.visible_ = visible;\n this.trigger('visible', visible);\n }\n },\n false\n );\n }\n }\n\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/VisibilityMonitor.ts","/**\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\nimport { assert } from '../../../utils/assert';\nimport { EventEmitter } from './EventEmitter';\nimport { isMobileCordova } from '../../../utils/environment';\n\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 */\nexport class OnlineMonitor extends EventEmitter {\n private online_ = true;\n\n static getInstance() {\n return new OnlineMonitor();\n }\n\n constructor() {\n super(['online']);\n\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 (\n typeof window !== 'undefined' &&\n typeof window.addEventListener !== 'undefined' &&\n !isMobileCordova()\n ) {\n window.addEventListener(\n 'online',\n () => {\n if (!this.online_) {\n this.online_ = true;\n this.trigger('online', true);\n }\n },\n false\n );\n\n window.addEventListener(\n 'offline',\n () => {\n if (this.online_) {\n this.online_ = false;\n this.trigger('online', false);\n }\n },\n false\n );\n }\n }\n\n /**\n * @param {!string} eventType\n * @return {Array.}\n */\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'online', 'Unknown event type: ' + eventType);\n return [this.online_];\n }\n\n /**\n * @return {boolean}\n */\n currentlyOnline(): boolean {\n return this.online_;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/util/OnlineMonitor.ts","/**\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\nimport { base64Decode } from '../database/core/util/util';\nimport { jsonEval } from './json';\n\n/**\n * Decodes a Firebase auth. token into constituent parts.\n *\n * Notes:\n * - May return with invalid / incomplete claims if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n *\n * @param {?string} token\n * @return {{header: *, claims: *, data: *, signature: string}}\n */\nexport const decode = function(token) {\n var header = {},\n claims = {},\n data = {},\n signature = '';\n\n try {\n var parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '');\n claims = jsonEval(base64Decode(parts[1]) || '');\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header: header,\n claims: claims,\n data: data,\n signature: signature\n };\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its time-based claims. Will return true if the\n * token is within the time window authorized by the 'nbf' (not-before) and 'iat' (issued-at) claims.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n *\n * @param {?string} token\n * @return {boolean}\n */\nexport const isValidTimestamp = function(token) {\n var claims = decode(token).claims,\n now = Math.floor(new Date().getTime() / 1000),\n validSince,\n validUntil;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'];\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'];\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'];\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n now && validSince && validUntil && now >= validSince && now <= validUntil\n );\n};\n\n/**\n * Decodes a Firebase auth. token and returns its issued at time if valid, null otherwise.\n *\n * Notes:\n * - May return null if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n *\n * @param {?string} token\n * @return {?number}\n */\nexport const issuedAtTime = function(token) {\n var claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'];\n }\n return null;\n};\n\n/**\n * Decodes a Firebase auth. token and checks the validity of its format. Expects a valid issued-at time and non-empty\n * signature.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n *\n * @param {?string} token\n * @return {boolean}\n */\nexport const isValidFormat = function(token) {\n var decoded = decode(token),\n claims = decoded.claims;\n\n return (\n !!decoded.signature &&\n !!claims &&\n typeof claims === 'object' &&\n claims.hasOwnProperty('iat')\n );\n};\n\n/**\n * Attempts to peer into an auth token and determine if it's an admin auth token by looking at the claims portion.\n *\n * Notes:\n * - May return a false negative if there's no native base64 decoding support.\n * - Doesn't check if the token is actually valid.\n *\n * @param {?string} token\n * @return {boolean}\n */\nexport const isAdmin = function(token) {\n var claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/utils/jwt.ts","/**\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\nimport firebase from '../../app';\nimport { forEach, contains, isEmpty, getCount, safeGet } from '../../utils/obj';\nimport { stringify } from '../../utils/json';\nimport { assert } from '../../utils/assert';\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { Path } from './util/Path';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { OnlineMonitor } from './util/OnlineMonitor';\nimport { isAdmin, isValidFormat } from '../../utils/jwt';\nimport { Connection } from '../realtime/Connection';\nimport { CONSTANTS } from '../../utils/constants';\nimport {\n isMobileCordova,\n isReactNative,\n isNodeSdk\n} from '../../utils/environment';\nimport { ServerActions } from './ServerActions';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { Query } from '../api/Query';\n\nconst RECONNECT_MIN_DELAY = 1000;\nconst RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\nconst RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\nconst RECONNECT_DELAY_MULTIPLIER = 1.3;\nconst RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\nconst SERVER_KILL_INTERRUPT_REASON = 'server_kill';\n\n// If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\nconst INVALID_AUTH_TOKEN_THRESHOLD = 3;\n\ninterface ListenSpec {\n onComplete(s: string, p?: any): void;\n\n hashFn(): string;\n\n query: Query;\n tag: number | null;\n}\n\ninterface OnDisconnectRequest {\n pathString: string;\n action: string;\n data: any;\n onComplete?: (a: string, b: string) => void;\n}\n\ninterface OutstandingPut {\n action: string;\n request: Object;\n queued?: boolean;\n onComplete: (a: string, b?: string) => void;\n}\n\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 */\nexport class PersistentConnection extends ServerActions {\n // Used for diagnostic logging.\n id = PersistentConnection.nextPersistentConnectionId_++;\n private log_ = logWrapper('p:' + this.id + ':');\n\n /** @private {Object} */\n private interruptReasons_: { [reason: string]: boolean } = {};\n private listens_: { [path: string]: { [queryId: string]: ListenSpec } } = {};\n private outstandingPuts_: OutstandingPut[] = [];\n private outstandingPutCount_ = 0;\n private onDisconnectRequestQueue_: OnDisconnectRequest[] = [];\n private connected_ = false;\n private reconnectDelay_ = RECONNECT_MIN_DELAY;\n private maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n private securityDebugCallback_: ((a: Object) => void) | null = null;\n lastSessionId: string | null = null;\n\n /** @private {number|null} */\n private establishConnectionTimer_: number | null = null;\n\n /** @private {boolean} */\n private visible_: boolean = false;\n\n // Before we get connected, we keep a queue of pending messages to send.\n private requestCBHash_: { [k: number]: (a: any) => void } = {};\n private requestNumber_ = 0;\n\n /** @private {?{\n * sendRequest(Object),\n * close()\n * }} */\n private realtime_: {\n sendRequest(a: Object): void;\n close(): void;\n } | null = null;\n\n /** @private {string|null} */\n private authToken_: string | null = null;\n private forceTokenRefresh_ = false;\n private invalidAuthTokenCount_ = 0;\n\n private firstConnection_ = true;\n private lastConnectionAttemptTime_: number | null = null;\n private lastConnectionEstablishedTime_: number | null = null;\n\n /**\n * @private\n */\n private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n * @type {number}\n * @private\n */\n private static nextConnectionId_ = 0;\n\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 constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: any,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: any) => void,\n private authTokenProvider_: AuthTokenProvider,\n private authOverride_?: Object | null\n ) {\n super();\n\n if (authOverride_ && !isNodeSdk()) {\n throw new Error(\n 'Auth override specified in options, but not supported on non Node.js platforms'\n );\n }\n this.scheduleConnect_(0);\n\n VisibilityMonitor.getInstance().on('visible', this.onVisible_, this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', this.onOnline_, this);\n }\n }\n\n /**\n * @param {!string} action\n * @param {*} body\n * @param {function(*)=} onResponse\n * @protected\n */\n protected sendRequest(\n action: string,\n body: any,\n onResponse?: (a: any) => void\n ) {\n const curReqNum = ++this.requestNumber_;\n\n const msg = { r: curReqNum, a: action, b: body };\n this.log_(stringify(msg));\n assert(\n this.connected_,\n \"sendRequest call when we're not connected not allowed.\"\n );\n this.realtime_.sendRequest(msg);\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n }\n\n /**\n * @inheritDoc\n */\n listen(\n query: Query,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: any) => void\n ) {\n const queryId = query.queryIdentifier();\n const pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n assert(\n query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(),\n 'listen() called for non-default but complete query'\n );\n assert(\n !this.listens_[pathString][queryId],\n 'listen() called twice for same path/queryId.'\n );\n const listenSpec: ListenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\n\n /**\n * @param {!{onComplete(),\n * hashFn():!string,\n * query: !Query,\n * tag: ?number}} listenSpec\n * @private\n */\n private sendListen_(listenSpec: ListenSpec) {\n const query = listenSpec.query;\n const pathString = query.path.toString();\n const queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n const req: { [k: string]: any } = { /*path*/ p: pathString };\n\n const action = 'q';\n\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\n req[/*hash*/ 'h'] = listenSpec.hashFn();\n\n this.sendRequest(action, req, (message: { [k: string]: any }) => {\n const payload: any = message[/*data*/ 'd'];\n const status: string = message[/*status*/ 's'];\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n 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\n if (status !== 'ok') {\n this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n }\n\n /**\n * @param {*} payload\n * @param {!Query} query\n * @private\n */\n private static warnOnListenWarnings_(payload: any, query: Query) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n const warnings = safeGet(payload, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' + query.getQueryParams().getIndex().toString() + '\"';\n const indexPath = query.path.toString();\n warn(\n `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\n /**\n * @inheritDoc\n */\n refreshAuthToken(token: string) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n if (this.authToken_) {\n this.tryAuth();\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', {}, () => {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n }\n\n /**\n * @param {!string} credential\n * @private\n */\n private reduceReconnectDelayIfAdminCredential_(credential: string) {\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 const isFirebaseSecret = credential && credential.length === 40;\n if (isFirebaseSecret || isAdmin(credential)) {\n this.log_(\n 'Admin auth credential detected. Reducing max reconnect time.'\n );\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\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 tryAuth() {\n if (this.connected_ && this.authToken_) {\n const token = this.authToken_;\n const authMethod = isValidFormat(token) ? 'auth' : 'gauth';\n const requestData: { [k: string]: any } = { cred: token };\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n this.sendRequest(authMethod, requestData, (res: { [k: string]: any }) => {\n const status: string = res[/*status*/ 's'];\n const data: string = res[/*data*/ 'd'] || 'error';\n\n if (this.authToken_ === token) {\n if (status === 'ok') {\n this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n unlisten(query: Query, tag: number | null) {\n const pathString = query.path.toString();\n const queryId = query.queryIdentifier();\n\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n\n assert(\n query.getQueryParams().isDefault() ||\n !query.getQueryParams().loadsAllData(),\n 'unlisten() called for non-default but complete query'\n );\n const listen = this.removeListen_(pathString, queryId);\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n }\n\n private sendUnlisten_(\n pathString: string,\n queryId: string,\n queryObj: Object,\n tag: number | null\n ) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n\n const req: { [k: string]: any } = { /*path*/ p: pathString };\n const 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\n this.sendRequest(action, req);\n }\n\n /**\n * @inheritDoc\n */\n onDisconnectPut(\n pathString: string,\n data: any,\n onComplete?: (a: string, b: string) => void\n ) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'o',\n data,\n onComplete\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n onDisconnectMerge(\n pathString: string,\n data: any,\n onComplete?: (a: string, b: string) => void\n ) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'om',\n data,\n onComplete\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString,\n action: 'oc',\n data: null,\n onComplete\n });\n }\n }\n\n private sendOnDisconnect_(\n action: string,\n pathString: string,\n data: any,\n onComplete: (a: string, b: string) => void\n ) {\n const request = { /*path*/ p: pathString, /*data*/ d: data };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, (response: { [k: string]: any }) => {\n if (onComplete) {\n setTimeout(function() {\n onComplete(response[/*status*/ 's'], response[/* data */ 'd']);\n }, Math.floor(0));\n }\n });\n }\n\n /**\n * @inheritDoc\n */\n put(\n pathString: string,\n data: any,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {\n this.putInternal('p', pathString, data, onComplete, hash);\n }\n\n /**\n * @inheritDoc\n */\n merge(\n pathString: string,\n data: any,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n this.putInternal('m', pathString, data, onComplete, hash);\n }\n\n putInternal(\n action: string,\n pathString: string,\n data: any,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n const request: { [k: string]: any } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) request[/*hash*/ 'h'] = hash;\n\n // TODO: Only keep track of the most recent put for a given path?\n this.outstandingPuts_.push({\n action,\n request,\n onComplete\n });\n\n this.outstandingPutCount_++;\n const index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n }\n\n private sendPut_(index: number) {\n const action = this.outstandingPuts_[index].action;\n const request = this.outstandingPuts_[index].request;\n const onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n\n this.sendRequest(action, request, (message: { [k: string]: any }) => {\n this.log_(action + ' response', message);\n\n delete this.outstandingPuts_[index];\n this.outstandingPutCount_--;\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n\n if (onComplete)\n onComplete(message[/*status*/ 's'], message[/* data */ 'd']);\n });\n }\n\n /**\n * @inheritDoc\n */\n reportStats(stats: { [k: string]: any }) {\n // If we're not connected, we just drop the stats.\n if (this.connected_) {\n const request = { /*counters*/ c: stats };\n this.log_('reportStats', request);\n\n this.sendRequest(/*stats*/ 's', request, result => {\n const status = result[/*status*/ 's'];\n if (status !== 'ok') {\n const errorReason = result[/* data */ 'd'];\n this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n }\n\n /**\n * @param {*} message\n * @private\n */\n private onDataMessage_(message: { [k: string]: any }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'];\n const onResponse = this.requestCBHash_[reqNum];\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[/*body*/ 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\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\n private onDataPush_(action: string, body: { [k: string]: any }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd')\n this.onDataUpdate_(\n body[/*path*/ 'p'],\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t']\n );\n else if (action === 'm')\n this.onDataUpdate_(\n body[/*path*/ 'p'],\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t']\n );\n else if (action === 'c')\n this.onListenRevoked_(body[/*path*/ 'p'], body[/*query*/ 'q']);\n else if (action === 'ac')\n this.onAuthRevoked_(\n body[/*status code*/ 's'],\n body[/* explanation */ 'd']\n );\n else if (action === 'sd') this.onSecurityDebugPacket_(body);\n else\n error(\n 'Unrecognized action received from server: ' +\n stringify(action) +\n '\\nAre you using the latest client?'\n );\n }\n\n private onReady_(timestamp: number, sessionId: string) {\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\n private scheduleConnect_(timeout: number) {\n assert(\n !this.realtime_,\n \"Scheduling a connect when we're already connected/ing?\"\n );\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n }\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\n this.establishConnectionTimer_ = setTimeout(() => {\n this.establishConnectionTimer_ = null;\n this.establishConnection_();\n }, Math.floor(timeout)) as any;\n }\n\n /**\n * @param {boolean} visible\n * @private\n */\n private onVisible_(visible: boolean) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (\n visible &&\n !this.visible_ &&\n this.reconnectDelay_ === this.maxReconnectDelay_\n ) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n this.visible_ = visible;\n }\n\n private onOnline_(online: boolean) {\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 } else {\n this.log_('Browser went offline. Killing connection.');\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n }\n\n private onRealtimeDisconnect_() {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null;\n\n // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n this.cancelSentTransactions_();\n\n // Clear out the pending requests.\n this.requestCBHash_ = {};\n\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 } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n const timeSinceLastConnectSucceeded =\n new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT)\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n\n const timeSinceLastConnectAttempt =\n new Date().getTime() - this.lastConnectionAttemptTime_;\n let reconnectDelay = Math.max(\n 0,\n this.reconnectDelay_ - timeSinceLastConnectAttempt\n );\n reconnectDelay = Math.random() * reconnectDelay;\n\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay);\n\n // Adjust reconnect delay for next time.\n this.reconnectDelay_ = Math.min(\n this.maxReconnectDelay_,\n this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER\n );\n }\n this.onConnectStatus_(false);\n }\n\n private establishConnection_() {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n const onDataMessage = this.onDataMessage_.bind(this);\n const onReady = this.onReady_.bind(this);\n const onDisconnect = this.onRealtimeDisconnect_.bind(this);\n const connId = this.id + ':' + PersistentConnection.nextConnectionId_++;\n const self = this;\n const lastSessionId = this.lastSessionId;\n let canceled = false;\n let connection: Connection | null = null;\n const closeFn = function() {\n if (connection) {\n connection.close();\n } else {\n canceled = true;\n onDisconnect();\n }\n };\n const sendRequestFn = function(msg: Object) {\n assert(\n connection,\n \"sendRequest call when we're not connected not allowed.\"\n );\n connection.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn,\n sendRequest: sendRequestFn\n };\n\n const forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false;\n\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) {\n log('getToken() completed. Creating connection.');\n self.authToken_ = result && result.accessToken;\n connection = new Connection(\n connId,\n self.repoInfo_,\n onDataMessage,\n onReady,\n onDisconnect,\n /* onKill= */ function(reason) {\n warn(reason + ' (' + self.repoInfo_.toString() + ')');\n self.interrupt(SERVER_KILL_INTERRUPT_REASON);\n },\n lastSessionId\n );\n } else {\n log('getToken() completed but was canceled');\n }\n })\n .then(null, function(error) {\n self.log_('Failed to get token: ' + error);\n if (!canceled) {\n if (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 warn(error);\n }\n closeFn();\n }\n });\n }\n }\n\n /**\n * @param {string} reason\n */\n interrupt(reason: string) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n if (this.realtime_) {\n this.realtime_.close();\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 /**\n * @param {string} reason\n */\n resume(reason: string) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n if (isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n }\n\n private handleTimestamp_(timestamp: number) {\n const delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({ serverTimeOffset: delta });\n }\n\n private cancelSentTransactions_() {\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n const put = this.outstandingPuts_[i];\n if (put && /*hash*/ 'h' in put.request && put.queued) {\n if (put.onComplete) put.onComplete('disconnect');\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) this.outstandingPuts_ = [];\n }\n\n /**\n * @param {!string} pathString\n * @param {Array.<*>=} query\n * @private\n */\n private onListenRevoked_(pathString: string, query?: any[]) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n let queryId;\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(q => ObjectToUniqueKey(q)).join('$');\n }\n const listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) listen.onComplete('permission_denied');\n }\n\n /**\n * @param {!string} pathString\n * @param {!string} queryId\n * @return {{queries:Array., onComplete:function(string)}}\n * @private\n */\n private removeListen_(pathString: string, queryId: string): ListenSpec {\n const normalizedPathString = new Path(pathString).toString(); // normalize path.\n let listen;\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n if (getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n return listen;\n }\n\n private onAuthRevoked_(statusCode: string, explanation: string) {\n 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\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\n private onSecurityDebugPacket_(body: { [k: string]: any }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body && typeof console !== 'undefined') {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n }\n\n private restoreState_() {\n //Re-authenticate ourselves if we have a credential stored.\n this.tryAuth();\n\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 forEach(this.listens_, (pathString: string, queries: Object) => {\n forEach(queries, (key: string, listenSpec: ListenSpec) => {\n this.sendListen_(listenSpec);\n });\n });\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) this.sendPut_(i);\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n const request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(\n request.action,\n request.pathString,\n request.data,\n request.onComplete\n );\n }\n }\n\n /**\n * Sends client stats for first connection\n * @private\n */\n private sendConnectStats_() {\n const stats: { [k: string]: number } = {};\n\n let clientName = 'js';\n if (CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n } else if (CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n\n stats[\n 'sdk.' + clientName + '.' + firebase.SDK_VERSION.replace(/\\./g, '-')\n ] = 1;\n\n if (isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n this.reportStats(stats);\n }\n\n /**\n * @return {boolean}\n * @private\n */\n private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/PersistentConnection.ts","/**\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\nimport { BrowserPollConnection } from './BrowserPollConnection';\nimport { WebSocketConnection } from './WebSocketConnection';\nimport { warn, each } from '../core/util/util';\nimport { TransportConstructor } from './Transport';\nimport { RepoInfo } from '../core/RepoInfo';\n\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 */\nexport class TransportManager {\n private transports_: TransportConstructor[];\n\n /**\n * @const\n * @type {!Array.}\n */\n static get ALL_TRANSPORTS() {\n return [BrowserPollConnection, WebSocketConnection];\n }\n\n /**\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\n */\n constructor(repoInfo: RepoInfo) {\n this.initTransports_(repoInfo);\n }\n\n /**\n * @param {!RepoInfo} repoInfo\n * @private\n */\n private initTransports_(repoInfo: RepoInfo) {\n const isWebSocketsAvailable: boolean =\n WebSocketConnection && WebSocketConnection['isAvailable']();\n let isSkipPollConnection =\n isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable)\n warn(\n \"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\"\n );\n\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n each(\n TransportManager.ALL_TRANSPORTS,\n (i: number, transport: TransportConstructor) => {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\n }\n }\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 initialTransport(): TransportConstructor {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n }\n\n /**\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\n * transport, or null\n */\n upgradeTransport(): TransportConstructor | null {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/realtime/TransportManager.ts","/**\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\nimport {\n error,\n logWrapper,\n requireKey,\n setTimeoutNonBlocking,\n warn\n} from '../core/util/util';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { PROTOCOL_VERSION } from './Constants';\nimport { TransportManager } from './TransportManager';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { Transport, TransportConstructor } from './Transport';\n\n// Abort upgrade attempt if it takes longer than 60s.\nconst UPGRADE_TIMEOUT = 60000;\n\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.\nconst DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000;\n\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.\nconst BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nconst BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\n\nconst enum RealtimeState {\n CONNECTING,\n CONNECTED,\n DISCONNECTED\n}\n\nconst MESSAGE_TYPE = 't';\nconst MESSAGE_DATA = 'd';\nconst CONTROL_SHUTDOWN = 's';\nconst CONTROL_RESET = 'r';\nconst CONTROL_ERROR = 'e';\nconst CONTROL_PONG = 'o';\nconst SWITCH_ACK = 'a';\nconst END_TRANSMISSION = 'n';\nconst PING = 'p';\n\nconst SERVER_HELLO = 'h';\n\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 */\nexport class Connection {\n connectionCount = 0;\n pendingDataMessages: any[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: any[]) => void;\n private primaryResponsesRequired_: number;\n private rx_: Transport;\n private secondaryConn_: Transport;\n private secondaryResponsesRequired_: number;\n private state_ = RealtimeState.CONNECTING;\n private transportManager_: TransportManager;\n private tx_: Transport;\n\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 constructor(\n public id: string,\n private repoInfo_: RepoInfo,\n private onMessage_: (a: Object) => void,\n private onReady_: (a: number, b: string) => void,\n private onDisconnect_: () => void,\n private onKill_: (a: string) => void,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n\n /**\n * Starts a connection attempt\n * @private\n */\n private start_() {\n const conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n undefined,\n this.lastSessionId\n );\n\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\n const onMessageReceived = this.connReceiver_(this.conn_);\n const 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 /*\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(() => {\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\n const healthyTimeout_ms = conn['healthyTimeout'] || 0;\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(() => {\n this.healthyTimeout_ = null;\n if (!this.isHealthy_) {\n if (\n this.conn_ &&\n this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has received ' +\n this.conn_.bytesReceived +\n ' bytes. Marking connection healthy.'\n );\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n } else if (\n this.conn_ &&\n this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE\n ) {\n this.log_(\n 'Connection exceeded healthy timeout but has sent ' +\n this.conn_.bytesSent +\n ' bytes. Leaving connection alive.'\n );\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 } else {\n this.log_('Closing unhealthy connection after timeout.');\n this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms)) as any;\n }\n }\n\n /**\n * @return {!string}\n * @private\n */\n private nextTransportId_(): string {\n return 'c:' + this.id + ':' + this.connectionCount++;\n }\n\n private disconnReceiver_(conn) {\n return everConnected => {\n if (conn === this.conn_) {\n this.onConnectionLost_(everConnected);\n } else if (conn === this.secondaryConn_) {\n this.log_('Secondary connection lost.');\n this.onSecondaryConnectionLost_();\n } else {\n this.log_('closing an old connection');\n }\n };\n }\n\n private connReceiver_(conn: Transport) {\n return (message: object) => {\n if (this.state_ != RealtimeState.DISCONNECTED) {\n if (conn === this.rx_) {\n this.onPrimaryMessageReceived_(message);\n } else if (conn === this.secondaryConn_) {\n this.onSecondaryMessageReceived_(message);\n } else {\n this.log_('message on old connection');\n }\n }\n };\n }\n\n /**\n *\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\n */\n sendRequest(dataMsg: object) {\n // wrap in a data message envelope and send it on\n const msg = { t: 'd', d: dataMsg };\n this.sendData_(msg);\n }\n\n tryCleanupConnection() {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_(\n 'cleaning up and promoting a connection: ' + this.secondaryConn_.connId\n );\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null;\n // the server will shutdown the old connection\n }\n }\n\n private onSecondaryControl_(controlData: { [k: string]: any }) {\n if (MESSAGE_TYPE in controlData) {\n const cmd = controlData[MESSAGE_TYPE] as string;\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\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 (\n this.tx_ === this.secondaryConn_ ||\n this.rx_ === this.secondaryConn_\n ) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n }\n\n private onSecondaryMessageReceived_(parsedData: object) {\n const layer: string = requireKey('t', parsedData);\n const data: any = requireKey('d', parsedData);\n if (layer == 'c') {\n this.onSecondaryControl_(data);\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 } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n }\n\n private upgradeIfSecondaryHealthy_() {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\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\n private proceedWithUpgrade_() {\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\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\n this.tryCleanupConnection();\n }\n\n private onPrimaryMessageReceived_(parsedData: { [k: string]: any }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData);\n const data: any = requireKey('d', parsedData);\n if (layer == 'c') {\n this.onControl_(data);\n } else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: any) {\n this.onPrimaryResponse_();\n\n // We don't do anything with data messages, just kick them up a level\n this.onMessage_(message);\n }\n\n private onPrimaryResponse_() {\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\n private onControl_(controlData: { [k: string]: any }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData);\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n for (let i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\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 } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n }\n\n /**\n *\n * @param {Object} handshake The handshake data returned from the server\n * @private\n */\n private onHandshake_(handshake: {\n ts: number;\n v: string;\n h: string;\n s: string;\n }) {\n const timestamp = handshake.ts;\n const version = handshake.v;\n const 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_ == RealtimeState.CONNECTING) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n }\n // TODO: do we want to upgrade? when? maybe a delay?\n this.tryStartUpgrade_();\n }\n }\n\n private tryStartUpgrade_() {\n const conn = this.transportManager_.upgradeTransport();\n if (conn) {\n this.startUpgrade_(conn);\n }\n }\n\n private startUpgrade_(conn: TransportConstructor) {\n this.secondaryConn_ = new conn(\n this.nextTransportId_(),\n this.repoInfo_,\n this.sessionId\n );\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\n const onMessage = this.connReceiver_(this.secondaryConn_);\n const onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect);\n\n // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n setTimeoutNonBlocking(() => {\n if (this.secondaryConn_) {\n this.log_('Timed out trying to upgrade.');\n this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n }\n\n private onReset_(host: string) {\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_ === RealtimeState.CONNECTED) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n }\n\n private onConnectionEstablished_(conn: Transport, timestamp: number) {\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = RealtimeState.CONNECTED;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n }\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 } else {\n setTimeoutNonBlocking(() => {\n this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n }\n\n private sendPingOnPrimaryIfNecessary_() {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === RealtimeState.CONNECTED) {\n this.log_('sending ping on primary.');\n this.sendData_({ t: 'c', d: { t: PING, d: {} } });\n }\n }\n\n private onSecondaryConnectionLost_() {\n const 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 *\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 private onConnectionLost_(everConnected: boolean) {\n this.conn_ = null;\n\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_ === RealtimeState.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 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 } else if (this.state_ === RealtimeState.CONNECTED) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n }\n\n /**\n *\n * @param {string} reason\n * @private\n */\n private onConnectionShutdown_(reason: string) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n }\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\n this.close();\n }\n\n private sendData_(data: object) {\n if (this.state_ !== RealtimeState.CONNECTED) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n }\n\n /**\n * Cleans up this connection, calling the appropriate callbacks\n */\n close() {\n if (this.state_ !== RealtimeState.DISCONNECTED) {\n this.log_('Closing realtime connection.');\n this.state_ = RealtimeState.DISCONNECTED;\n\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n }\n\n /**\n *\n * @private\n */\n private closeConnections_() {\n this.log_('Shutting down all connections');\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/realtime/Connection.ts","/**\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\nimport { exceptionGuard } from '../../core/util/util';\n\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 */\nexport class PacketReceiver {\n pendingResponses: any[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: Object) => void) {}\n\n closeAfter(responseNum: number, callback: () => void) {\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 /**\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 handleResponse(requestNum: number, data: any[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[this.currentResponseNum];\n delete this.pendingResponses[this.currentResponseNum];\n for (let i = 0; i < toProcess.length; ++i) {\n if (toProcess[i]) {\n exceptionGuard(() => {\n this.onMessage_(toProcess[i]);\n });\n }\n }\n if (this.currentResponseNum === this.closeAfterResponse) {\n if (this.onClose) {\n this.onClose();\n this.onClose = null;\n }\n break;\n }\n this.currentResponseNum++;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/realtime/polling/PacketReceiver.ts","/**\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\nimport {\n base64Encode,\n executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\nimport { CountedSet } from '../core/util/CountedSet';\nimport { StatsManager } from '../core/stats/StatsManager';\nimport { PacketReceiver } from './polling/PacketReceiver';\nimport {\n FORGE_DOMAIN,\n FORGE_REF,\n LAST_SESSION_PARAM,\n LONG_POLLING,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM\n} from './Constants';\nimport { stringify } from '../../utils/json';\nimport { isNodeSdk } from '../../utils/environment';\nimport { Transport } from './Transport';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { StatsCollection } from '../core/stats/StatsCollection';\n\n// URL query parameters associated with longpolling\nexport const FIREBASE_LONGPOLL_START_PARAM = 'start';\nexport const FIREBASE_LONGPOLL_CLOSE_COMMAND = 'close';\nexport const FIREBASE_LONGPOLL_COMMAND_CB_NAME = 'pLPCommand';\nexport const FIREBASE_LONGPOLL_DATA_CB_NAME = 'pRTLPCB';\nexport const FIREBASE_LONGPOLL_ID_PARAM = 'id';\nexport const FIREBASE_LONGPOLL_PW_PARAM = 'pw';\nexport const FIREBASE_LONGPOLL_SERIAL_PARAM = 'ser';\nexport const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = 'cb';\nexport const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = 'seg';\nexport const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = 'ts';\nexport const FIREBASE_LONGPOLL_DATA_PARAM = 'd';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM = 'disconn';\nexport const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = 'dframe';\n\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.\nconst MAX_URL_DATA_SIZE = 1870;\nconst SEG_HEADER_SIZE = 30; //ie: &seg=8299234&ts=982389123&d=\nconst MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;\n\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 */\nconst KEEPALIVE_REQUEST_INTERVAL = 25000;\n\n/**\n * How long to wait before aborting a long-polling connection attempt.\n * @const\n * @type {number}\n */\nconst LP_CONNECT_TIMEOUT = 30000;\n\n/**\n * This class manages a single long-polling connection.\n *\n * @constructor\n * @implements {Transport}\n */\nexport class BrowserPollConnection implements Transport {\n bytesSent = 0;\n bytesReceived = 0;\n urlFn: (params: object) => string;\n scriptTagHolder: FirebaseIFrameScriptHolder;\n myDisconnFrame: HTMLIFrameElement;\n curSegmentNum: number;\n myPacketOrderer: PacketReceiver;\n id: string;\n password: string;\n private log_: (...a: any[]) => void;\n private stats_: StatsCollection;\n private everConnected_ = false;\n private isClosed_: boolean;\n private connectTimeoutTimer_: number | null;\n private onDisconnect_: ((a?: boolean) => void) | null;\n\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 constructor(\n public connId: string,\n public repoInfo: RepoInfo,\n public transportSessionId?: string,\n public lastSessionId?: string\n ) {\n this.log_ = logWrapper(connId);\n this.stats_ = StatsManager.getCollection(repoInfo);\n this.urlFn = (params: { [k: string]: string }) =>\n repoInfo.connectionURL(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 open(onMessage: (msg: Object) => void, onDisconnect: (a?: boolean) => void) {\n this.curSegmentNum = 0;\n this.onDisconnect_ = onDisconnect;\n this.myPacketOrderer = new PacketReceiver(onMessage);\n this.isClosed_ = false;\n\n this.connectTimeoutTimer_ = setTimeout(() => {\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)) as any;\n\n // Ensure we delay the creation of the iframe until the DOM is loaded.\n executeWhenDOMReady(() => {\n if (this.isClosed_) return;\n\n //Set up a callback that gets triggered once a connection is set up.\n this.scriptTagHolder = new FirebaseIFrameScriptHolder(\n (...args) => {\n const [command, arg1, arg2, arg3, arg4] = args;\n this.incrementIncomingBytes_(args);\n if (!this.scriptTagHolder) return; // we closed the connection.\n\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n this.everConnected_ = true;\n if (command == FIREBASE_LONGPOLL_START_PARAM) {\n this.id = arg1;\n this.password = arg2;\n } else if (command === 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\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, () => {\n this.onClosed_();\n });\n } else {\n this.onClosed_();\n }\n } else {\n throw new Error('Unrecognized command received: ' + command);\n }\n },\n (...args) => {\n const [pN, data] = args;\n this.incrementIncomingBytes_(args);\n this.myPacketOrderer.handleResponse(pN, data);\n },\n () => {\n this.onClosed_();\n },\n this.urlFn\n );\n\n //Send the initial request to connect. The serial number is simply to keep the browser from pulling previous results\n //from cache.\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_START_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(\n Math.random() * 100000000\n );\n if (this.scriptTagHolder.uniqueCallbackIdentifier)\n urlParams[\n FIREBASE_LONGPOLL_CALLBACK_ID_PARAM\n ] = this.scriptTagHolder.uniqueCallbackIdentifier;\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n if (this.transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;\n }\n if (this.lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = this.lastSessionId;\n }\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(FORGE_DOMAIN) !== -1\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n const connectURL = this.urlFn(urlParams);\n this.log_('Connecting via long-poll to ' + connectURL);\n this.scriptTagHolder.addTag(connectURL, () => {\n /* do nothing */\n });\n });\n }\n\n /**\n * Call this when a handshake has completed successfully and we want to consider the connection established\n */\n start() {\n this.scriptTagHolder.startLongPoll(this.id, this.password);\n this.addDisconnectPingFrame(this.id, this.password);\n }\n\n private static forceAllow_: boolean;\n\n /**\n * Forces long polling to be considered as a potential transport\n */\n static forceAllow() {\n BrowserPollConnection.forceAllow_ = true;\n }\n\n private static forceDisallow_: boolean;\n\n /**\n * Forces longpolling to not be considered as a potential transport\n */\n static forceDisallow() {\n BrowserPollConnection.forceDisallow_ = true;\n }\n\n // Static method, use string literal so it can be accessed in a generic way\n static isAvailable() {\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 (\n BrowserPollConnection.forceAllow_ ||\n (!BrowserPollConnection.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp() &&\n !isNodeSdk())\n );\n }\n\n /**\n * No-op for polling\n */\n markConnectionHealthy() {}\n\n /**\n * Stops polling and cleans up the iframe\n * @private\n */\n private shutdown_() {\n this.isClosed_ = true;\n\n if (this.scriptTagHolder) {\n this.scriptTagHolder.close();\n this.scriptTagHolder = null;\n }\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\n if (this.connectTimeoutTimer_) {\n clearTimeout(this.connectTimeoutTimer_);\n this.connectTimeoutTimer_ = null;\n }\n }\n\n /**\n * Triggered when this transport is closed\n * @private\n */\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('Longpoll is closing itself');\n this.shutdown_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_(this.everConnected_);\n this.onDisconnect_ = null;\n }\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 close() {\n if (!this.isClosed_) {\n this.log_('Longpoll is being closed.');\n this.shutdown_();\n }\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 send(data: Object) {\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\n //first, lets get the base64-encoded data\n const base64data = base64Encode(dataStr);\n\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 const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);\n\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 (let i = 0; i < dataSegs.length; i++) {\n this.scriptTagHolder.enqueueSegment(\n this.curSegmentNum,\n dataSegs.length,\n dataSegs[i]\n );\n this.curSegmentNum++;\n }\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 addDisconnectPingFrame(id: string, pw: string) {\n if (isNodeSdk()) return;\n this.myDisconnFrame = document.createElement('iframe');\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;\n this.myDisconnFrame.src = this.urlFn(urlParams);\n this.myDisconnFrame.style.display = 'none';\n\n document.body.appendChild(this.myDisconnFrame);\n }\n\n /**\n * Used to track the bytes received by this client\n * @param {*} args\n * @private\n */\n private incrementIncomingBytes_(args: any) {\n // TODO: This is an annoying perf hit just to track the number of incoming bytes. Maybe it should be opt-in.\n const bytesReceived = stringify(args).length;\n this.bytesReceived += bytesReceived;\n this.stats_.incrementCounter('bytes_received', bytesReceived);\n }\n}\n\nexport interface IFrameElement extends HTMLIFrameElement {\n doc: Document;\n}\n\n/*********************************************************************************************\n * A wrapper around an iframe that is used as a long-polling script holder.\n * @constructor\n *********************************************************************************************/\nexport class FirebaseIFrameScriptHolder {\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 outstandingRequests = new CountedSet();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: { seg: number; ts: number; d: any }[] = [];\n\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 currentSerial = Math.floor(Math.random() * 100000000);\n\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 sendNewPolls = true;\n\n uniqueCallbackIdentifier: number;\n myIFrame: IFrameElement;\n alive: boolean;\n myID: string;\n myPW: string;\n commandCB: (command: string, ...args: any[]) => void;\n onMessageCB: (...args: any[]) => void;\n\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 constructor(\n commandCB: (command: string, ...args: any[]) => void,\n onMessageCB: (...args: any[]) => void,\n public onDisconnect: () => void,\n public urlFn: (a: object) => string\n ) {\n if (!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 = LUIDGenerator();\n (window as any)[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n (window as any)[\n FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier\n ] = onMessageCB;\n\n //Create an iframe for us to add script tags to.\n this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();\n\n // Set the iframe's contents.\n let 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 (\n this.myIFrame.src &&\n this.myIFrame.src.substr(0, 'javascript:'.length) === 'javascript:'\n ) {\n const currentDomain = document.domain;\n script = '';\n }\n const iframeContents = '' + script + '';\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n if (e.stack) {\n log(e.stack);\n }\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\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 private static createIFrame_(): IFrameElement {\n const iframe = document.createElement('iframe') as IFrameElement;\n iframe.style.display = 'none';\n\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 const 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 log('No IE domain setting required');\n }\n } catch (e) {\n const domain = document.domain;\n iframe.src =\n \"javascript:void((function(){document.open();document.domain='\" +\n domain +\n \"';document.close();})())\";\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\n // Get the document of the iframe in a browser-specific way.\n if (iframe.contentDocument) {\n (iframe as any).doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n (iframe as any).doc = iframe.contentWindow.document; // Internet Explorer\n } else if ((iframe as any).document) {\n (iframe as any).doc = (iframe as any).document; //others?\n }\n\n return iframe;\n }\n\n /**\n * Cancel all outstanding queries and remove the frame.\n */\n close() {\n //Mark this iframe as dead, so no new requests are sent.\n this.alive = false;\n\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(() => {\n if (this.myIFrame !== null) {\n document.body.removeChild(this.myIFrame);\n this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n if (isNodeSdk() && this.myID) {\n const urlParams: { [k: string]: string } = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n const theURL = this.urlFn(urlParams);\n (FirebaseIFrameScriptHolder as any).nodeRestRequest(theURL);\n }\n\n // Protect from being called recursively.\n const onDisconnect = this.onDisconnect;\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\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 startLongPoll(id: string, pw: string) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true;\n\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 /**\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 private newRequest_() {\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 (\n this.alive &&\n this.sendNewPolls &&\n this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)\n ) {\n //construct our url\n this.currentSerial++;\n const urlParams: { [k: string]: string | number } = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n let theURL = this.urlFn(urlParams);\n //Now add as much data as we can.\n let curDataString = '';\n let i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n const nextSeg = this.pendingSegs[0];\n if (\n nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <=\n MAX_URL_DATA_SIZE\n ) {\n //great, the segment will fit. Lets append it.\n const theSeg = this.pendingSegs.shift();\n curDataString =\n curDataString +\n '&' +\n FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM +\n i +\n '=' +\n theSeg.seg +\n '&' +\n FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET +\n i +\n '=' +\n theSeg.ts +\n '&' +\n FIREBASE_LONGPOLL_DATA_PARAM +\n i +\n '=' +\n theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n\n return true;\n } else {\n return false;\n }\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 enqueueSegment(segnum: number, totalsegs: number, data: any) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });\n\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 /**\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 private addLongPollTag_(url: string, serial: number) {\n //remember that we sent this request.\n this.outstandingRequests.add(serial, 1);\n\n const doNewRequest = () => {\n this.outstandingRequests.remove(serial);\n this.newRequest_();\n };\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 const keepaliveTimeout = setTimeout(\n doNewRequest,\n Math.floor(KEEPALIVE_REQUEST_INTERVAL)\n );\n\n const readyStateCB = () => {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout);\n\n // Trigger a new request so we can continue receiving data.\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n }\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 addTag(url: string, loadCB: () => void) {\n if (isNodeSdk()) {\n (this as any).doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(() => {\n try {\n // if we're already closed, don't add this poll\n if (!this.sendNewPolls) return;\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n newScript.onload = (newScript as any).onreadystatechange = function() {\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript.onload = (newScript as any).onreadystatechange = null;\n if (newScript.parentNode) {\n newScript.parentNode.removeChild(newScript);\n }\n loadCB();\n }\n };\n newScript.onerror = () => {\n log('Long-poll script failed to load: ' + url);\n this.sendNewPolls = false;\n this.close();\n };\n this.myIFrame.doc.body.appendChild(newScript);\n } catch (e) {\n // TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/realtime/BrowserPollConnection.ts","/**\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\nimport { RepoInfo } from '../core/RepoInfo';\n\ndeclare const MozWebSocket: any;\n\nimport firebase from '../../app';\nimport { assert } from '../../utils/assert';\nimport { logWrapper, splitStringBySize } from '../core/util/util';\nimport { StatsManager } from '../core/stats/StatsManager';\nimport {\n FORGE_DOMAIN,\n FORGE_REF,\n LAST_SESSION_PARAM,\n PROTOCOL_VERSION,\n REFERER_PARAM,\n TRANSPORT_SESSION_PARAM,\n VERSION_PARAM,\n WEBSOCKET\n} from './Constants';\nimport { CONSTANTS as ENV_CONSTANTS } from '../../utils/constants';\nimport { PersistentStorage } from '../core/storage/storage';\nimport { jsonEval, stringify } from '../../utils/json';\nimport { isNodeSdk } from '../../utils/environment';\nimport { Transport } from './Transport';\nimport { StatsCollection } from '../core/stats/StatsCollection';\n\nconst WEBSOCKET_MAX_FRAME_SIZE = 16384;\nconst WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\n\nlet WebSocketImpl = null;\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n\nexport function setWebSocketImpl(impl) {\n WebSocketImpl = impl;\n}\n\n/**\n * Create a new websocket connection with the given callbacks.\n * @constructor\n * @implements {Transport}\n */\nexport class WebSocketConnection implements Transport {\n keepaliveTimer: number | null = null;\n frames: string[] | null = null;\n totalFrames = 0;\n bytesSent = 0;\n bytesReceived = 0;\n connURL: string;\n onDisconnect: (a?: boolean) => void;\n onMessage: (msg: Object) => void;\n mySock: any | null;\n private log_: (...a: any[]) => void;\n private stats_: StatsCollection;\n private everConnected_: boolean;\n private isClosed_: boolean;\n\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 constructor(\n public connId: string,\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string\n ) {\n this.log_ = logWrapper(this.connId);\n this.stats_ = StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(\n repoInfo,\n transportSessionId,\n lastSessionId\n );\n }\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 private static connectionURL_(\n repoInfo: RepoInfo,\n transportSessionId?: string,\n lastSessionId?: string\n ): string {\n const urlParams: { [k: string]: string } = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (\n !isNodeSdk() &&\n typeof location !== 'undefined' &&\n location.href &&\n location.href.indexOf(FORGE_DOMAIN) !== -1\n ) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n return repoInfo.connectionURL(WEBSOCKET, urlParams);\n }\n\n /**\n *\n * @param onMessage Callback when messages arrive\n * @param onDisconnect Callback with connection lost.\n */\n open(onMessage: (msg: Object) => void, onDisconnect: (a?: boolean) => void) {\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n\n this.log_('Websocket connecting to ' + this.connURL);\n\n this.everConnected_ = false;\n // Assume failure until proven otherwise.\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n if (isNodeSdk()) {\n const device = ENV_CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node';\n // UA Format: Firebase////\n const options: { [k: string]: object } = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${firebase.SDK_VERSION}/${process.platform}/${device}`\n }\n };\n\n // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n const env = process['env'];\n const proxy =\n this.connURL.indexOf('wss://') == 0\n ? env['HTTPS_PROXY'] || env['https_proxy']\n : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = { origin: proxy };\n }\n\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = () => {\n this.log_('Websocket connected.');\n this.everConnected_ = true;\n };\n\n this.mySock.onclose = () => {\n this.log_('Websocket connection was disconnected.');\n this.mySock = null;\n this.onClosed_();\n };\n\n this.mySock.onmessage = (m: object) => {\n this.handleIncomingFrame(m);\n };\n\n this.mySock.onerror = (e: any) => {\n this.log_('WebSocket error. Closing connection.');\n const error = e.message || e.data;\n if (error) {\n this.log_(error);\n }\n this.onClosed_();\n };\n }\n\n /**\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\n */\n start() {}\n\n static forceDisallow_: Boolean;\n\n static forceDisallow() {\n WebSocketConnection.forceDisallow_ = true;\n }\n\n static isAvailable(): boolean {\n let isOldAndroid = false;\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n const oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n const 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\n return (\n !isOldAndroid &&\n WebSocketImpl !== null &&\n !WebSocketConnection.forceDisallow_\n );\n }\n\n /**\n * Number of response before we consider the connection \"healthy.\"\n * @type {number}\n */\n static responsesRequiredToBeHealthy = 2;\n\n /**\n * Time to wait for the connection te become healthy before giving up.\n * @type {number}\n */\n static healthyTimeout = 30000;\n\n /**\n * Returns true if we previously failed to connect with this transport.\n * @return {boolean}\n */\n static previouslyFailed(): boolean {\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 (\n PersistentStorage.isInMemoryStorage ||\n PersistentStorage.get('previous_websocket_failure') === true\n );\n }\n\n markConnectionHealthy() {\n PersistentStorage.remove('previous_websocket_failure');\n }\n\n private appendFrame_(data: string) {\n this.frames.push(data);\n if (this.frames.length == this.totalFrames) {\n const fullMess = this.frames.join('');\n this.frames = null;\n const jsonMess = jsonEval(fullMess);\n\n //handle the message\n this.onMessage(jsonMess);\n }\n }\n\n /**\n * @param {number} frameCount The number of frames we are expecting from the server\n * @private\n */\n private handleNewFrameCount_(frameCount: number) {\n this.totalFrames = frameCount;\n this.frames = [];\n }\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 private extractFrameCount_(data: string): string | null {\n 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 const 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 /**\n * Process a websocket frame that has arrived from the server.\n * @param mess The frame data\n */\n handleIncomingFrame(mess: { [k: string]: any }) {\n if (this.mySock === null) return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n const data = mess['data'] as string;\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n const remainingData = this.extractFrameCount_(data);\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n }\n\n /**\n * Send a message to the server\n * @param {Object} data The JSON object to transmit\n */\n send(data: Object) {\n this.resetKeepAlive();\n\n const dataStr = stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length);\n\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\n const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);\n\n //Send the length header\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n }\n\n //Send the actual data in segments.\n for (let i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n }\n\n private shutdown_() {\n this.isClosed_ = true;\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n }\n\n private onClosed_() {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_();\n\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 /**\n * External-facing close handler.\n * Close the websocket and kill the connection.\n */\n close() {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\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 resetKeepAlive() {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(() => {\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)) as any;\n }\n\n /**\n * Send a string over the websocket.\n *\n * @param {string} str String to send.\n * @private\n */\n private sendString_(str: string) {\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 } catch (e) {\n this.log_(\n 'Exception thrown from WebSocket.send():',\n e.message || e.data,\n 'Closing connection.'\n );\n setTimeout(this.onClosed_.bind(this), 0);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/realtime/WebSocketConnection.ts","/**\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\nimport { Query } from '../api/Query';\n\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 */\nexport abstract class ServerActions {\n /**\n * @param {!Query} query\n * @param {function():string} currentHashFn\n * @param {?number} tag\n * @param {function(string, *)} onComplete\n */\n abstract listen(\n query: Query,\n currentHashFn: () => string,\n tag: number | null,\n onComplete: (a: string, b: any) => void\n ): void;\n\n /**\n * Remove a listen.\n *\n * @param {!Query} query\n * @param {?number} tag\n */\n abstract unlisten(query: Query, tag: number | null): void;\n\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n * @param {string=} hash\n */\n put(\n pathString: string,\n data: any,\n onComplete?: (a: string, b: string) => void,\n hash?: string\n ) {}\n\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, ?string)} onComplete\n * @param {string=} hash\n */\n merge(\n pathString: string,\n data: any,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {}\n\n /**\n * Refreshes the auth token for the current connection.\n * @param {string} token The authentication token\n */\n refreshAuthToken(token: string) {}\n\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n onDisconnectPut(\n pathString: string,\n data: any,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n /**\n * @param {string} pathString\n * @param {*} data\n * @param {function(string, string)=} onComplete\n */\n onDisconnectMerge(\n pathString: string,\n data: any,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n /**\n * @param {string} pathString\n * @param {function(string, string)=} onComplete\n */\n onDisconnectCancel(\n pathString: string,\n onComplete?: (a: string, b: string) => void\n ) {}\n\n /**\n * @param {Object.} stats\n */\n reportStats(stats: { [k: string]: any }) {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/core/ServerActions.ts","/**\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\nimport firebase from './app';\nimport { FirebaseApp, FirebaseNamespace } from './app/firebase_app';\nimport { Database } from './database/api/Database';\nimport { Query } from './database/api/Query';\nimport { Reference } from './database/api/Reference';\nimport { enableLogging } from './database/core/util/util';\nimport { RepoManager } from './database/core/RepoManager';\nimport * as INTERNAL from './database/api/internal';\nimport * as TEST_ACCESS from './database/api/test_access';\nimport { isNodeSdk } from './utils/environment';\n\nexport function registerDatabase(instance: FirebaseNamespace) {\n // Register the Database Service with the 'firebase' namespace.\n const namespace = instance.INTERNAL.registerService(\n 'database',\n (app, unused, url) => RepoManager.getInstance().databaseFromApp(app, url),\n // firebase.database namespace properties\n {\n Reference,\n Query,\n Database,\n enableLogging,\n INTERNAL,\n ServerValue: Database.ServerValue,\n TEST_ACCESS\n },\n null,\n true\n );\n\n if (isNodeSdk()) {\n module.exports = namespace;\n }\n}\n\n/**\n * Extensions to the FirebaseApp and FirebaseNamespaces interfaces\n */\ndeclare module './app/firebase_app' {\n interface FirebaseApp {\n database?(): Database;\n }\n}\n\ndeclare module './app/firebase_app' {\n interface FirebaseNamespace {\n database?: {\n (app?: FirebaseApp): Database;\n Database;\n enableLogging;\n INTERNAL;\n Query;\n Reference;\n ServerValue;\n };\n }\n}\n\nregisterDatabase(firebase);\n\n\n\n// WEBPACK FOOTER //\n// ./src/database.ts","module.exports = function(originalModule) {\r\n\tif(!originalModule.webpackPolyfill) {\r\n\t\tvar module = Object.create(originalModule);\r\n\t\t// module.parent = undefined by default\r\n\t\tif(!module.children) module.children = [];\r\n\t\tObject.defineProperty(module, \"loaded\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.l;\r\n\t\t\t}\r\n\t\t});\r\n\t\tObject.defineProperty(module, \"id\", {\r\n\t\t\tenumerable: true,\r\n\t\t\tget: function() {\r\n\t\t\t\treturn module.i;\r\n\t\t\t}\r\n\t\t});\r\n\t\tObject.defineProperty(module, \"exports\", {\r\n\t\t\tenumerable: true,\r\n\t\t});\r\n\t\tmodule.webpackPolyfill = 1;\r\n\t}\r\n\treturn module;\r\n};\r\n\n\n\n//////////////////\n// WEBPACK FOOTER\n// (webpack)/buildin/harmony-module.js\n// module id = 63\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\nimport { WebSocketConnection } from '../realtime/WebSocketConnection';\nimport { BrowserPollConnection } from '../realtime/BrowserPollConnection';\nimport { Reference } from './Reference';\n\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 */\n\nexport const forceLongPolling = function() {\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n};\n\nexport const forceWebSockets = function() {\n BrowserPollConnection.forceDisallow();\n};\n\n/* Used by App Manager */\nexport const isWebSocketsAvailable = function(): boolean {\n return WebSocketConnection['isAvailable']();\n};\n\nexport const setSecurityDebugCallback = function(\n ref: Reference,\n callback: (a: Object) => void\n) {\n (ref.repo.persistentConnection_ as any).securityDebugCallback_ = callback;\n};\n\nexport const stats = function(ref: Reference, showDelta?: boolean) {\n ref.repo.stats(showDelta);\n};\n\nexport const statsIncrementCounter = function(ref: Reference, metric: string) {\n ref.repo.statsIncrementCounter(metric);\n};\n\nexport const dataUpdateCount = function(ref: Reference): number {\n return ref.repo.dataUpdateCount;\n};\n\nexport const interceptServerData = function(\n ref: Reference,\n callback: ((a: string, b: any) => void) | null\n) {\n return ref.repo.interceptServerData_(callback);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/internal.ts","/**\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\nimport { RepoInfo } from '../core/RepoInfo';\nimport { PersistentConnection } from '../core/PersistentConnection';\nimport { RepoManager } from '../core/RepoManager';\nimport { Connection } from '../realtime/Connection';\nimport { Query } from './Query';\n\nexport const DataConnection = PersistentConnection;\n\n/**\n * @param {!string} pathString\n * @param {function(*)} onComplete\n */\n(PersistentConnection.prototype as any).simpleListen = function(\n pathString: string,\n onComplete: (a: any) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\n(PersistentConnection.prototype as any).echo = function(\n data: any,\n onEcho: (a: any) => void\n) {\n this.sendRequest('echo', { d: data }, onEcho);\n};\n\n// RealTimeConnection properties that we use in tests.\nexport const RealTimeConnection = Connection;\n\n/**\n * @param {function(): string} newHash\n * @return {function()}\n */\nexport const hijackHash = function(newHash: () => string) {\n const oldPut = PersistentConnection.prototype.put;\n PersistentConnection.prototype.put = function(\n pathString,\n data,\n opt_onComplete,\n opt_hash\n ) {\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.prototype.put = oldPut;\n };\n};\n\n/**\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\n */\nexport const ConnectionTarget = RepoInfo;\n\n/**\n * @param {!Query} query\n * @return {!string}\n */\nexport const queryIdentifier = function(query: Query) {\n return query.queryIdentifier();\n};\n\n/**\n * @param {!Query} firebaseRef\n * @return {!Object}\n */\nexport const listens = function(firebaseRef: Query) {\n return (firebaseRef.repo.persistentConnection_ as any).listens_;\n};\n\n/**\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\n *\n * @param {boolean} forceRestClient\n */\nexport const forceRestClient = function(forceRestClient: boolean) {\n RepoManager.getInstance().forceRestClient(forceRestClient);\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/database/api/test_access.ts","try {\n webpackJsonpFirebase([3],{\n\n/***/ 61:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// EXTERNAL MODULE: ./src/app/errors.ts\nvar errors = __webpack_require__(24);\n\n// CONCATENATED MODULE: ./src/messaging/models/errors.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key'\n};\nvar ERROR_MAP = (_a = {}, _a[CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.', _a[CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.', _a[CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.', _a[CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" + 'correctly in the options passed into firebase.initializeApp().', _a[CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.', _a[CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.', _a[CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" + 'required to use the firebase SDK.', _a[CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.', _a[CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' + 'default service worker. {$browserErrorMessage}', _a[CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.', _a[CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' + 'any existing Push Subscriptions.', _a[CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.', _a[CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.', _a[CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}', _a[CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.', _a[CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.', _a[CODES.USE_SW_BEFORE_GET_TOKEN] = 'You must call useServiceWorker() before ' + 'calling getToken() to ensure your service worker is used.', _a[CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' + 'deleteToken(), i.e. the token from getToken().', _a[CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' + 'be performed as the token was not found.', _a[CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' + 'scope could not be performed as the scope was not found.', _a[CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.', _a[CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.', _a[CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' + 'the FCM token for push messaging. Will have to resubscribe the ' + 'user on next visit. {$message}', _a[CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' + 'and as a result, unable to resubscribe. Will have to resubscribe the ' + 'user on next visit.', _a[CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.', _a[CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' + 'successful, there was a problem accessing the service worker itself.', _a[CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" + \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\", _a[CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' + 'least one character.', _a[CODES.BAD_VAPID_KEY] = 'The public VAPID key must be a string with at ' + 'least one character.', _a[CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.', _a[CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' + 'a valid token string.', _a[CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' + 'not a valid push set string.', _a[CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.', _a);\n/* harmony default export */ var models_errors = ({\n codes: CODES,\n map: ERROR_MAP\n});\nvar _a;\n// CONCATENATED MODULE: ./src/messaging/helpers/array-buffer-to-base64.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\nfunction toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\n/* harmony default export */ var array_buffer_to_base64 = (function (arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n});;\n// CONCATENATED MODULE: ./src/messaging/models/fcm-details.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar FCM_APPLICATION_SERVER_KEY = [0x04, 0x33, 0x94, 0xf7, 0xdf, 0xa1, 0xeb, 0xb1, 0xdc, 0x03, 0xa2, 0x5e, 0x15, 0x71, 0xdb, 0x48, 0xd3, 0x2e, 0xed, 0xed, 0xb2, 0x34, 0xdb, 0xb7, 0x47, 0x3a, 0x0c, 0x8f, 0xc4, 0xcc, 0xe1, 0x6f, 0x3c, 0x8c, 0x84, 0xdf, 0xab, 0xb6, 0x66, 0x3e, 0xf2, 0x0c, 0xd4, 0x8b, 0xfe, 0xe3, 0xf9, 0x76, 0x2f, 0x14, 0x1c, 0x63, 0x08, 0x6a, 0x6f, 0x2d, 0xb1, 0x1a, 0x95, 0xb0, 0xce, 0x37, 0xc0, 0x9c, 0x6e];\nvar SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: new Uint8Array(FCM_APPLICATION_SERVER_KEY)\n};\n/* harmony default export */ var fcm_details = ({\n ENDPOINT: 'https://fcm.googleapis.com',\n APPLICATION_SERVER_KEY: FCM_APPLICATION_SERVER_KEY,\n SUBSCRIPTION_OPTIONS: SUBSCRIPTION_DETAILS\n});\n// CONCATENATED MODULE: ./src/messaging/models/token-manager.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n\nvar FCM_TOKEN_DETAILS_DB = 'fcm_token_details_db';\nvar FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nvar FCM_TOKEN_DETAILS_DB_VERSION = 1;\nvar token_manager_TokenManager = /** @class */function () {\n function TokenManager() {\n this.errorFactory_ = new errors[\"a\" /* ErrorFactory */]('messaging', 'Messaging', models_errors.map);\n this.openDbPromise_ = null;\n }\n /**\r\n * Get the indexedDB as a promsie.\r\n * @private\r\n * @return {Promise} The IndexedDB database\r\n */\n TokenManager.prototype.openDatabase_ = function () {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n this.openDbPromise_ = new Promise(function (resolve, reject) {\n var request = indexedDB.open(FCM_TOKEN_DETAILS_DB, FCM_TOKEN_DETAILS_DB_VERSION);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n request.onupgradeneeded = function (event) {\n var db = event.target.result;\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n return this.openDbPromise_;\n };\n /**\r\n * Close the currently open database.\r\n * @return {Promise} Returns the result of the promise chain.\r\n */\n TokenManager.prototype.closeDatabase = function () {\n var _this = this;\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(function (db) {\n db.close();\n _this.openDbPromise_ = null;\n });\n }\n return Promise.resolve();\n };\n /**\r\n * Given a token, this method will look up the details in indexedDB.\r\n * @public\r\n * @param {string} fcmToken\r\n * @return {Promise} The details associated with that token.\r\n */\n TokenManager.prototype.getTokenDetailsFromToken = function (fcmToken) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var index = objectStore.index('fcmToken');\n var request = index.get(fcmToken);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getTokenDetailsFromSWScope_ = function (swScope) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = function (event) {\n reject(event.target.error);\n };\n scopeRequest.onsuccess = function (event) {\n resolve(event.target.result);\n };\n });\n });\n };\n TokenManager.prototype.getAllTokenDetailsForSenderId_ = function (senderId) {\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var senderIdTokens = [];\n var cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n } else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n };\n /**\r\n * Given a PushSubscription and messagingSenderId, get an FCM token.\r\n * @public\r\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\r\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\r\n * @param {string=} pushSet If defined this will swap the subscription for\r\n * matching FCM token.\r\n * @return {Promise} Returns the FCM token to be used in place\r\n * of the PushSubscription.\r\n */\n TokenManager.prototype.subscribeToFCM = function (senderId, subscription, pushSet) {\n var _this = this;\n var p256dh = array_buffer_to_base64(subscription['getKey']('p256dh'));\n var auth = array_buffer_to_base64(subscription['getKey']('auth'));\n var fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" + (\"endpoint=\" + subscription.endpoint + \"&\") + (\"encryption_key=\" + p256dh + \"&\") + (\"encryption_auth=\" + auth);\n if (pushSet) {\n fcmSubscribeBody += \"&pushSet=\" + pushSet;\n }\n var headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n var subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n return fetch(fcm_details.ENDPOINT + '/fcm/connect/subscribe', subscribeOptions).then(function (response) {\n return response.json();\n }).then(function (response) {\n var fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n var message = fcmTokenResponse['error']['message'];\n throw _this.errorFactory_.create(models_errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n if (!fcmTokenResponse['token']) {\n throw _this.errorFactory_.create(models_errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n if (!fcmTokenResponse['pushSet']) {\n throw _this.errorFactory_.create(models_errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n };\n /**\r\n * Checks the that fields in the PushSubscription are equivalent to the\r\n * details stores in the masterTokenDetails.\r\n * @private\r\n * @param {PushSubscription} subscription The push subscription we expect\r\n * the master token to match.\r\n * @param {Object} masterTokenDetails The saved details we wish to compare\r\n * with the PushSubscription\r\n * @return {boolean} true if the subscription and token details are\r\n * equivalent.\r\n */\n TokenManager.prototype.isSameSubscription_ = function (subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return subscription.endpoint === masterTokenDetails['endpoint'] && array_buffer_to_base64(subscription['getKey']('auth')) === masterTokenDetails['auth'] && array_buffer_to_base64(subscription['getKey']('p256dh')) === masterTokenDetails['p256dh'];\n };\n /**\r\n * Save the details for the fcm token for re-use at a later date.\r\n * @private\r\n * @param {string} senderId The 'messagingSenderId' used for this project\r\n * @param {ServiceWorkerRegistration} swRegistration The service worker\r\n * used to subscribe the user for web push\r\n * @param {PushSubscription} subscription The push subscription passed to\r\n * FCM for the current token.\r\n * @param {string} fcmToken The FCM token currently used on this\r\n * device.\r\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\r\n * @return {Promise}\r\n */\n TokenManager.prototype.saveTokenDetails_ = function (senderId, swRegistration, subscription, fcmToken, fcmPushSet) {\n var details = {\n swScope: swRegistration.scope,\n endpoint: subscription.endpoint,\n auth: array_buffer_to_base64(subscription['getKey']('auth')),\n p256dh: array_buffer_to_base64(subscription['getKey']('p256dh')),\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n fcmSenderId: senderId\n };\n return this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.put(details);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n resolve();\n };\n });\n });\n };\n /**\r\n * Returns the saved FCM Token if one is available and still valid,\r\n * otherwise `null` is returned.\r\n * @param {string} senderId This should be the sender ID associated with the\r\n * FCM Token being retrieved.\r\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\r\n * to subscribe the user to push.\r\n * @return {Promise | Promise} Returns the saved FCM Token if\r\n * avilable and valid.\r\n * @export\r\n */\n TokenManager.prototype.getSavedToken = function (senderId, swRegistration) {\n var _this = this;\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(models_errors.codes.SW_REGISTRATION_EXPECTED));\n }\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(models_errors.codes.BAD_SENDER_ID));\n }\n return this.getAllTokenDetailsForSenderId_(senderId).then(function (allTokenDetails) {\n if (allTokenDetails.length === 0) {\n return;\n }\n var index = allTokenDetails.findIndex(function (tokenDetails) {\n return swRegistration.scope === tokenDetails['swScope'] && senderId === tokenDetails['fcmSenderId'];\n });\n if (index === -1) {\n return;\n }\n return allTokenDetails[index];\n }).then(function (tokenDetails) {\n if (!tokenDetails) {\n return;\n }\n return swRegistration.pushManager.getSubscription().catch(function (err) {\n throw _this.errorFactory_.create(models_errors.codes.GET_SUBSCRIPTION_FAILED);\n }).then(function (subscription) {\n if (subscription && _this.isSameSubscription_(subscription, tokenDetails)) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n };\n /**\r\n * Creates a new FCM token.\r\n */\n TokenManager.prototype.createToken = function (senderId, swRegistration) {\n var _this = this;\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(this.errorFactory_.create(models_errors.codes.BAD_SENDER_ID));\n }\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(this.errorFactory_.create(models_errors.codes.SW_REGISTRATION_EXPECTED));\n }\n // Check for existing subscription first\n var subscription;\n var fcmTokenDetails;\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe(fcm_details.SUBSCRIPTION_OPTIONS);\n }).then(function (sub) {\n subscription = sub;\n return _this.subscribeToFCM(senderId, subscription);\n }).then(function (tokenDetails) {\n fcmTokenDetails = tokenDetails;\n return _this.saveTokenDetails_(senderId, swRegistration, subscription, fcmTokenDetails['token'], fcmTokenDetails['pushSet']);\n }).then(function () {\n return fcmTokenDetails['token'];\n });\n };\n /**\r\n * This method deletes details of the current FCM token.\r\n * It's returning a promise in case we need to move to an async\r\n * method for deleting at a later date.\r\n * @param {string} token Token to be deleted\r\n * @return {Promise} Resolves once the FCM token details have been\r\n * deleted and returns the deleted details.\r\n */\n TokenManager.prototype.deleteToken = function (token) {\n var _this = this;\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(this.errorFactory_.create(models_errors.codes.INVALID_DELETE_TOKEN));\n }\n return this.getTokenDetailsFromToken(token).then(function (details) {\n if (!details) {\n throw _this.errorFactory_.create(models_errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n return _this.openDatabase_().then(function (db) {\n return new Promise(function (resolve, reject) {\n var transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n var objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n var request = objectStore.delete(details['swScope']);\n request.onerror = function (event) {\n reject(event.target.error);\n };\n request.onsuccess = function (event) {\n if (event.target.result === 0) {\n reject(_this.errorFactory_.create(models_errors.codes.FAILED_TO_DELETE_TOKEN));\n return;\n }\n resolve(details);\n };\n });\n });\n });\n };\n return TokenManager;\n}();\n/* harmony default export */ var token_manager = (token_manager_TokenManager);\n// CONCATENATED MODULE: ./src/messaging/models/notification-permission.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n/* harmony default export */ var notification_permission = ({\n granted: 'granted',\n default: 'default',\n denied: 'denied'\n});\n// CONCATENATED MODULE: ./src/messaging/controllers/controller-interface.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId';\nvar controller_interface_ControllerInterface = /** @class */function () {\n /**\r\n * An interface of the Messaging Service API\r\n * @param {!firebase.app.App} app\r\n */\n function ControllerInterface(app) {\n var _this = this;\n this.errorFactory_ = new errors[\"a\" /* ErrorFactory */]('messaging', 'Messaging', models_errors.map);\n if (!app.options[SENDER_ID_OPTION_NAME] || typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw this.errorFactory_.create(models_errors.codes.BAD_SENDER_ID);\n }\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n this.tokenManager_ = new token_manager();\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = function () {\n return _this.delete;\n };\n }\n /**\r\n * @export\r\n * @return {Promise | Promise} Returns a promise that\r\n * resolves to an FCM token.\r\n */\n ControllerInterface.prototype.getToken = function () {\n var _this = this;\n // Check with permissions\n var currentPermission = this.getNotificationPermission_();\n if (currentPermission !== notification_permission.granted) {\n if (currentPermission === notification_permission.denied) {\n return Promise.reject(this.errorFactory_.create(models_errors.codes.NOTIFICATIONS_BLOCKED));\n }\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n return this.getSWRegistration_().then(function (registration) {\n return _this.tokenManager_.getSavedToken(_this.messagingSenderId_, registration).then(function (token) {\n if (token) {\n return token;\n }\n return _this.tokenManager_.createToken(_this.messagingSenderId_, registration);\n });\n });\n };\n /**\r\n * This method deletes tokens that the token manager looks after and then\r\n * unregisters the push subscription if it exists.\r\n * @export\r\n * @param {string} token\r\n * @return {Promise}\r\n */\n ControllerInterface.prototype.deleteToken = function (token) {\n var _this = this;\n return this.tokenManager_.deleteToken(token).then(function () {\n return _this.getSWRegistration_().then(function (registration) {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n }).then(function (subscription) {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n };\n ControllerInterface.prototype.getSWRegistration_ = function () {\n throw this.errorFactory_.create(models_errors.codes.SHOULD_BE_INHERITED);\n };\n //\n // The following methods should only be available in the window.\n //\n ControllerInterface.prototype.requestPermission = function () {\n throw this.errorFactory_.create(models_errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\r\n * @export\r\n * @param {!ServiceWorkerRegistration} registration\r\n */\n ControllerInterface.prototype.useServiceWorker = function (registration) {\n throw this.errorFactory_.create(models_errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\r\n * @export\r\n * @param {!firebase.Observer|function(*)} nextOrObserver\r\n * @param {function(!Error)=} optError\r\n * @param {function()=} optCompleted\r\n * @return {!function()}\r\n */\n ControllerInterface.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(models_errors.codes.AVAILABLE_IN_WINDOW);\n };\n /**\r\n * @export\r\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\r\n * or a function triggered on token refresh.\r\n * @param {function(!Error)=} optError Optional A function\r\n * triggered on token refresh error.\r\n * @param {function()=} optCompleted Optional function triggered when the\r\n * observer is removed.\r\n * @return {!function()} The unsubscribe function for the observer.\r\n */\n ControllerInterface.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(models_errors.codes.AVAILABLE_IN_WINDOW);\n };\n //\n // The following methods are used by the service worker only.\n //\n /**\r\n * @export\r\n * @param {function(Object)} callback\r\n */\n ControllerInterface.prototype.setBackgroundMessageHandler = function (callback) {\n throw this.errorFactory_.create(models_errors.codes.AVAILABLE_IN_SW);\n };\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n /**\r\n * This method is required to adhere to the Firebase interface.\r\n * It closes any currently open indexdb database connections.\r\n */\n ControllerInterface.prototype.delete = function () {\n this.tokenManager_.closeDatabase();\n };\n /**\r\n * Returns the current Notification Permission state.\r\n * @private\r\n * @return {string} The currenct permission state.\r\n */\n ControllerInterface.prototype.getNotificationPermission_ = function () {\n return Notification.permission;\n };\n /**\r\n * @protected\r\n * @returns {TokenManager}\r\n */\n ControllerInterface.prototype.getTokenManager = function () {\n return this.tokenManager_;\n };\n return ControllerInterface;\n}();\n/* harmony default export */ var controller_interface = (controller_interface_ControllerInterface);\n// CONCATENATED MODULE: ./src/messaging/models/worker-page-message.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\n\nvar PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nvar msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\nvar createNewMsg = function createNewMsg(msgType, msgData) {\n var message = (_a = {}, _a[PARAMS.TYPE_OF_MSG] = msgType, _a[PARAMS.DATA] = msgData, _a);\n return message;\n var _a;\n};\n/* harmony default export */ var worker_page_message = ({\n PARAMS: PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg: createNewMsg\n});\n// CONCATENATED MODULE: ./src/messaging/models/default-sw.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n/* harmony default export */ var default_sw = ({\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n});\n// EXTERNAL MODULE: ./src/app/subscribe.ts\nvar subscribe = __webpack_require__(31);\n\n// CONCATENATED MODULE: ./src/messaging/controllers/window-controller.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar __extends = this && this.__extends || function () {\n var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) {\n if (b.hasOwnProperty(p)) d[p] = b[p];\n }\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() {\n this.constructor = d;\n }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n}();\n\n\n\n\n\n\nvar window_controller_WindowController = /** @class */function (_super) {\n __extends(WindowController, _super);\n /**\r\n * A service that provides a MessagingService instance.\r\n * @param {!firebase.app.App} app\r\n */\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n /**\r\n * @private\r\n * @type {ServiceWorkerRegistration}\r\n */\n _this.registrationToUse_;\n /**\r\n * @private\r\n * @type {Promise}\r\n */\n _this.manifestCheckPromise_;\n /**\r\n * @private\r\n * @type {firebase.Observer}\r\n */\n _this.messageObserver_ = null;\n /**\r\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\r\n * observer.\r\n */\n _this.onMessage_ = Object(subscribe[\"a\" /* createSubscribe */])(function (observer) {\n _this.messageObserver_ = observer;\n });\n /**\r\n * @private\r\n * @type {firebase.Observer}\r\n */\n _this.tokenRefreshObserver_ = null;\n _this.onTokenRefresh_ = Object(subscribe[\"a\" /* createSubscribe */])(function (observer) {\n _this.tokenRefreshObserver_ = observer;\n });\n _this.setupSWMessageListener_();\n return _this;\n }\n /**\r\n * This method returns an FCM token if it can be generated.\r\n * The return promise will reject if the browser doesn't support\r\n * FCM, if permission is denied for notifications or it's not\r\n * possible to generate a token.\r\n * @export\r\n * @return {Promise | Promise} Returns a promise the\r\n * resolves to an FCM token or null if permission isn't granted.\r\n */\n WindowController.prototype.getToken = function () {\n var _this = this;\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(this.errorFactory_.create(models_errors.codes.UNSUPPORTED_BROWSER));\n }\n return this.manifestCheck_().then(function () {\n return _super.prototype.getToken.call(_this);\n });\n };\n /**\r\n * The method checks that a manifest is defined and has the correct GCM\r\n * sender ID.\r\n * @private\r\n * @return {Promise} Returns a promise that resolves if the manifest matches\r\n * our required sender ID\r\n */\n WindowController.prototype.manifestCheck_ = function () {\n var _this = this;\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n var manifestTag = document.querySelector('link[rel=\"manifest\"]');\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n } else {\n this.manifestCheckPromise_ = fetch(manifestTag.href).then(function (response) {\n return response.json();\n }).catch(function () {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n }).then(function (manifestContent) {\n if (!manifestContent) {\n return;\n }\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw _this.errorFactory_.create(models_errors.codes.INCORRECT_GCM_SENDER_ID);\n }\n });\n }\n return this.manifestCheckPromise_;\n };\n /**\r\n * Request permission if it is not currently granted\r\n * @export\r\n * @returns {Promise} Resolves if the permission was granted, otherwise\r\n * rejects\r\n */\n WindowController.prototype.requestPermission = function () {\n var _this = this;\n if (Notification.permission === notification_permission.granted) {\n return Promise.resolve();\n }\n return new Promise(function (resolve, reject) {\n var managePermissionResult = function managePermissionResult(result) {\n if (result === notification_permission.granted) {\n return resolve();\n } else if (result === notification_permission.denied) {\n return reject(_this.errorFactory_.create(models_errors.codes.PERMISSION_BLOCKED));\n } else {\n return reject(_this.errorFactory_.create(models_errors.codes.PERMISSION_DEFAULT));\n }\n };\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n var permissionPromise = Notification.requestPermission(function (result) {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n managePermissionResult(result);\n });\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n };\n /**\r\n * This method allows a developer to override the default service worker and\r\n * instead use a custom service worker.\r\n * @export\r\n * @param {!ServiceWorkerRegistration} registration The service worker\r\n * registration that should be used to receive the push messages.\r\n */\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(models_errors.codes.SW_REGISTRATION_EXPECTED);\n }\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(models_errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n this.registrationToUse_ = registration;\n };\n /**\r\n * @export\r\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\r\n * or a function triggered on message.\r\n * @param {function(!Error)=} optError Optional A function triggered on\r\n * message error.\r\n * @param {function()=} optCompleted Optional function triggered when the\r\n * observer is removed.\r\n * @return {!function()} The unsubscribe function for the observer.\r\n */\n WindowController.prototype.onMessage = function (nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n };\n /**\r\n * @export\r\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\r\n * or a function triggered on token refresh.\r\n * @param {function(!Error)=} optError Optional A function\r\n * triggered on token refresh error.\r\n * @param {function()=} optCompleted Optional function triggered when the\r\n * observer is removed.\r\n * @return {!function()} The unsubscribe function for the observer.\r\n */\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n };\n /**\r\n * Given a registration, wait for the service worker it relates to\r\n * become activer\r\n * @private\r\n * @param {ServiceWorkerRegistration} registration Registration to wait\r\n * for service worker to become active\r\n * @return {Promise} Wait for service worker\r\n * registration to become active\r\n */\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var _this = this;\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(_this.errorFactory_.create(models_errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(models_errors.codes.SW_REG_REDUNDANT));\n return;\n }\n var stateChangeListener = function stateChangeListener() {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n } else if (serviceWorker.state === 'redundant') {\n reject(_this.errorFactory_.create(models_errors.codes.SW_REG_REDUNDANT));\n } else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\r\n * This will regiater the default service worker and return the registration\r\n * @private\r\n * @return {Promise} The service worker\r\n * registration to be used for the push service.\r\n */\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n return navigator.serviceWorker.register(default_sw.path, {\n scope: default_sw.scope\n }).catch(function (err) {\n throw _this.errorFactory_.create(models_errors.codes.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n }).then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse_ = registration;\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n return registration;\n });\n });\n };\n /**\r\n * This method will set up a message listener to handle\r\n * events from the service worker that should trigger\r\n * events in the page.\r\n *\r\n * @private\r\n */\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n if (!('serviceWorker' in navigator)) {\n return;\n }\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n var workerPageMessage = event.data;\n switch (workerPageMessage[worker_page_message.PARAMS.TYPE_OF_MSG]) {\n case worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[worker_page_message.PARAMS.DATA];\n _this.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n }, false);\n };\n /**\r\n * Checks to see if the required API's are valid or not.\r\n * @private\r\n * @return {boolean} Returns true if the desired APIs are available.\r\n */\n WindowController.prototype.isSupported_ = function () {\n return 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window && 'fetch' in window && ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') && PushSubscription.prototype.hasOwnProperty('getKey');\n };\n return WindowController;\n}(controller_interface);\n/* harmony default export */ var window_controller = (window_controller_WindowController);\n// CONCATENATED MODULE: ./src/messaging/controllers/sw-controller.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nvar sw_controller___extends = this && this.__extends || function () {\n var extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) {\n if (b.hasOwnProperty(p)) d[p] = b[p];\n }\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() {\n this.constructor = d;\n }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n}();\n\n\n\n\nvar FCM_MSG = 'FCM_MSG';\nvar sw_controller_SWController = /** @class */function (_super) {\n sw_controller___extends(SWController, _super);\n function SWController(app) {\n var _this = _super.call(this, app) || this;\n self.addEventListener('push', function (e) {\n return _this.onPush_(e);\n }, false);\n self.addEventListener('pushsubscriptionchange', function (e) {\n return _this.onSubChange_(e);\n }, false);\n self.addEventListener('notificationclick', function (e) {\n return _this.onNotificationClick_(e);\n }, false);\n /**\r\n * @private\r\n * @type {function(Object)|null}\r\n */\n _this.bgMessageHandler_ = null;\n return _this;\n }\n /**\r\n * A handler for push events that shows notifications based on the content of\r\n * the payload.\r\n *\r\n * The payload must be a JSON-encoded Object with a `notification` key. The\r\n * value of the `notification` property will be used as the NotificationOptions\r\n * object passed to showNotification. Additionally, the `title` property of the\r\n * notification object will be used as the title.\r\n *\r\n * If there is no notification data in the payload then no notification will be\r\n * shown.\r\n * @private\r\n */\n SWController.prototype.onPush_ = function (event) {\n var _this = this;\n var msgPayload;\n try {\n msgPayload = event.data.json();\n } catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n var handleMsgPromise = this.hasVisibleClients_().then(function (hasVisibleClients) {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || _this.bgMessageHandler_) {\n // Send to page\n return _this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n var notificationDetails = _this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n var notificationTitle = notificationDetails.title || '';\n return self.registration.showNotification(notificationTitle, notificationDetails);\n } else if (_this.bgMessageHandler_) {\n return _this.bgMessageHandler_(msgPayload);\n }\n });\n event.waitUntil(handleMsgPromise);\n };\n /**\r\n * @private\r\n */\n SWController.prototype.onSubChange_ = function (event) {\n var _this = this;\n var promiseChain = this.getToken().then(function (token) {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw _this.errorFactory_.create(models_errors.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE);\n }\n var tokenDetails = null;\n var tokenManager = _this.getTokenManager();\n return tokenManager.getTokenDetailsFromToken(token).then(function (details) {\n tokenDetails = details;\n if (!tokenDetails) {\n throw _this.errorFactory_.create(models_errors.codes.INVALID_SAVED_TOKEN);\n }\n // Attempt to get a new subscription\n return self.registration.pushManager.subscribe(fcm_details.SUBSCRIPTION_OPTIONS);\n }).then(function (newSubscription) {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(tokenDetails.fcmSenderId, newSubscription, tokenDetails.fcmPushSet);\n }).catch(function (err) {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken).then(function () {\n throw _this.errorFactory_.create(models_errors.codes.UNABLE_TO_RESUBSCRIBE, {\n message: err\n });\n });\n });\n });\n event.waitUntil(promiseChain);\n };\n /**\r\n * @private\r\n */\n SWController.prototype.onNotificationClick_ = function (event) {\n var _this = this;\n if (!(event.notification && event.notification.data && event.notification.data[FCM_MSG])) {\n // Not an FCM notification, do nothing.\n return;\n }\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n var msgPayload = event.notification.data[FCM_MSG];\n var clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n var promiseChain = this.getWindowClient_(clickAction).then(function (windowClient) {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return self.clients.openWindow(clickAction);\n }\n return windowClient;\n }).then(function (windowClient) {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n // Delete notification data from payload before sending to the page.\n var notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.NOTIFICATION_CLICKED, msgPayload);\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return _this.attemptToMessageClient_(windowClient, internalMsg);\n });\n event.waitUntil(promiseChain);\n };\n /**\r\n * @private\r\n * @param {Object} msgPayload\r\n * @return {NotificationOptions|undefined}\r\n */\n SWController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n if (_typeof(msgPayload.notification) !== 'object') {\n return;\n }\n var notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = (_a = {}, _a[FCM_MSG] = msgPayload, _a);\n return notificationInformation;\n var _a;\n };\n /**\r\n * Calling setBackgroundMessageHandler will opt in to some specific\r\n * behaviours.\r\n * 1.) If a notification doesn't need to be shown due to a window already\r\n * being visible, then push messages will be sent to the page.\r\n * 2.) If a notification needs to be shown, and the message contains no\r\n * notification data this method will be called\r\n * and the promise it returns will be passed to event.waitUntil.\r\n * If you do not set this callback then all push messages will let and the\r\n * developer can handle them in a their own 'push' event callback\r\n * @export\r\n * @param {function(Object)} callback The callback to be called when a push\r\n * message is received and a notification must be shown. The callback will\r\n * be given the data from the push message.\r\n */\n SWController.prototype.setBackgroundMessageHandler = function (callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(models_errors.codes.BG_HANDLER_FUNCTION_EXPECTED);\n }\n this.bgMessageHandler_ = callback;\n };\n /**\r\n * @private\r\n * @param {string} url The URL to look for when focusing a client.\r\n * @return {Object} Returns an existing window client or a newly opened\r\n * WindowClient.\r\n */\n SWController.prototype.getWindowClient_ = function (url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n var parsedURL = new URL(url).href;\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n }).then(function (clientList) {\n var suitableClient = null;\n for (var i = 0; i < clientList.length; i++) {\n var parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n };\n /**\r\n * This message will attempt to send the message to a window client.\r\n * @private\r\n * @param {Object} client The WindowClient to send the message to.\r\n * @param {Object} message The message to send to the client.\r\n * @returns {Promise} Returns a promise that resolves after sending the\r\n * message. This does not guarantee that the message was successfully\r\n * received.\r\n */\n SWController.prototype.attemptToMessageClient_ = function (client, message) {\n var _this = this;\n return new Promise(function (resolve, reject) {\n if (!client) {\n return reject(_this.errorFactory_.create(models_errors.codes.NO_WINDOW_CLIENT_TO_MSG));\n }\n client.postMessage(message);\n resolve();\n });\n };\n /**\r\n * @private\r\n * @returns {Promise} If there is currently a visible WindowClient,\r\n * this method will resolve to true, otherwise false.\r\n */\n SWController.prototype.hasVisibleClients_ = function () {\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n }).then(function (clientList) {\n return clientList.some(function (client) {\n return client.visibilityState === 'visible';\n });\n });\n };\n /**\r\n * @private\r\n * @param {Object} msgPayload The data from the push event that should be sent\r\n * to all available pages.\r\n * @returns {Promise} Returns a promise that resolves once the message\r\n * has been sent to all WindowClients.\r\n */\n SWController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n var _this = this;\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n }).then(function (clientList) {\n var internalMsg = worker_page_message.createNewMsg(worker_page_message.TYPES_OF_MSG.PUSH_MSG_RECEIVED, msgPayload);\n return Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }));\n });\n };\n /**\r\n * This will register the default service worker and return the registration.\r\n * @private\r\n * @return {Promise} The service worker\r\n * registration to be used for the push service.\r\n */\n SWController.prototype.getSWRegistration_ = function () {\n return Promise.resolve(self.registration);\n };\n return SWController;\n}(controller_interface);\n/* harmony default export */ var sw_controller = (sw_controller_SWController);\n// EXTERNAL MODULE: ./src/app.ts + 1 modules\nvar src_app = __webpack_require__(9);\n\n// CONCATENATED MODULE: ./src/messaging.ts\n/* harmony export (immutable) */ __webpack_exports__[\"registerMessaging\"] = registerMessaging;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\nfunction registerMessaging(instance) {\n var messagingName = 'messaging';\n var factoryMethod = function factoryMethod(app) {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new sw_controller(app);\n }\n // Assume we are in the window context.\n return new window_controller(app);\n };\n var namespaceExports = {\n // no-inline\n Messaging: window_controller\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\nregisterMessaging(src_app[\"default\"]);\n\n/***/ })\n\n},[61]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-messaging.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-messaging.js","/**\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 */\nfunction toBase64(arrayBuffer) {\n const uint8Version = new Uint8Array(arrayBuffer);\n return window.btoa(String.fromCharCode.apply(null, uint8Version));\n}\n\nexport default arrayBuffer => {\n const base64String = toBase64(arrayBuffer);\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/helpers/array-buffer-to-base64.ts","/**\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'use strict';\n\nimport WindowController from './messaging/controllers/window-controller';\nimport SWController from './messaging/controllers/sw-controller';\nimport firebase from './app';\n\nexport function registerMessaging(instance) {\n const messagingName = 'messaging';\n const factoryMethod = app => {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n return new SWController(app);\n }\n\n // Assume we are in the window context.\n return new WindowController(app);\n };\n\n const namespaceExports = {\n // no-inline\n Messaging: WindowController\n };\n\n instance.INTERNAL.registerService(\n messagingName,\n factoryMethod,\n namespaceExports\n );\n}\n\nregisterMessaging(firebase);\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging.ts","/**\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'use strict';\n\nconst CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key'\n};\n\nconst ERROR_MAP = {\n [CODES.AVAILABLE_IN_WINDOW]: 'This method is available in a Window context.',\n [CODES.AVAILABLE_IN_SW]:\n 'This method is available in a service worker ' + 'context.',\n [CODES.SHOULD_BE_INHERITED]:\n 'This method should be overriden by ' + 'extended classes.',\n [CODES.BAD_SENDER_ID]:\n \"Please ensure that 'messagingSenderId' is set \" +\n 'correctly in the options passed into firebase.initializeApp().',\n [CODES.PERMISSION_DEFAULT]:\n 'The required permissions were not granted and ' + 'dismissed instead.',\n [CODES.PERMISSION_BLOCKED]:\n 'The required permissions were not granted and ' + 'blocked instead.',\n [CODES.UNSUPPORTED_BROWSER]:\n \"This browser doesn't support the API's \" +\n 'required to use the firebase SDK.',\n [CODES.NOTIFICATIONS_BLOCKED]: 'Notifications have been blocked.',\n [CODES.FAILED_DEFAULT_REGISTRATION]:\n 'We are unable to register the ' +\n 'default service worker. {$browserErrorMessage}',\n [CODES.SW_REGISTRATION_EXPECTED]:\n 'A service worker registration was the ' + 'expected input.',\n [CODES.GET_SUBSCRIPTION_FAILED]:\n 'There was an error when trying to get ' +\n 'any existing Push Subscriptions.',\n [CODES.INVALID_SAVED_TOKEN]: 'Unable to access details of the saved token.',\n [CODES.SW_REG_REDUNDANT]:\n 'The service worker being used for push was made ' + 'redundant.',\n [CODES.TOKEN_SUBSCRIBE_FAILED]:\n 'A problem occured while subscribing the ' + 'user to FCM: {$message}',\n [CODES.TOKEN_SUBSCRIBE_NO_TOKEN]:\n 'FCM returned no token when subscribing ' + 'the user to push.',\n [CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET]:\n 'FCM returned an invalid response ' + 'when getting an FCM token.',\n [CODES.USE_SW_BEFORE_GET_TOKEN]:\n 'You must call useServiceWorker() before ' +\n 'calling getToken() to ensure your service worker is used.',\n [CODES.INVALID_DELETE_TOKEN]:\n 'You must pass a valid token into ' +\n 'deleteToken(), i.e. the token from getToken().',\n [CODES.DELETE_TOKEN_NOT_FOUND]:\n 'The deletion attempt for token could not ' +\n 'be performed as the token was not found.',\n [CODES.DELETE_SCOPE_NOT_FOUND]:\n 'The deletion attempt for service worker ' +\n 'scope could not be performed as the scope was not found.',\n [CODES.BG_HANDLER_FUNCTION_EXPECTED]:\n 'The input to ' + 'setBackgroundMessageHandler() must be a function.',\n [CODES.NO_WINDOW_CLIENT_TO_MSG]:\n 'An attempt was made to message a ' + 'non-existant window client.',\n [CODES.UNABLE_TO_RESUBSCRIBE]:\n 'There was an error while re-subscribing ' +\n 'the FCM token for push messaging. Will have to resubscribe the ' +\n 'user on next visit. {$message}',\n [CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE]:\n 'Could not find an FCM token ' +\n 'and as a result, unable to resubscribe. Will have to resubscribe the ' +\n 'user on next visit.',\n [CODES.FAILED_TO_DELETE_TOKEN]: 'Unable to delete the currently saved token.',\n [CODES.NO_SW_IN_REG]:\n 'Even though the service worker registration was ' +\n 'successful, there was a problem accessing the service worker itself.',\n [CODES.INCORRECT_GCM_SENDER_ID]:\n \"Please change your web app manifest's \" +\n \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\",\n [CODES.BAD_SCOPE]:\n 'The service worker scope must be a string with at ' +\n 'least one character.',\n [CODES.BAD_VAPID_KEY]:\n 'The public VAPID key must be a string with at ' + 'least one character.',\n [CODES.BAD_SUBSCRIPTION]:\n 'The subscription must be a valid ' + 'PushSubscription.',\n [CODES.BAD_TOKEN]:\n 'The FCM Token used for storage / lookup was not ' +\n 'a valid token string.',\n [CODES.BAD_PUSH_SET]:\n 'The FCM push set used for storage / lookup was not ' +\n 'not a valid push set string.',\n [CODES.FAILED_DELETE_VAPID_KEY]: 'The VAPID key could not be deleted.'\n};\n\nexport default {\n codes: CODES,\n map: ERROR_MAP\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/errors.ts","/**\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'use strict';\n\nconst FCM_APPLICATION_SERVER_KEY = [\n 0x04,\n 0x33,\n 0x94,\n 0xf7,\n 0xdf,\n 0xa1,\n 0xeb,\n 0xb1,\n 0xdc,\n 0x03,\n 0xa2,\n 0x5e,\n 0x15,\n 0x71,\n 0xdb,\n 0x48,\n 0xd3,\n 0x2e,\n 0xed,\n 0xed,\n 0xb2,\n 0x34,\n 0xdb,\n 0xb7,\n 0x47,\n 0x3a,\n 0x0c,\n 0x8f,\n 0xc4,\n 0xcc,\n 0xe1,\n 0x6f,\n 0x3c,\n 0x8c,\n 0x84,\n 0xdf,\n 0xab,\n 0xb6,\n 0x66,\n 0x3e,\n 0xf2,\n 0x0c,\n 0xd4,\n 0x8b,\n 0xfe,\n 0xe3,\n 0xf9,\n 0x76,\n 0x2f,\n 0x14,\n 0x1c,\n 0x63,\n 0x08,\n 0x6a,\n 0x6f,\n 0x2d,\n 0xb1,\n 0x1a,\n 0x95,\n 0xb0,\n 0xce,\n 0x37,\n 0xc0,\n 0x9c,\n 0x6e\n];\n\nconst SUBSCRIPTION_DETAILS = {\n userVisibleOnly: true,\n applicationServerKey: new Uint8Array(FCM_APPLICATION_SERVER_KEY)\n};\n\nexport default {\n ENDPOINT: 'https://fcm.googleapis.com',\n APPLICATION_SERVER_KEY: FCM_APPLICATION_SERVER_KEY,\n SUBSCRIPTION_OPTIONS: SUBSCRIPTION_DETAILS\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/fcm-details.ts","/**\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'use strict';\n\nimport { ErrorFactory } from '../../app/errors';\n\nimport Errors from './errors';\nimport arrayBufferToBase64 from '../helpers/array-buffer-to-base64';\nimport FCMDetails from './fcm-details';\n\nconst FCM_TOKEN_DETAILS_DB = 'fcm_token_details_db';\nconst FCM_TOKEN_OBJ_STORE = 'fcm_token_object_Store';\nconst FCM_TOKEN_DETAILS_DB_VERSION = 1;\n\nexport default class TokenManager {\n private errorFactory_: ErrorFactory;\n private openDbPromise_: Promise;\n\n constructor() {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n this.openDbPromise_ = null;\n }\n\n /**\n * Get the indexedDB as a promsie.\n * @private\n * @return {Promise} The IndexedDB database\n */\n openDatabase_() {\n if (this.openDbPromise_) {\n return this.openDbPromise_;\n }\n\n this.openDbPromise_ = new Promise((resolve, reject) => {\n const request = indexedDB.open(\n FCM_TOKEN_DETAILS_DB,\n FCM_TOKEN_DETAILS_DB_VERSION\n );\n request.onerror = event => {\n reject((event.target).error);\n };\n request.onsuccess = event => {\n resolve((event.target).result);\n };\n request.onupgradeneeded = event => {\n var db = (event.target).result;\n\n var objectStore = db.createObjectStore(FCM_TOKEN_OBJ_STORE, {\n keyPath: 'swScope'\n });\n\n // Make sure the sender ID can be searched\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n };\n });\n\n return this.openDbPromise_;\n }\n\n /**\n * Close the currently open database.\n * @return {Promise} Returns the result of the promise chain.\n */\n closeDatabase() {\n if (this.openDbPromise_) {\n return this.openDbPromise_.then(db => {\n db.close();\n this.openDbPromise_ = null;\n });\n }\n\n return Promise.resolve();\n }\n\n /**\n * Given a token, this method will look up the details in indexedDB.\n * @public\n * @param {string} fcmToken\n * @return {Promise} The details associated with that token.\n */\n getTokenDetailsFromToken(fcmToken) {\n return this.openDatabase_().then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const index = objectStore.index('fcmToken');\n const request = index.get(fcmToken);\n request.onerror = function(event) {\n reject((event.target).error);\n };\n request.onsuccess = function(event) {\n resolve((event.target).result);\n };\n });\n });\n }\n\n getTokenDetailsFromSWScope_(swScope) {\n return this.openDatabase_().then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const scopeRequest = objectStore.get(swScope);\n scopeRequest.onerror = event => {\n reject((event.target).error);\n };\n\n scopeRequest.onsuccess = event => {\n resolve((event.target).result);\n };\n });\n });\n }\n\n getAllTokenDetailsForSenderId_(senderId): Promise> {\n return this.openDatabase_().then(db => {\n return new Promise>((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE]);\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n\n const senderIdTokens = [];\n\n const cursorRequest = objectStore.openCursor();\n cursorRequest.onerror = event => {\n reject((event.target).error);\n };\n\n cursorRequest.onsuccess = event => {\n const cursor = (event.target).result;\n if (cursor) {\n if (cursor.value['fcmSenderId'] === senderId) {\n senderIdTokens.push(cursor.value);\n }\n cursor.continue();\n } else {\n resolve(senderIdTokens);\n }\n };\n });\n });\n }\n\n /**\n * Given a PushSubscription and messagingSenderId, get an FCM token.\n * @public\n * @param {string} senderId The 'messagingSenderId' to tie the token to.\n * @param {PushSubscription} subscription The PushSusbcription to \"federate\".\n * @param {string=} pushSet If defined this will swap the subscription for\n * matching FCM token.\n * @return {Promise} Returns the FCM token to be used in place\n * of the PushSubscription.\n */\n subscribeToFCM(senderId, subscription, pushSet?): Promise {\n const p256dh = arrayBufferToBase64(subscription['getKey']('p256dh'));\n const auth = arrayBufferToBase64(subscription['getKey']('auth'));\n\n let fcmSubscribeBody =\n `authorized_entity=${senderId}&` +\n `endpoint=${subscription.endpoint}&` +\n `encryption_key=${p256dh}&` +\n `encryption_auth=${auth}`;\n\n if (pushSet) {\n fcmSubscribeBody += `&pushSet=${pushSet}`;\n }\n\n const headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n\n const subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n\n return fetch(\n FCMDetails.ENDPOINT + '/fcm/connect/subscribe',\n subscribeOptions\n )\n .then(response => response.json())\n .then(response => {\n const fcmTokenResponse = response;\n if (fcmTokenResponse['error']) {\n const message = fcmTokenResponse['error']['message'];\n throw this.errorFactory_.create(Errors.codes.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n\n if (!fcmTokenResponse['token']) {\n throw this.errorFactory_.create(\n Errors.codes.TOKEN_SUBSCRIBE_NO_TOKEN\n );\n }\n\n if (!fcmTokenResponse['pushSet']) {\n throw this.errorFactory_.create(\n Errors.codes.TOKEN_SUBSCRIBE_NO_PUSH_SET\n );\n }\n\n return {\n token: fcmTokenResponse['token'],\n pushSet: fcmTokenResponse['pushSet']\n };\n });\n }\n\n /**\n * Checks the that fields in the PushSubscription are equivalent to the\n * details stores in the masterTokenDetails.\n * @private\n * @param {PushSubscription} subscription The push subscription we expect\n * the master token to match.\n * @param {Object} masterTokenDetails The saved details we wish to compare\n * with the PushSubscription\n * @return {boolean} true if the subscription and token details are\n * equivalent.\n */\n isSameSubscription_(subscription, masterTokenDetails) {\n // getKey() isn't defined in the PushSubscription externs file, hence\n // subscription['getKey']('').\n return (\n subscription.endpoint === masterTokenDetails['endpoint'] &&\n arrayBufferToBase64(subscription['getKey']('auth')) ===\n masterTokenDetails['auth'] &&\n arrayBufferToBase64(subscription['getKey']('p256dh')) ===\n masterTokenDetails['p256dh']\n );\n }\n\n /**\n * Save the details for the fcm token for re-use at a later date.\n * @private\n * @param {string} senderId The 'messagingSenderId' used for this project\n * @param {ServiceWorkerRegistration} swRegistration The service worker\n * used to subscribe the user for web push\n * @param {PushSubscription} subscription The push subscription passed to\n * FCM for the current token.\n * @param {string} fcmToken The FCM token currently used on this\n * device.\n * @param {string} fcmPushSet The FCM push tied to the fcm token.\n * @return {Promise}\n */\n saveTokenDetails_(\n senderId,\n swRegistration,\n subscription,\n fcmToken,\n fcmPushSet\n ) {\n const details = {\n swScope: swRegistration.scope,\n endpoint: subscription.endpoint,\n auth: arrayBufferToBase64(subscription['getKey']('auth')),\n p256dh: arrayBufferToBase64(subscription['getKey']('p256dh')),\n fcmToken: fcmToken,\n fcmPushSet: fcmPushSet,\n fcmSenderId: senderId\n };\n\n return this.openDatabase_().then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([FCM_TOKEN_OBJ_STORE], 'readwrite');\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const request = objectStore.put(details);\n request.onerror = event => {\n reject((event.target).error);\n };\n request.onsuccess = event => {\n resolve();\n };\n });\n });\n }\n\n /**\n * Returns the saved FCM Token if one is available and still valid,\n * otherwise `null` is returned.\n * @param {string} senderId This should be the sender ID associated with the\n * FCM Token being retrieved.\n * @param {ServiceWorkerRegistration} swRegistration Registration to be used\n * to subscribe the user to push.\n * @return {Promise | Promise} Returns the saved FCM Token if\n * avilable and valid.\n * @export\n */\n getSavedToken(senderId, swRegistration) {\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED)\n );\n }\n\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.BAD_SENDER_ID)\n );\n }\n\n return this.getAllTokenDetailsForSenderId_(senderId)\n .then(allTokenDetails => {\n if (allTokenDetails.length === 0) {\n return;\n }\n\n const index = allTokenDetails.findIndex(tokenDetails => {\n return (\n swRegistration.scope === tokenDetails['swScope'] &&\n senderId === tokenDetails['fcmSenderId']\n );\n });\n\n if (index === -1) {\n return;\n }\n\n return allTokenDetails[index];\n })\n .then(tokenDetails => {\n if (!tokenDetails) {\n return;\n }\n\n return swRegistration.pushManager\n .getSubscription()\n .catch(err => {\n throw this.errorFactory_.create(\n Errors.codes.GET_SUBSCRIPTION_FAILED\n );\n })\n .then(subscription => {\n if (\n subscription &&\n this.isSameSubscription_(subscription, tokenDetails)\n ) {\n return tokenDetails['fcmToken'];\n }\n });\n });\n }\n\n /**\n * Creates a new FCM token.\n */\n createToken(senderId, swRegistration): Promise {\n if (typeof senderId !== 'string' || senderId.length === 0) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.BAD_SENDER_ID)\n );\n }\n\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED)\n );\n }\n\n // Check for existing subscription first\n let subscription;\n let fcmTokenDetails;\n return swRegistration.pushManager\n .getSubscription()\n .then(subscription => {\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe(\n FCMDetails.SUBSCRIPTION_OPTIONS\n );\n })\n .then(sub => {\n subscription = sub;\n return this.subscribeToFCM(senderId, subscription);\n })\n .then(tokenDetails => {\n fcmTokenDetails = tokenDetails;\n return this.saveTokenDetails_(\n senderId,\n swRegistration,\n subscription,\n fcmTokenDetails['token'],\n fcmTokenDetails['pushSet']\n );\n })\n .then(() => fcmTokenDetails['token']);\n }\n\n /**\n * This method deletes details of the current FCM token.\n * It's returning a promise in case we need to move to an async\n * method for deleting at a later date.\n * @param {string} token Token to be deleted\n * @return {Promise} Resolves once the FCM token details have been\n * deleted and returns the deleted details.\n */\n deleteToken(token) {\n if (typeof token !== 'string' || token.length === 0) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.INVALID_DELETE_TOKEN)\n );\n }\n\n return this.getTokenDetailsFromToken(token).then(details => {\n if (!details) {\n throw this.errorFactory_.create(Errors.codes.DELETE_TOKEN_NOT_FOUND);\n }\n\n return this.openDatabase_().then(db => {\n return new Promise((resolve, reject) => {\n const transaction = db.transaction(\n [FCM_TOKEN_OBJ_STORE],\n 'readwrite'\n );\n const objectStore = transaction.objectStore(FCM_TOKEN_OBJ_STORE);\n const request = objectStore.delete(details['swScope']);\n request.onerror = event => {\n reject((event.target).error);\n };\n request.onsuccess = event => {\n if ((event.target).result === 0) {\n reject(\n this.errorFactory_.create(Errors.codes.FAILED_TO_DELETE_TOKEN)\n );\n return;\n }\n\n resolve(details);\n };\n });\n });\n });\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/token-manager.ts","/**\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'use strict';\n\nimport { ErrorFactory } from '../../app/errors';\nimport Errors from '../models/errors';\nimport TokenManager from '../models/token-manager';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\n\nconst SENDER_ID_OPTION_NAME = 'messagingSenderId';\n\nexport default class ControllerInterface {\n public app;\n public INTERNAL;\n protected errorFactory_;\n private messagingSenderId_: string;\n private tokenManager_: TokenManager;\n\n /**\n * An interface of the Messaging Service API\n * @param {!firebase.app.App} app\n */\n constructor(app) {\n this.errorFactory_ = new ErrorFactory('messaging', 'Messaging', Errors.map);\n\n if (\n !app.options[SENDER_ID_OPTION_NAME] ||\n typeof app.options[SENDER_ID_OPTION_NAME] !== 'string'\n ) {\n throw this.errorFactory_.create(Errors.codes.BAD_SENDER_ID);\n }\n\n this.messagingSenderId_ = app.options[SENDER_ID_OPTION_NAME];\n\n this.tokenManager_ = new TokenManager();\n\n this.app = app;\n this.INTERNAL = {};\n this.INTERNAL.delete = () => this.delete;\n }\n\n /**\n * @export\n * @return {Promise | Promise} Returns a promise that\n * resolves to an FCM token.\n */\n getToken() {\n // Check with permissions\n const currentPermission = this.getNotificationPermission_();\n if (currentPermission !== NOTIFICATION_PERMISSION.granted) {\n if (currentPermission === NOTIFICATION_PERMISSION.denied) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.NOTIFICATIONS_BLOCKED)\n );\n }\n\n // We must wait for permission to be granted\n return Promise.resolve(null);\n }\n\n return this.getSWRegistration_().then(registration => {\n return this.tokenManager_\n .getSavedToken(this.messagingSenderId_, registration)\n .then(token => {\n if (token) {\n return token;\n }\n\n return this.tokenManager_.createToken(\n this.messagingSenderId_,\n registration\n );\n });\n });\n }\n\n /**\n * This method deletes tokens that the token manager looks after and then\n * unregisters the push subscription if it exists.\n * @export\n * @param {string} token\n * @return {Promise}\n */\n deleteToken(token) {\n return this.tokenManager_.deleteToken(token).then(() => {\n return this.getSWRegistration_()\n .then(registration => {\n if (registration) {\n return registration.pushManager.getSubscription();\n }\n })\n .then(subscription => {\n if (subscription) {\n return subscription.unsubscribe();\n }\n });\n });\n }\n\n getSWRegistration_(): Promise {\n throw this.errorFactory_.create(Errors.codes.SHOULD_BE_INHERITED);\n }\n\n //\n // The following methods should only be available in the window.\n //\n\n requestPermission() {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n /**\n * @export\n * @param {!ServiceWorkerRegistration} registration\n */\n useServiceWorker(registration) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver\n * @param {function(!Error)=} optError\n * @param {function()=} optCompleted\n * @return {!function()}\n */\n onMessage(nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n onTokenRefresh(nextOrObserver, optError, optCompleted) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_WINDOW);\n }\n\n //\n // The following methods are used by the service worker only.\n //\n\n /**\n * @export\n * @param {function(Object)} callback\n */\n setBackgroundMessageHandler(callback) {\n throw this.errorFactory_.create(Errors.codes.AVAILABLE_IN_SW);\n }\n\n //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n\n /**\n * This method is required to adhere to the Firebase interface.\n * It closes any currently open indexdb database connections.\n */\n delete() {\n this.tokenManager_.closeDatabase();\n }\n\n /**\n * Returns the current Notification Permission state.\n * @private\n * @return {string} The currenct permission state.\n */\n getNotificationPermission_() {\n return (Notification as any).permission;\n }\n\n /**\n * @protected\n * @returns {TokenManager}\n */\n getTokenManager() {\n return this.tokenManager_;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/controllers/controller-interface.ts","/**\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'use strict';\n\n// These fields are strings to prevent closure from thinking goog.getMsg\n// should be used to initialise the values\nconst PARAMS = {\n TYPE_OF_MSG: 'firebase-messaging-msg-type',\n DATA: 'firebase-messaging-msg-data'\n};\n\n// This value isn't using the TYPE_OF_MSG short hand as closure\n// expects the variable to be defined via goog.getMsg\nconst msgType = {\n PUSH_MSG_RECEIVED: 'push-msg-received',\n NOTIFICATION_CLICKED: 'notification-clicked'\n};\n\nconst createNewMsg = (msgType, msgData) => {\n const message = {\n [PARAMS.TYPE_OF_MSG]: msgType,\n [PARAMS.DATA]: msgData\n };\n return message;\n};\n\nexport default {\n PARAMS,\n TYPES_OF_MSG: msgType,\n createNewMsg\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/worker-page-message.ts","/**\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'use strict';\n\nexport default {\n path: '/firebase-messaging-sw.js',\n scope: '/firebase-cloud-messaging-push-scope'\n};\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/models/default-sw.ts","/**\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'use strict';\n\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport DefaultSW from '../models/default-sw';\nimport NOTIFICATION_PERMISSION from '../models/notification-permission';\nimport { createSubscribe } from '../../app/subscribe';\n\ndeclare const firebase: any;\n\nexport default class WindowController extends ControllerInterface {\n private registrationToUse_;\n private manifestCheckPromise_;\n private messageObserver_;\n private onMessage_;\n private tokenRefreshObserver_;\n private onTokenRefresh_;\n\n /**\n * A service that provides a MessagingService instance.\n * @param {!firebase.app.App} app\n */\n constructor(app) {\n super(app);\n\n /**\n * @private\n * @type {ServiceWorkerRegistration}\n */\n this.registrationToUse_;\n\n /**\n * @private\n * @type {Promise}\n */\n this.manifestCheckPromise_;\n\n /**\n * @private\n * @type {firebase.Observer}\n */\n this.messageObserver_ = null;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the onMessage\n * observer.\n */\n this.onMessage_ = createSubscribe(observer => {\n this.messageObserver_ = observer;\n });\n\n /**\n * @private\n * @type {firebase.Observer}\n */\n this.tokenRefreshObserver_ = null;\n this.onTokenRefresh_ = createSubscribe(observer => {\n this.tokenRefreshObserver_ = observer;\n });\n\n this.setupSWMessageListener_();\n }\n\n /**\n * This method returns an FCM token if it can be generated.\n * The return promise will reject if the browser doesn't support\n * FCM, if permission is denied for notifications or it's not\n * possible to generate a token.\n * @export\n * @return {Promise | Promise} Returns a promise the\n * resolves to an FCM token or null if permission isn't granted.\n */\n getToken() {\n // Check that the required API's are available\n if (!this.isSupported_()) {\n return Promise.reject(\n this.errorFactory_.create(Errors.codes.UNSUPPORTED_BROWSER)\n );\n }\n\n return this.manifestCheck_().then(() => {\n return super.getToken();\n });\n }\n\n /**\n * The method checks that a manifest is defined and has the correct GCM\n * sender ID.\n * @private\n * @return {Promise} Returns a promise that resolves if the manifest matches\n * our required sender ID\n */\n manifestCheck_() {\n if (this.manifestCheckPromise_) {\n return this.manifestCheckPromise_;\n }\n\n const manifestTag = document.querySelector(\n 'link[rel=\"manifest\"]'\n );\n if (!manifestTag) {\n this.manifestCheckPromise_ = Promise.resolve();\n } else {\n this.manifestCheckPromise_ = fetch(manifestTag.href)\n .then(response => {\n return response.json();\n })\n .catch(() => {\n // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n return Promise.resolve();\n })\n .then(manifestContent => {\n if (!manifestContent) {\n return;\n }\n\n if (!manifestContent['gcm_sender_id']) {\n return;\n }\n\n if (manifestContent['gcm_sender_id'] !== '103953800507') {\n throw this.errorFactory_.create(\n Errors.codes.INCORRECT_GCM_SENDER_ID\n );\n }\n });\n }\n\n return this.manifestCheckPromise_;\n }\n\n /**\n * Request permission if it is not currently granted\n * @export\n * @returns {Promise} Resolves if the permission was granted, otherwise\n * rejects\n */\n requestPermission() {\n if ((Notification as any).permission === NOTIFICATION_PERMISSION.granted) {\n return Promise.resolve();\n }\n\n return new Promise((resolve, reject) => {\n const managePermissionResult = result => {\n if (result === NOTIFICATION_PERMISSION.granted) {\n return resolve();\n } else if (result === NOTIFICATION_PERMISSION.denied) {\n return reject(\n this.errorFactory_.create(Errors.codes.PERMISSION_BLOCKED)\n );\n } else {\n return reject(\n this.errorFactory_.create(Errors.codes.PERMISSION_DEFAULT)\n );\n }\n };\n\n // The Notification.requestPermission API was changed to\n // return a promise so now have to handle both in case\n // browsers stop support callbacks for promised version\n const permissionPromise = Notification.requestPermission(result => {\n if (permissionPromise) {\n // Let the promise manage this\n return;\n }\n\n managePermissionResult(result);\n });\n\n if (permissionPromise) {\n // Prefer the promise version as it's the future API.\n permissionPromise.then(managePermissionResult);\n }\n });\n }\n\n /**\n * This method allows a developer to override the default service worker and\n * instead use a custom service worker.\n * @export\n * @param {!ServiceWorkerRegistration} registration The service worker\n * registration that should be used to receive the push messages.\n */\n useServiceWorker(registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw this.errorFactory_.create(Errors.codes.SW_REGISTRATION_EXPECTED);\n }\n\n if (typeof this.registrationToUse_ !== 'undefined') {\n throw this.errorFactory_.create(Errors.codes.USE_SW_BEFORE_GET_TOKEN);\n }\n\n this.registrationToUse_ = registration;\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function(*)} nextOrObserver An observer object\n * or a function triggered on message.\n * @param {function(!Error)=} optError Optional A function triggered on\n * message error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n onMessage(nextOrObserver, optError, optCompleted) {\n return this.onMessage_(nextOrObserver, optError, optCompleted);\n }\n\n /**\n * @export\n * @param {!firebase.Observer|function()} nextOrObserver An observer object\n * or a function triggered on token refresh.\n * @param {function(!Error)=} optError Optional A function\n * triggered on token refresh error.\n * @param {function()=} optCompleted Optional function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\n onTokenRefresh(nextOrObserver, optError, optCompleted) {\n return this.onTokenRefresh_(nextOrObserver, optError, optCompleted);\n }\n\n /**\n * Given a registration, wait for the service worker it relates to\n * become activer\n * @private\n * @param {ServiceWorkerRegistration} registration Registration to wait\n * for service worker to become active\n * @return {Promise} Wait for service worker\n * registration to become active\n */\n waitForRegistrationToActivate_(registration) {\n const serviceWorker =\n registration.installing || registration.waiting || registration.active;\n\n return new Promise((resolve, reject) => {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(this.errorFactory_.create(Errors.codes.NO_SW_IN_REG));\n return;\n }\n // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n\n if (serviceWorker.state === 'redundant') {\n reject(this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n return;\n }\n\n let stateChangeListener = () => {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n } else if (serviceWorker.state === 'redundant') {\n reject(this.errorFactory_.create(Errors.codes.SW_REG_REDUNDANT));\n } else {\n // Return early and wait to next state change\n return;\n }\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n }\n\n /**\n * This will regiater the default service worker and return the registration\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n getSWRegistration_() {\n if (this.registrationToUse_) {\n return this.waitForRegistrationToActivate_(this.registrationToUse_);\n }\n\n // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse_ is no longer undefined\n this.registrationToUse_ = null;\n\n return navigator.serviceWorker\n .register(DefaultSW.path, {\n scope: DefaultSW.scope\n })\n .catch(err => {\n throw this.errorFactory_.create(\n Errors.codes.FAILED_DEFAULT_REGISTRATION,\n {\n browserErrorMessage: err.message\n }\n );\n })\n .then(registration => {\n return this.waitForRegistrationToActivate_(registration).then(() => {\n this.registrationToUse_ = registration;\n\n // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n registration.update();\n\n return registration;\n });\n });\n }\n\n /**\n * This method will set up a message listener to handle\n * events from the service worker that should trigger\n * events in the page.\n *\n * @private\n */\n setupSWMessageListener_() {\n if (!('serviceWorker' in navigator)) {\n return;\n }\n\n navigator.serviceWorker.addEventListener(\n 'message',\n event => {\n if (!event.data || !event.data[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n\n const workerPageMessage = event.data;\n switch (workerPageMessage[WorkerPageMessage.PARAMS.TYPE_OF_MSG]) {\n case WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED:\n case WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED:\n const pushMessage =\n workerPageMessage[WorkerPageMessage.PARAMS.DATA];\n this.messageObserver_.next(pushMessage);\n break;\n default:\n // Noop.\n break;\n }\n },\n false\n );\n }\n\n /**\n * Checks to see if the required API's are valid or not.\n * @private\n * @return {boolean} Returns true if the desired APIs are available.\n */\n isSupported_() {\n return (\n 'serviceWorker' in navigator &&\n 'PushManager' in window &&\n 'Notification' in window &&\n 'fetch' in window &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/controllers/window-controller.ts","/**\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'use strict';\n\nimport ControllerInterface from './controller-interface';\nimport Errors from '../models/errors';\nimport WorkerPageMessage from '../models/worker-page-message';\nimport FCMDetails from '../models/fcm-details';\n\nconst FCM_MSG = 'FCM_MSG';\n\nexport default class SWController extends ControllerInterface {\n private bgMessageHandler_: (input: Object) => Promise;\n\n constructor(app) {\n super(app);\n\n self.addEventListener('push', e => this.onPush_(e), false);\n self.addEventListener(\n 'pushsubscriptionchange',\n e => this.onSubChange_(e),\n false\n );\n self.addEventListener(\n 'notificationclick',\n e => this.onNotificationClick_(e),\n false\n );\n\n /**\n * @private\n * @type {function(Object)|null}\n */\n this.bgMessageHandler_ = null;\n }\n\n /**\n * A handler for push events that shows notifications based on the content of\n * the payload.\n *\n * The payload must be a JSON-encoded Object with a `notification` key. The\n * value of the `notification` property will be used as the NotificationOptions\n * object passed to showNotification. Additionally, the `title` property of the\n * notification object will be used as the title.\n *\n * If there is no notification data in the payload then no notification will be\n * shown.\n * @private\n */\n onPush_(event) {\n let msgPayload;\n try {\n msgPayload = event.data.json();\n } catch (err) {\n // Not JSON so not an FCM message\n return;\n }\n\n const handleMsgPromise = this.hasVisibleClients_().then(\n hasVisibleClients => {\n if (hasVisibleClients) {\n // Do not need to show a notification.\n if (msgPayload.notification || this.bgMessageHandler_) {\n // Send to page\n return this.sendMessageToWindowClients_(msgPayload);\n }\n return;\n }\n\n const notificationDetails = this.getNotificationData_(msgPayload);\n if (notificationDetails) {\n const notificationTitle = notificationDetails.title || '';\n return (self as any).registration.showNotification(\n notificationTitle,\n notificationDetails\n );\n } else if (this.bgMessageHandler_) {\n return this.bgMessageHandler_(msgPayload);\n }\n }\n );\n\n event.waitUntil(handleMsgPromise);\n }\n\n /**\n * @private\n */\n onSubChange_(event) {\n const promiseChain = this.getToken().then(token => {\n if (!token) {\n // We can't resubscribe if we don't have an FCM token for this scope.\n throw this.errorFactory_.create(\n Errors.codes.NO_FCM_TOKEN_FOR_RESUBSCRIBE\n );\n }\n\n let tokenDetails = null;\n const tokenManager = this.getTokenManager();\n return tokenManager\n .getTokenDetailsFromToken(token)\n .then(details => {\n tokenDetails = details;\n if (!tokenDetails) {\n throw this.errorFactory_.create(Errors.codes.INVALID_SAVED_TOKEN);\n }\n\n // Attempt to get a new subscription\n return (self as any).registration.pushManager.subscribe(\n FCMDetails.SUBSCRIPTION_OPTIONS\n );\n })\n .then(newSubscription => {\n // Send new subscription to FCM.\n return tokenManager.subscribeToFCM(\n tokenDetails.fcmSenderId,\n newSubscription,\n tokenDetails.fcmPushSet\n );\n })\n .catch(err => {\n // The best thing we can do is log this to the terminal so\n // developers might notice the error.\n return tokenManager.deleteToken(tokenDetails.fcmToken).then(() => {\n throw this.errorFactory_.create(\n Errors.codes.UNABLE_TO_RESUBSCRIBE,\n {\n message: err\n }\n );\n });\n });\n });\n\n event.waitUntil(promiseChain);\n }\n\n /**\n * @private\n */\n onNotificationClick_(event) {\n if (\n !(\n event.notification &&\n event.notification.data &&\n event.notification.data[FCM_MSG]\n )\n ) {\n // Not an FCM notification, do nothing.\n return;\n }\n\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n\n event.notification.close();\n\n const msgPayload = event.notification.data[FCM_MSG];\n const clickAction = msgPayload['notification']['click_action'];\n if (!clickAction) {\n // Nothing to do.\n return;\n }\n\n const promiseChain = this.getWindowClient_(clickAction)\n .then(windowClient => {\n if (!windowClient) {\n // Unable to find window client so need to open one.\n return (self as any).clients.openWindow(clickAction);\n }\n return windowClient;\n })\n .then(windowClient => {\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n\n // Delete notification data from payload before sending to the page.\n const notificationData = msgPayload['notification'];\n delete msgPayload['notification'];\n\n const internalMsg = WorkerPageMessage.createNewMsg(\n WorkerPageMessage.TYPES_OF_MSG.NOTIFICATION_CLICKED,\n msgPayload\n );\n // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n return this.attemptToMessageClient_(windowClient, internalMsg);\n });\n\n event.waitUntil(promiseChain);\n }\n\n /**\n * @private\n * @param {Object} msgPayload\n * @return {NotificationOptions|undefined}\n */\n getNotificationData_(msgPayload) {\n if (!msgPayload) {\n return;\n }\n\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n\n const notificationInformation = Object.assign({}, msgPayload.notification);\n // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n notificationInformation['data'] = {\n [FCM_MSG]: msgPayload\n };\n\n return notificationInformation;\n }\n\n /**\n * Calling setBackgroundMessageHandler will opt in to some specific\n * behaviours.\n * 1.) If a notification doesn't need to be shown due to a window already\n * being visible, then push messages will be sent to the page.\n * 2.) If a notification needs to be shown, and the message contains no\n * notification data this method will be called\n * and the promise it returns will be passed to event.waitUntil.\n * If you do not set this callback then all push messages will let and the\n * developer can handle them in a their own 'push' event callback\n * @export\n * @param {function(Object)} callback The callback to be called when a push\n * message is received and a notification must be shown. The callback will\n * be given the data from the push message.\n */\n setBackgroundMessageHandler(callback) {\n if (callback && typeof callback !== 'function') {\n throw this.errorFactory_.create(\n Errors.codes.BG_HANDLER_FUNCTION_EXPECTED\n );\n }\n\n this.bgMessageHandler_ = callback;\n }\n\n /**\n * @private\n * @param {string} url The URL to look for when focusing a client.\n * @return {Object} Returns an existing window client or a newly opened\n * WindowClient.\n */\n getWindowClient_(url) {\n // Use URL to normalize the URL when comparing to windowClients.\n // This at least handles whether to include trailing slashes or not\n const parsedURL = new URL(url).href;\n\n return (self as any).clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(clientList => {\n let suitableClient = null;\n for (let i = 0; i < clientList.length; i++) {\n const parsedClientUrl = new URL(clientList[i].url).href;\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n\n if (suitableClient) {\n suitableClient.focus();\n return suitableClient;\n }\n });\n }\n\n /**\n * This message will attempt to send the message to a window client.\n * @private\n * @param {Object} client The WindowClient to send the message to.\n * @param {Object} message The message to send to the client.\n * @returns {Promise} Returns a promise that resolves after sending the\n * message. This does not guarantee that the message was successfully\n * received.\n */\n attemptToMessageClient_(client, message) {\n return new Promise((resolve, reject) => {\n if (!client) {\n return reject(\n this.errorFactory_.create(Errors.codes.NO_WINDOW_CLIENT_TO_MSG)\n );\n }\n\n client.postMessage(message);\n resolve();\n });\n }\n\n /**\n * @private\n * @returns {Promise} If there is currently a visible WindowClient,\n * this method will resolve to true, otherwise false.\n */\n hasVisibleClients_() {\n return (self as any).clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(clientList => {\n return clientList.some(client => client.visibilityState === 'visible');\n });\n }\n\n /**\n * @private\n * @param {Object} msgPayload The data from the push event that should be sent\n * to all available pages.\n * @returns {Promise} Returns a promise that resolves once the message\n * has been sent to all WindowClients.\n */\n sendMessageToWindowClients_(msgPayload) {\n return (self as any).clients\n .matchAll({\n type: 'window',\n includeUncontrolled: true\n })\n .then(clientList => {\n const internalMsg = WorkerPageMessage.createNewMsg(\n WorkerPageMessage.TYPES_OF_MSG.PUSH_MSG_RECEIVED,\n msgPayload\n );\n\n return Promise.all(\n clientList.map(client => {\n return this.attemptToMessageClient_(client, internalMsg);\n })\n );\n });\n }\n\n /**\n * This will register the default service worker and return the registration.\n * @private\n * @return {Promise} The service worker\n * registration to be used for the push service.\n */\n getSWRegistration_() {\n return Promise.resolve((self as any).registration);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/messaging/controllers/sw-controller.ts","try {\n webpackJsonpFirebase([2],{\n\n/***/ 60:\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\nObject.defineProperty(__webpack_exports__, \"__esModule\", { value: true });\n\n// CONCATENATED MODULE: ./src/storage/implementation/constants.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Constants used in the Firebase Storage library.\r\n */\n/**\r\n * Domain and scheme for API calls.\r\n */\nvar domainBase = 'https://firebasestorage.googleapis.com';\n/**\r\n * Domain and scheme for object downloads.\r\n */\nvar downloadBase = 'https://firebasestorage.googleapis.com';\n/**\r\n * Base URL for non-upload calls to the API.\r\n */\nvar apiBaseUrl = '/v0';\n/**\r\n * Base URL for upload calls to the API.\r\n */\nvar apiUploadBaseUrl = '/v0';\nfunction setDomainBase(domainBase) {\n domainBase = domainBase;\n}\nvar configOption = 'storageBucket';\n/**\r\n * 1 minute\r\n */\nvar shortMaxOperationRetryTime = 1 * 60 * 1000;\n/**\r\n * 2 minutes\r\n */\nvar defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\r\n * 10 minutes\r\n */\nvar defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\r\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\r\n * enough for us to use it directly.\r\n */\nvar minSafeInteger = -9007199254740991;\n// CONCATENATED MODULE: ./src/storage/implementation/error.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar FirebaseStorageError = /** @class */function () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function get() {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function get() {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function get() {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function get() {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}();\n\nvar errors = {};\nvar Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\nfunction prependCode(code) {\n return 'storage/' + code;\n}\nfunction unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' + 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\nfunction objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\nfunction bucketNotFound(bucket) {\n return new FirebaseStorageError(Code.BUCKET_NOT_FOUND, \"Bucket '\" + bucket + \"' does not exist.\");\n}\nfunction projectNotFound(project) {\n return new FirebaseStorageError(Code.PROJECT_NOT_FOUND, \"Project '\" + project + \"' does not exist.\");\n}\nfunction quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" + bucket + \"' exceeded, please view quota on \" + 'https://firebase.google.com/pricing/.');\n}\nfunction unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' + 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\nfunction unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\nfunction retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\nfunction invalidChecksum(path, checksum, calculated) {\n return new FirebaseStorageError(Code.INVALID_CHECKSUM, \"Uploaded/downloaded object '\" + path + \"' has checksum '\" + checksum + \"' which does not match '\" + calculated + \"'. Please retry the upload/download.\");\n}\nfunction error_canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\nfunction invalidEventName(name) {\n return new FirebaseStorageError(Code.INVALID_EVENT_NAME, \"Invalid event name '\" + name + \"'.\");\n}\nfunction invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\nfunction invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\nfunction noDefaultBucket() {\n return new FirebaseStorageError(Code.NO_DEFAULT_BUCKET, 'No default bucket ' + \"found. Did you set the '\" + configOption + \"' property when initializing the app?\");\n}\nfunction cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\nfunction serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\nfunction noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\nfunction invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\nfunction invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n } else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' + fnName + '`: Expected ' + countPart + ' ' + plural + ', received ' + real + '.');\n}\nfunction appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\r\n * @param name The name of the operation that was invalid.\r\n */\nfunction invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" + name + \"' cannot be performed on a root reference, create a non-root \" + \"reference using child, such as .child('file.png').\");\n}\n/**\r\n * @param format The format that was not valid.\r\n * @param message A message describing the format violation.\r\n */\nfunction invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\r\n * @param message A message describing the internal error.\r\n */\nfunction internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n// CONCATENATED MODULE: ./src/storage/implementation/string.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\nfunction formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' + StringFormat.RAW + ', ' + StringFormat.BASE64 + ', ' + StringFormat.BASE64URL + ', ' + StringFormat.DATA_URL + '].';\n }\n}\n/**\r\n * @struct\r\n */\nvar StringData = /** @class */function () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n return StringData;\n}();\n\nfunction dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n // assert(false);\n throw unknown();\n}\nfunction utf8Bytes_(string) {\n var b = [];\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n } else {\n if (c <= 2047) {\n b.push(192 | c >> 6, 128 | c & 63);\n } else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 && (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n } else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | (hi & 1023) << 10 | lo & 1023;\n b.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);\n }\n } else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n } else {\n b.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\nfunction percentEncodedBytes_(string) {\n var decoded;\n try {\n decoded = decodeURIComponent(string);\n } catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n return utf8Bytes_(decoded);\n}\nfunction base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64:\n {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64url encoded?\");\n }\n break;\n }\n case StringFormat.BASE64URL:\n {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n var bytes;\n try {\n bytes = atob(string);\n } catch (e) {\n throw invalidFormat(format, 'Invalid character found');\n }\n var array = new Uint8Array(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n/**\r\n * @struct\r\n */\nvar string_DataURLParts = /** @class */function () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n var middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64 ? middle.substring(0, middle.length - ';base64'.length) : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n return DataURLParts;\n}();\nfunction dataURLBytes_(string) {\n var parts = new string_DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n } else {\n return percentEncodedBytes_(parts.rest);\n }\n}\nfunction dataURLContentType_(string) {\n var parts = new string_DataURLParts(string);\n return parts.contentType;\n}\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n return s.substring(s.length - end.length) === end;\n}\n// CONCATENATED MODULE: ./src/storage/implementation/taskenums.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\nvar TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nvar InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nvar TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\nfunction taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n// CONCATENATED MODULE: ./src/storage/implementation/object.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Contains methods for working with objects.\r\n */\nfunction contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\nfunction forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\nfunction clone(obj) {\n if (obj == null) {\n return {};\n }\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n// EXTERNAL MODULE: ./src/utils/promise.ts\nvar promise = __webpack_require__(3);\n\n// CONCATENATED MODULE: ./src/storage/implementation/promise_external.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Implements the promise abstraction interface for external\r\n * (public SDK) packaging, which just passes through to the firebase-app impl.\r\n */\n/**\r\n * @template T\r\n * @param {function((function(T): void),\r\n * (function(!Error): void))} resolver\r\n */\n\nfunction make(resolver) {\n return new promise[\"b\" /* PromiseImpl */](resolver);\n}\n/**\r\n * @template T\r\n */\nfunction promise_external_resolve(value) {\n return promise[\"b\" /* PromiseImpl */].resolve(value);\n}\nfunction promise_external_reject(error) {\n return promise[\"b\" /* PromiseImpl */].reject(error);\n}\n// CONCATENATED MODULE: ./src/storage/implementation/type.ts\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @return False if the object is undefined or null, true otherwise.\r\n */\nfunction isDef(p) {\n return p != null;\n}\nfunction isJustDef(p) {\n return p !== void 0;\n}\nfunction isFunction(p) {\n return typeof p === 'function';\n}\nfunction isObject(p) {\n return (typeof p === 'undefined' ? 'undefined' : _typeof(p)) === 'object';\n}\nfunction isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\nfunction isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\nfunction isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\nfunction isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\nfunction isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\nfunction isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n// CONCATENATED MODULE: ./src/storage/implementation/xhrio.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @enum{number}\r\n */\nvar ErrorCode;\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode || (ErrorCode = {}));\n// CONCATENATED MODULE: ./src/storage/implementation/xhrio_network.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n/**\r\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\r\n * doesn't work in React Native on Android.\r\n */\nvar xhrio_network_NetworkXhrIo = /** @class */function () {\n function NetworkXhrIo() {\n var _this = this;\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = make(function (resolve, reject) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = ErrorCode.ABORT;\n resolve(_this);\n });\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve(_this);\n });\n _this.xhr_.addEventListener('load', function (event) {\n resolve(_this);\n });\n });\n }\n /**\r\n * @override\r\n */\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (isDef(opt_headers)) {\n var headers = opt_headers;\n forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (isDef(opt_body)) {\n this.xhr_.send(opt_body);\n } else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n };\n /**\r\n * @override\r\n */\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n return this.errorCode_;\n };\n /**\r\n * @override\r\n */\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n } catch (e) {\n return -1;\n }\n };\n /**\r\n * @override\r\n */\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw internalError('cannot .getResponseText() before sending');\n }\n return this.xhr_.responseText;\n };\n /**\r\n * Aborts the request.\r\n * @override\r\n */\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\r\n * @override\r\n */\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\r\n * @override\r\n */\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\r\n * @override\r\n */\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n return NetworkXhrIo;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/xhriopool.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Factory-like class for creating XhrIo instances.\r\n */\nvar xhriopool_XhrIoPool = /** @class */function () {\n function XhrIoPool() {}\n XhrIoPool.prototype.createXhrIo = function () {\n return new xhrio_network_NetworkXhrIo();\n };\n return XhrIoPool;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/json.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Returns the Object resulting from parsing the given JSON, or null if the\r\n * given string does not represent a JSON object.\r\n */\nfunction jsonObjectOrNull(s) {\n var obj;\n try {\n obj = JSON.parse(s);\n } catch (e) {\n return null;\n }\n if (isNonArrayObject(obj)) {\n return obj;\n } else {\n return null;\n }\n}\n// CONCATENATED MODULE: ./src/storage/implementation/location.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Functionality related to the parsing/composition of bucket/\r\n * object location.\r\n */\n\n/**\r\n * @struct\r\n */\nvar location_Location = /** @class */function () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n Object.defineProperty(Location.prototype, \"path\", {\n get: function get() {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n } catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n } else {\n throw invalidDefaultBucket(bucketString);\n }\n };\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = { bucket: 1, path: 3 };\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' + version + '/b/' + bucketDomain + '/o' + path, 'i');\n var httpIndices = { bucket: 1, path: 3 };\n var groups = [{ regex: gsRegex, indices: gsIndices, postModify: gsModify }, { regex: httpRegex, indices: httpIndices, postModify: httpModify }];\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw invalidUrl(url);\n }\n return location;\n };\n return Location;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/path.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Contains helper methods for manipulating paths.\r\n */\n/**\r\n * @return Null if the path is already at the root.\r\n */\nfunction path_parent(path) {\n if (path.length == 0) {\n return null;\n }\n var index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n var newPath = path.slice(0, index);\n return newPath;\n}\nfunction child(path, childPath) {\n var canonicalChildPath = childPath.split('/').filter(function (component) {\n return component.length > 0;\n }).join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n } else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\r\n * Returns the last component of a path.\r\n * '/foo/bar' -> 'bar'\r\n * '/foo/bar/baz/' -> 'baz/'\r\n * '/a' -> 'a'\r\n */\nfunction lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n } else {\n return path.slice(index + 1);\n }\n}\n// CONCATENATED MODULE: ./src/storage/implementation/url.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Functions to create and manipulate URLs for the server API.\r\n */\n\n\nfunction makeNormalUrl(urlPart) {\n return domainBase + apiBaseUrl + urlPart;\n}\nfunction makeDownloadUrl(urlPart) {\n return downloadBase + apiBaseUrl + urlPart;\n}\nfunction makeUploadUrl(urlPart) {\n return domainBase + apiUploadBaseUrl + urlPart;\n}\nfunction makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n// CONCATENATED MODULE: ./src/storage/implementation/metadata.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\nfunction noXform_(metadata, value) {\n return value;\n}\n/**\r\n * @struct\r\n */\nvar Mapping = /** @class */function () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n return Mapping;\n}();\n\nvar mappings_ = null;\nfunction xformPath(fullPath) {\n var valid = isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n } else {\n fullPath = fullPath;\n return lastComponent(fullPath);\n }\n}\nfunction getMappings() {\n if (mappings_) {\n return mappings_;\n }\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\r\n * Coerces the second param to a number, if it is defined.\r\n */\n function xformSize(metadata, size) {\n if (isDef(size)) {\n return +size;\n } else {\n return size;\n }\n }\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n /**\r\n * Transforms a comma-separated string of tokens into a list of download\r\n * URLs.\r\n */\n function xformTokens(metadata, tokens) {\n var valid = isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = makeDownloadUrl(urlPart);\n var queryString = makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(new Mapping('downloadTokens', 'downloadURLs', false, xformTokens));\n mappings_ = mappings;\n return mappings_;\n}\nfunction addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new location_Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\nfunction fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\nfunction fromResourceString(authWrapper, resourceString, mappings) {\n var obj = jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\nfunction toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\nfunction metadataValidator(p) {\n var validType = p && isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (var key in p) {\n var val = p[key];\n if (key === 'customMetadata') {\n if (!isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n } else {\n if (isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n// CONCATENATED MODULE: ./src/storage/implementation/args.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n/**\r\n * @param name Name of the function.\r\n * @param specs Argument specs.\r\n * @param passed The actual arguments passed to the function.\r\n * @throws {fbs.Error} If the arguments are invalid.\r\n */\nfunction validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n } catch (e) {\n if (e instanceof Error) {\n throw invalidArgument(i, name, e.message);\n } else {\n throw invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\r\n * @struct\r\n */\nvar args_ArgSpec = /** @class */function () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n this.validator = function (p) {\n if (self.optional && !isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n return ArgSpec;\n}();\n\nfunction and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\nfunction stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!isString(p)) {\n throw 'Expected string.';\n }\n }\n var validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n } else {\n validator = stringValidator;\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array || p instanceof ArrayBuffer || isNativeBlobDefined() && p instanceof Blob;\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction metadataSpec(opt_optional) {\n return new args_ArgSpec(metadataValidator, opt_optional);\n}\nfunction nonNegativeNumberSpec() {\n function validator(p) {\n var valid = isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new args_ArgSpec(validator);\n}\nfunction looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || isDef(p) && p instanceof Object;\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\nfunction nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new args_ArgSpec(validator, opt_optional);\n}\n// CONCATENATED MODULE: ./src/storage/implementation/fs.ts\n\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n } else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n } else {\n return undefined;\n }\n}\n/**\r\n * Concatenates one or more values together and converts them to a Blob.\r\n *\r\n * @param var_args The values that will make up the resulting blob.\r\n * @return The blob.\r\n */\nfunction getBlob() {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n var BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n } else {\n if (isNativeBlobDefined()) {\n return new Blob(var_args);\n } else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\r\n * Slices the blob. The returned blob contains data from the start byte\r\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\r\n *\r\n * @param blob The blob to be sliced.\r\n * @param start Index of the starting byte.\r\n * @param end Index of the ending byte.\r\n * @return The blob slice or null if not supported.\r\n */\nfunction sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n } else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n } else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n// CONCATENATED MODULE: ./src/storage/implementation/blob.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @file Provides a Blob-like wrapper for various binary types (including the\r\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\r\n * making uploads possible in environments without the native Blob type.\r\n */\n\n\n\n\n/**\r\n * @param opt_elideCopy If true, doesn't copy mutable input data\r\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\r\n * modified after this blob's construction.\r\n */\nvar blob_FbsBlob = /** @class */function () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n if (isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n } else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n } else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n } else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n } else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n } else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n FbsBlob.getBlob = function () {\n var var_args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n if (isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n } else {\n return val;\n }\n });\n return new FbsBlob(getBlob.apply(null, blobby));\n } else {\n var uint8Arrays = var_args.map(function (val) {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val).data;\n } else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n return FbsBlob;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/array.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * Returns true if the object is contained in the array (compared with ===).\r\n * @template T\r\n */\nfunction array_contains(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\r\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\r\n * @template T\r\n */\nfunction array_clone(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\r\n * Removes the given element from the given array, if it is contained.\r\n * Directly modifies the passed-in array.\r\n * @template T\r\n */\nfunction remove(array, elem) {\n var i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n// CONCATENATED MODULE: ./src/storage/implementation/requestinfo.ts\nvar RequestInfo = /** @class */function () {\n function RequestInfo(url, method,\n /**\r\n * Returns the value with which to resolve the request's promise. Only called\r\n * if the request is successful. Throw from this function to reject the\r\n * returned Request's promise with the thrown error.\r\n * Note: The XhrIo passed to this function may be reused after this callback\r\n * returns. Do not keep a reference to it in any way.\r\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\r\n * Called with the current number of bytes uploaded and total size (-1 if not\r\n * computable) of the request body (i.e. used to report upload progress).\r\n */\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n return RequestInfo;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/requests.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n\n\n\n/**\r\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\r\n */\nfunction handlerCheck(cndn) {\n if (!cndn) {\n throw unknown();\n }\n}\nfunction metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n return handler;\n}\nfunction sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n if (xhr.getStatus() === 401) {\n newErr = unauthenticated();\n } else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n } else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n } else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\nfunction getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = toResourceString(metadata, mappings);\n var headers = { 'Content-Type': 'application/json; charset=utf-8' };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n function handler(xhr, text) {}\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\nfunction determineContentType_(metadata, blob) {\n return metadata && metadata['contentType'] || blob && blob.type() || 'application/octet-stream';\n}\nfunction metadataForUpload_(location, blob, opt_metadata) {\n var metadata = clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\nfunction multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n function genBoundary() {\n var str = '';\n for (var i = 0; i < 2; i++) {\n str = str + Math.random().toString().slice(2);\n }\n return str;\n }\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = toResourceString(metadata, mappings);\n var preBlobPart = '--' + boundary + '\\r\\n' + 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' + metadataString + '\\r\\n--' + boundary + '\\r\\n' + 'Content-Type: ' + metadata['contentType'] + '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = blob_FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\r\n * @param current The number of bytes that have been uploaded so far.\r\n * @param total The total number of bytes in the upload.\r\n * @param opt_finalized True if the server has finished the upload.\r\n * @param opt_metadata The upload metadata, should\r\n * only be passed if opt_finalized is true.\r\n * @struct\r\n */\nvar ResumableUploadStatus = /** @class */function () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n return ResumableUploadStatus;\n}();\n\nfunction checkResumeHeader_(xhr, opt_allowed) {\n var status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n } catch (e) {\n handlerCheck(false);\n }\n var allowed = opt_allowed || ['active'];\n handlerCheck(array_contains(allowed, status));\n return status;\n}\nfunction createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = { name: metadata['fullPath'] };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n } catch (e) {\n handlerCheck(false);\n }\n handlerCheck(isString(url));\n return url;\n }\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n */\nfunction getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = { 'X-Goog-Upload-Command': 'query' };\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n } catch (e) {\n handlerCheck(false);\n }\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\r\n * Any uploads via the resumable upload API must transfer a number of bytes\r\n * that is a multiple of this number.\r\n */\nvar resumableUploadChunkSize = 256 * 1024;\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n * @param chunkSize Number of bytes to upload.\r\n * @param opt_status The previous status.\r\n * If not passed or null, we start from the beginning.\r\n * @throws fbs.Error If the upload is already complete, the passed in status\r\n * has a final size inconsistent with the blob, or the blob cannot be sliced\r\n * for upload.\r\n */\nfunction continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n } else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw serverFileWrongSize();\n }\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n if (body === null) {\n throw cannotSliceBlob();\n }\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n } else {\n metadata = null;\n }\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n// CONCATENATED MODULE: ./src/storage/implementation/observer.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @struct\r\n */\nvar observer_Observer = /** @class */function () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = isFunction(nextOrObserver) || isDef(opt_error) || isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n } else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n return Observer;\n}();\n\n// CONCATENATED MODULE: ./src/storage/tasksnapshot.ts\nvar UploadTaskSnapshot = /** @class */function () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n Object.defineProperty(UploadTaskSnapshot.prototype, \"downloadURL\", {\n get: function get() {\n if (this.metadata !== null) {\n var urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n } else {\n return null;\n }\n } else {\n return null;\n }\n },\n enumerable: true,\n configurable: true\n });\n return UploadTaskSnapshot;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/async.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Method for invoking a callback asynchronously.\r\n */\n\n/**\r\n * Returns a function that invokes f with its arguments asynchronously as a\r\n * microtask, i.e. as soon as possible after the current script returns back\r\n * into browser code.\r\n */\nfunction async_async(f) {\n return function () {\n var argsToForward = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n promise_external_resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n// CONCATENATED MODULE: ./src/storage/task.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Defines types for interacting with blob transfer tasks.\r\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\r\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\r\n * upload and manage callbacks for various events.\r\n */\nvar task_UploadTask = /** @class */function () {\n /**\r\n * @param ref The firebaseStorage.Reference object this task came\r\n * from, untyped to avoid cyclic dependencies.\r\n * @param blob The blob to upload.\r\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) {\n metadata = null;\n }\n var _this = this;\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n if (error.codeEquals(Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n _this.completeTransitions_();\n } else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n if (error.codeEquals(Code.CANCELED)) {\n _this.completeTransitions_();\n } else {\n _this.error_ = error;\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = make(function (resolve, reject) {\n _this.resolve_ = resolve;\n _this.reject_ = reject;\n _this.start_();\n });\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, function () {});\n }\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n } else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n } else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n } else {\n this.continueUpload_();\n }\n }\n }\n } else {\n this.oneShotUpload_();\n }\n };\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n };\n // TODO(andysoto): assert false\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this;\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n _this.updateProgress_(status.current);\n _this.needToFetchStatus_ = false;\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new ResumableUploadStatus(this.transferred_, this.blob_.size());\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n try {\n requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n } catch (e) {\n _this.error_ = e;\n _this.transition_(InternalTaskState.ERROR);\n return;\n }\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = uploadRequest;\n uploadRequest.getPromise().then(function (newStatus) {\n _this.increaseMultiplier_();\n _this.request_ = null;\n _this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n } else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = resumableUploadChunkSize * this.chunkMultiplier_;\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n this.resolveToken_(function (authToken) {\n var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n _this.updateProgress_(_this.blob_.size());\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred;\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = error_canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function get() {\n var externalState = taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Adds a callback for an event.\r\n * @param type The type of event to listen for.\r\n */\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) {\n nextOrObserver = undefined;\n }\n if (error === void 0) {\n error = undefined;\n }\n if (completed === void 0) {\n completed = undefined;\n }\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' + '`next`, `error`, `complete` properties.';\n var nextValidator = nullFunctionSpec(true).validator;\n var observerValidator = looseObjectSpec(null, true).validator;\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n } catch (e) {}\n try {\n observerValidator(p);\n var anyDefined = isJustDef(p['next']) || isJustDef(p['error']) || isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n } catch (e) {\n throw nextOrObserverMessage;\n }\n }\n var specs = [stringSpec(typeValidator), looseObjectSpec(nextOrObserverValidator, true), nullFunctionSpec(true), nullFunctionSpec(true)];\n validate('on', specs, arguments);\n var self = this;\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n validate('on', specs, arguments);\n }\n var observer = new observer_Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n var binderSpecs = [looseObjectSpec(binderNextOrObserverValidator), nullFunctionSpec(true), nullFunctionSpec(true)];\n var typeOnly = !(isJustDef(nextOrObserver) || isJustDef(error) || isJustDef(completed));\n if (typeOnly) {\n return makeBinder(binderSpecs);\n } else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\r\n * This object behaves like a Promise, and resolves with its snapshot data\r\n * when the upload completes.\r\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\r\n * @param onRejected The rejection callback.\r\n */\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\r\n * Equivalent to calling `then(null, onRejected)`.\r\n */\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\r\n * Adds the given observer.\r\n */\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\r\n * Removes the given observer.\r\n */\n UploadTask.prototype.removeObserver_ = function (observer) {\n remove(this.observers_, observer);\n };\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n this.finishPromise_();\n var observers = array_clone(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n switch (taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n async_async(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n async_async(toCall.bind(null, this.error_))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n async_async(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n async_async(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n async_async(observer.error.bind(observer, this.error_))();\n }\n }\n };\n /**\r\n * Resumes a paused task. Has no effect on a currently running or failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\n UploadTask.prototype.resume = function () {\n validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED || this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n };\n /**\r\n * Pauses a currently running task. Has no effect on a paused or failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\n UploadTask.prototype.pause = function () {\n validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n };\n /**\r\n * Cancels a currently running or paused task. Has no effect on a complete or\r\n * failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\n UploadTask.prototype.cancel = function () {\n validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING || this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n };\n return UploadTask;\n}();\n\n// CONCATENATED MODULE: ./src/storage/reference.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Defines the Firebase Storage Reference class.\r\n */\n\n\n\n\n\n\n\n\n\n\n\n\n/**\r\n * Provides methods to interact with a bucket in the Firebase Storage service.\r\n * @param location An fbs.location, or the URL at\r\n * which to base this object, in one of the following forms:\r\n * gs:///\r\n * http[s]://firebasestorage.googleapis.com/\r\n * /b//o/\r\n * Any query or fragment strings will be ignored in the http[s]\r\n * format. If no value is passed, the storage object will use a URL based on\r\n * the project ID of the base firebase.App instance.\r\n */\nvar reference_Reference = /** @class */function () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n if (location instanceof location_Location) {\n this.location = location;\n } else {\n this.location = location_Location.makeFromUrl(location);\n }\n }\n /**\r\n * @return The URL for the bucket and path this object references,\r\n * in the form gs:///\r\n * @override\r\n */\n Reference.prototype.toString = function () {\n validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n Reference.prototype.mappings = function () {\n return getMappings();\n };\n /**\r\n * @return A reference to the object obtained by\r\n * appending childPath, removing any duplicate, beginning, or trailing\r\n * slashes.\r\n */\n Reference.prototype.child = function (childPath) {\n validate('child', [stringSpec()], arguments);\n var newPath = child(this.location.path, childPath);\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\r\n * @return A reference to the parent of the\r\n * current object, or null if the current object is the root.\r\n */\n get: function get() {\n var newPath = path_parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n var location = new location_Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\r\n * @return An reference to the root of this\r\n * object's bucket.\r\n */\n get: function get() {\n var location = new location_Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function get() {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function get() {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function get() {\n return lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function get() {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Uploads a blob to this object's location.\r\n * @param data The blob to upload.\r\n * @return An UploadTask that lets you control and\r\n * observe the upload.\r\n */\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) {\n metadata = null;\n }\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data), metadata);\n };\n /**\r\n * Uploads a string to this object's location.\r\n * @param string The string to upload.\r\n * @param opt_format The format of the string to upload.\r\n * @return An UploadTask that lets you control and\r\n * observe the upload.\r\n */\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) {\n format = StringFormat.RAW;\n }\n validate('putString', [stringSpec(), stringSpec(formatValidator, true), metadataSpec(true)], arguments);\n this.throwIfRoot_('putString');\n var data = dataFromString(format, string);\n var metadata = clone(opt_metadata);\n if (!isDef(metadata['contentType']) && isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new task_UploadTask(this, this.authWrapper, this.location, this.mappings(), new blob_FbsBlob(data.data, true), metadata);\n };\n /**\r\n * Deletes the object at this location.\r\n * @return A promise that resolves if the deletion succeeds.\r\n */\n Reference.prototype.delete = function () {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\r\n * A promise that resolves with the metadata for this object. If this\r\n * object doesn't exist or metadata cannot be retreived, the promise is\r\n * rejected.\r\n */\n Reference.prototype.getMetadata = function () {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\r\n * Updates the metadata for this object.\r\n * @param metadata The new metadata for the object.\r\n * Only values that have been explicitly set will be changed. Explicitly\r\n * setting a value to null will remove the metadata.\r\n * @return A promise that resolves\r\n * with the new metadata for this object.\r\n * @see firebaseStorage.Reference.prototype.getMetadata\r\n */\n Reference.prototype.updateMetadata = function (metadata) {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\r\n * @return A promise that resolves with the download\r\n * URL for this object.\r\n */\n Reference.prototype.getDownloadURL = function () {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function (metadata) {\n var url = metadata['downloadURLs'][0];\n if (isDef(url)) {\n return url;\n } else {\n throw noDownloadURL();\n }\n });\n };\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw invalidRootOperation(name);\n }\n };\n return Reference;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/failrequest.ts\n\n/**\r\n * A request whose promise always fails.\r\n * @struct\r\n * @template T\r\n */\nvar failrequest_FailRequest = /** @class */function () {\n function FailRequest(error) {\n this.promise_ = promise_external_reject(error);\n }\n /** @inheritDoc */\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) {\n appDelete = false;\n }\n };\n return FailRequest;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/requestmap.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n/**\r\n * @struct\r\n */\nvar requestmap_RequestMap = /** @class */function () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = minSafeInteger;\n }\n /**\r\n * Registers the given request with this map.\r\n * The request is unregistered when it completes.\r\n * @param r The request to register.\r\n */\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n };\n /**\r\n * Cancels all registered requests.\r\n */\n RequestMap.prototype.clear = function () {\n forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n return RequestMap;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/authwrapper.ts\n\n\n\n\n\n\n\n/**\r\n * @param app If null, getAuthToken always resolves with null.\r\n * @param service The storage service associated with this auth wrapper.\r\n * Untyped to avoid circular type dependencies.\r\n * @struct\r\n */\nvar authwrapper_AuthWrapper = /** @class */function () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n if (this.app_ !== null) {\n var options = this.app_.options;\n if (isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = defaultMaxUploadRetryTime;\n this.requestMap_ = new requestmap_RequestMap();\n }\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[configOption] || null;\n if (bucketString == null) {\n return null;\n }\n var loc = location_Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null && isDef(this.app_.INTERNAL) && isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n } else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n } else {\n return promise_external_resolve(null);\n }\n };\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw appDeleted();\n } else {\n return this.bucket_;\n }\n };\n /**\r\n * The service associated with this auth wrapper. Untyped to avoid circular\r\n * type dependencies.\r\n */\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\r\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\r\n * at the given Location.\r\n * @param loc The Location.\r\n * @return Actually a firebaseStorage.Reference, typing not allowed\r\n * because of circular dependency problems.\r\n */\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n } else {\n return new failrequest_FailRequest(appDeleted());\n }\n };\n /**\r\n * Stop running requests and prevent more from being created.\r\n */\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n return AuthWrapper;\n}();\n\n// CONCATENATED MODULE: ./src/storage/implementation/backoff.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @param f May be invoked\r\n * before the function returns.\r\n * @param callback Get all the arguments passed to the function\r\n * passed to f, including the initial boolean.\r\n */\nfunction start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n function canceled() {\n return cancelState === 2;\n }\n var triggeredCallback = false;\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n function handler(success) {\n var var_args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n var mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n var waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n } else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n var stopped = false;\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n } else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\r\n * Stops the retry loop from repeating.\r\n * If the function is currently \"in between\" retries, it is invoked immediately\r\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\r\n * after the current invocation finishes iff the current invocation would have\r\n * triggered another retry.\r\n */\nfunction stop(id) {\n id(false);\n}\n// EXTERNAL MODULE: ./src/app.ts + 1 modules\nvar src_app = __webpack_require__(9);\n\n// CONCATENATED MODULE: ./src/storage/implementation/request.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n/**\r\n * @fileoverview Defines methods used to actually send HTTP requests from\r\n * abstract representations.\r\n */\n\n\n\n\n\n\n\n\n\n/**\r\n * @struct\r\n * @template T\r\n */\nvar request_NetworkRequest = /** @class */function () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = make(function (resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n /**\r\n * Actually starts the retry loop.\r\n */\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n function doTheRequest(backoffCallback, canceled) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr.send(self.url_, self.method_, self.body_, self.headers_).then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n var successCode = array_contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\r\n * @param requestWentThrough True if the request eventually went\r\n * through, false if it hit the retry limit or was canceled.\r\n */\n function backoffDone(requestWentThrough, status) {\n var resolve = self.resolve_;\n var reject = self.reject_;\n var xhr = status.xhr;\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n if (isJustDef(result)) {\n resolve(result);\n } else {\n resolve();\n }\n } catch (e) {\n reject(e);\n }\n } else {\n if (xhr !== null) {\n var err = unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n } else {\n reject(err);\n }\n } else {\n if (status.canceled) {\n var err = self.appDelete_ ? appDeleted() : error_canceled();\n reject(err);\n } else {\n var err = retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n } else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429];\n var isExtraRetryCode = array_contains(extraRetryCodes, status);\n var isRequestSpecificRetryCode = array_contains(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n return NetworkRequest;\n}();\n/**\r\n * A collection of information about the result of a network request.\r\n * @param opt_canceled Defaults to false.\r\n * @struct\r\n */\nvar RequestEndStatus = /** @class */function () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n return RequestEndStatus;\n}();\n\nfunction addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\nfunction addVersionHeader_(headers) {\n var number = typeof src_app[\"default\"] !== 'undefined' ? src_app[\"default\"].SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\r\n * @template T\r\n */\nfunction makeRequest(requestInfo, authToken, pool) {\n var queryPart = makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new request_NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n// CONCATENATED MODULE: ./src/storage/service.ts\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n\n/**\r\n * A service that provides firebaseStorage.Reference instances.\r\n * @param opt_url gs:// url to a custom Storage Bucket\r\n *\r\n * @struct\r\n */\nvar service_Service = /** @class */function () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n function maker(authWrapper, loc) {\n return new reference_Reference(authWrapper, loc);\n }\n this.authWrapper_ = new authwrapper_AuthWrapper(app, maker, makeRequest, this, pool);\n this.app_ = app;\n if (url != null) {\n this.bucket_ = location_Location.makeFromBucketSpec(url);\n } else {\n var authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new location_Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new service_ServiceInternals(this);\n }\n /**\r\n * Returns a firebaseStorage.Reference for the given path in the default\r\n * bucket.\r\n */\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n validate('ref', [stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n var ref = new reference_Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n } else {\n return ref;\n }\n };\n /**\r\n * Returns a firebaseStorage.Reference object for the given absolute URL,\r\n * which must be a gs:// or http[s]:// URL.\r\n */\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n location_Location.makeFromUrl(p);\n } catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n validate('refFromURL', [stringSpec(validator, false)], arguments);\n return new reference_Reference(this.authWrapper_, url);\n };\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function get() {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxUploadRetryTime = function (time) {\n validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function get() {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n Service.prototype.setMaxOperationRetryTime = function (time) {\n validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n Object.defineProperty(Service.prototype, \"app\", {\n get: function get() {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function get() {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}();\n\n/**\r\n * @struct\r\n */\nvar service_ServiceInternals = /** @class */function () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\r\n * Called when the associated app is deleted.\r\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\r\n */\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return promise_external_resolve(undefined);\n };\n return ServiceInternals;\n}();\n\n// CONCATENATED MODULE: ./src/storage.ts\n/* harmony export (immutable) */ __webpack_exports__[\"registerStorage\"] = registerStorage;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\n\n\n\n\n\n/**\r\n * Type constant for Firebase Storage.\r\n */\nvar STORAGE_TYPE = 'storage';\nfunction factory(app, unused, opt_url) {\n return new service_Service(app, new xhriopool_XhrIoPool(), opt_url);\n}\nfunction registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: service_Service,\n Reference: reference_Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined,\n // Allow multiple storage instances per app.\n true);\n}\nregisterStorage(src_app[\"default\"]);\n\n/***/ })\n\n},[60]);\n } catch(error) {\n throw new Error(\n 'Cannot instantiate firebase-storage.js - ' +\n 'be sure to load firebase-app.js first.'\n )\n }\n\n\n// WEBPACK FOOTER //\n// firebase-storage.js","/**\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 */\nimport { configOption } from './constants';\n\nexport class FirebaseStorageError implements Error {\n private code_: string;\n private message_: string;\n private serverResponse_: string | null;\n private name_: string;\n\n constructor(code: Code, message: string) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n\n codeProp(): string {\n return this.code;\n }\n\n codeEquals(code: Code): boolean {\n return prependCode(code) === this.codeProp();\n }\n\n serverResponseProp(): string | null {\n return this.serverResponse_;\n }\n\n setServerResponseProp(serverResponse: string | null) {\n this.serverResponse_ = serverResponse;\n }\n\n get name(): string {\n return this.name_;\n }\n\n get code(): string {\n return this.code_;\n }\n\n get message(): string {\n return this.message_;\n }\n\n get serverResponse(): null | string {\n return this.serverResponse_;\n }\n}\n\nexport const errors = {};\n\n/**\n * @enum {string}\n */\nexport type Code = string;\nexport const Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\n\nexport function prependCode(code: Code): string {\n return 'storage/' + code;\n}\n\nexport function unknown(): FirebaseStorageError {\n let message =\n 'An unknown error occurred, please check the error payload for ' +\n 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\n\nexport function objectNotFound(path: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.OBJECT_NOT_FOUND,\n \"Object '\" + path + \"' does not exist.\"\n );\n}\n\nexport function bucketNotFound(bucket: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.BUCKET_NOT_FOUND,\n \"Bucket '\" + bucket + \"' does not exist.\"\n );\n}\n\nexport function projectNotFound(project: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.PROJECT_NOT_FOUND,\n \"Project '\" + project + \"' does not exist.\"\n );\n}\n\nexport function quotaExceeded(bucket: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.QUOTA_EXCEEDED,\n \"Quota for bucket '\" +\n bucket +\n \"' exceeded, please view quota on \" +\n 'https://firebase.google.com/pricing/.'\n );\n}\n\nexport function unauthenticated(): FirebaseStorageError {\n let message =\n 'User is not authenticated, please authenticate using Firebase ' +\n 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\n\nexport function unauthorized(path: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.UNAUTHORIZED,\n \"User does not have permission to access '\" + path + \"'.\"\n );\n}\n\nexport function retryLimitExceeded(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.RETRY_LIMIT_EXCEEDED,\n 'Max retry time for operation exceeded, please try again.'\n );\n}\n\nexport function invalidChecksum(\n path: string,\n checksum: string,\n calculated: string\n): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_CHECKSUM,\n \"Uploaded/downloaded object '\" +\n path +\n \"' has checksum '\" +\n checksum +\n \"' which does not match '\" +\n calculated +\n \"'. Please retry the upload/download.\"\n );\n}\n\nexport function canceled(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.CANCELED,\n 'User canceled the upload/download.'\n );\n}\n\nexport function invalidEventName(name: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_EVENT_NAME,\n \"Invalid event name '\" + name + \"'.\"\n );\n}\n\nexport function invalidUrl(url: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_URL,\n \"Invalid URL '\" + url + \"'.\"\n );\n}\n\nexport function invalidDefaultBucket(bucket: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_DEFAULT_BUCKET,\n \"Invalid default bucket '\" + bucket + \"'.\"\n );\n}\n\nexport function noDefaultBucket(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.NO_DEFAULT_BUCKET,\n 'No default bucket ' +\n \"found. Did you set the '\" +\n configOption +\n \"' property when initializing the app?\"\n );\n}\n\nexport function cannotSliceBlob(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.CANNOT_SLICE_BLOB,\n 'Cannot slice blob for upload. Please retry the upload.'\n );\n}\n\nexport function serverFileWrongSize(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.SERVER_FILE_WRONG_SIZE,\n 'Server recorded incorrect upload file size, please retry the upload.'\n );\n}\n\nexport function noDownloadURL(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.NO_DOWNLOAD_URL,\n 'The given file does not have any download URLs.'\n );\n}\n\nexport function invalidArgument(\n index: number,\n fnName: string,\n message: string\n): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_ARGUMENT,\n 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message\n );\n}\n\nexport function invalidArgumentCount(\n argMin: number,\n argMax: number,\n fnName: string,\n real: number\n): FirebaseStorageError {\n let countPart;\n let plural;\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n } else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n return new FirebaseStorageError(\n Code.INVALID_ARGUMENT_COUNT,\n 'Invalid argument count in `' +\n fnName +\n '`: Expected ' +\n countPart +\n ' ' +\n plural +\n ', received ' +\n real +\n '.'\n );\n}\n\nexport function appDeleted(): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.APP_DELETED,\n 'The Firebase app was deleted.'\n );\n}\n\n/**\n * @param name The name of the operation that was invalid.\n */\nexport function invalidRootOperation(name: string): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_ROOT_OPERATION,\n \"The operation '\" +\n name +\n \"' cannot be performed on a root reference, create a non-root \" +\n \"reference using child, such as .child('file.png').\"\n );\n}\n\n/**\n * @param format The format that was not valid.\n * @param message A message describing the format violation.\n */\nexport function invalidFormat(\n format: string,\n message: string\n): FirebaseStorageError {\n return new FirebaseStorageError(\n Code.INVALID_FORMAT,\n \"String does not match format '\" + format + \"': \" + message\n );\n}\n\n/**\n * @param message A message describing the internal error.\n */\nexport function internalError(message: string): FirebaseStorageError {\n throw new FirebaseStorageError(\n Code.INTERNAL_ERROR,\n 'Internal error: ' + message\n );\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/error.ts","/**\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 */\nimport * as errorsExports from './error';\nimport { errors } from './error';\n\n/**\n * @enum {string}\n */\nexport type StringFormat = string;\nexport const StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\n\nexport function formatValidator(stringFormat: string) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n default:\n throw 'Expected one of the event types: [' +\n StringFormat.RAW +\n ', ' +\n StringFormat.BASE64 +\n ', ' +\n StringFormat.BASE64URL +\n ', ' +\n StringFormat.DATA_URL +\n '].';\n }\n}\n\n/**\n * @struct\n */\nexport class StringData {\n contentType: string | null;\n\n constructor(public data: Uint8Array, opt_contentType?: string | null) {\n this.contentType = opt_contentType || null;\n }\n}\n\nexport function dataFromString(\n format: StringFormat,\n string: string\n): StringData {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n }\n\n // assert(false);\n throw errorsExports.unknown();\n}\n\nexport function utf8Bytes_(string: string): Uint8Array {\n let b = [];\n for (let i = 0; i < string.length; i++) {\n let c = string.charCodeAt(i);\n if (c <= 127) {\n b.push(c);\n } else {\n if (c <= 2047) {\n b.push(192 | (c >> 6), 128 | (c & 63));\n } else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n let valid =\n i < string.length - 1 &&\n (string.charCodeAt(i + 1) & 64512) == 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n } else {\n let hi = c;\n let lo = string.charCodeAt(++i);\n c = 65536 | ((hi & 1023) << 10) | (lo & 1023);\n b.push(\n 240 | (c >> 18),\n 128 | ((c >> 12) & 63),\n 128 | ((c >> 6) & 63),\n 128 | (c & 63)\n );\n }\n } else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n } else {\n b.push(224 | (c >> 12), 128 | ((c >> 6) & 63), 128 | (c & 63));\n }\n }\n }\n }\n }\n return new Uint8Array(b);\n}\n\nexport function percentEncodedBytes_(string: string): Uint8Array {\n let decoded;\n try {\n decoded = decodeURIComponent(string);\n } catch (e) {\n throw errorsExports.invalidFormat(\n StringFormat.DATA_URL,\n 'Malformed data URL.'\n );\n }\n return utf8Bytes_(decoded);\n}\n\nexport function base64Bytes_(format: StringFormat, string: string): Uint8Array {\n switch (format) {\n case StringFormat.BASE64: {\n let hasMinus = string.indexOf('-') !== -1;\n let hasUnder = string.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n let invalidChar = hasMinus ? '-' : '_';\n throw errorsExports.invalidFormat(\n format,\n \"Invalid character '\" +\n invalidChar +\n \"' found: is it base64url encoded?\"\n );\n }\n break;\n }\n case StringFormat.BASE64URL: {\n let hasPlus = string.indexOf('+') !== -1;\n let hasSlash = string.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n let invalidChar = hasPlus ? '+' : '/';\n throw errorsExports.invalidFormat(\n format,\n \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\"\n );\n }\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n let bytes;\n try {\n bytes = atob(string);\n } catch (e) {\n throw errorsExports.invalidFormat(format, 'Invalid character found');\n }\n let array = new Uint8Array(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n return array;\n}\n\n/**\n * @struct\n */\nclass DataURLParts {\n base64: boolean = false;\n contentType: string | null = null;\n rest: string;\n\n constructor(dataURL: string) {\n let matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw errorsExports.invalidFormat(\n StringFormat.DATA_URL,\n \"Must be formatted 'data:[][;base64],\"\n );\n }\n let middle = matches[1] || null;\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64\n ? middle.substring(0, middle.length - ';base64'.length)\n : middle;\n }\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n}\n\nexport function dataURLBytes_(string: string): Uint8Array {\n let parts = new DataURLParts(string);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n } else {\n return percentEncodedBytes_(parts.rest);\n }\n}\n\nexport function dataURLContentType_(string: string): string | null {\n let parts = new DataURLParts(string);\n return parts.contentType;\n}\n\nfunction endsWith(s: string, end: string): boolean {\n const longEnough = s.length >= end.length;\n if (!longEnough) {\n return false;\n }\n\n return s.substring(s.length - end.length) === end;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/string.ts","/**\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\n/**\n * @fileoverview Enumerations used for upload tasks.\n */\n\n/**\n * Enum for task events.\n * @enum {string}\n */\nexport type TaskEvent = string;\nexport const TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\n\n/**\n * Internal enum for task state.\n * @enum {string}\n */\nexport type InternalTaskState = string;\nexport const InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\n\n/**\n * External (API-surfaced) enum for task state.\n * @enum {string}\n */\nexport type TaskState = string;\nexport const TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n /** The task was paused by the user. */\n PAUSED: 'paused',\n /** The task completed successfully. */\n SUCCESS: 'success',\n /** The task was canceled. */\n CANCELED: 'canceled',\n /** The task failed with an error. */\n ERROR: 'error'\n};\n\nexport function taskStateFromInternalTaskState(\n state: InternalTaskState\n): TaskState {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/taskenums.ts","/**\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\n/**\n * @fileoverview Contains methods for working with objects.\n */\nexport function contains(obj: Object, prop: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nexport function forEach(\n obj: { [key: string]: T },\n f: (p1: string, p2: T) => void\n) {\n for (let key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\n\nexport function clone(obj?: { [key: string]: any } | null): T {\n if (obj == null) {\n return {} as T;\n }\n\n let c: { [name: string]: any } = {};\n forEach(obj, function(key, val) {\n c[key] = val;\n });\n return c as T;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/object.ts","/**\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\n/**\n * @fileoverview Implements the promise abstraction interface for external\n * (public SDK) packaging, which just passes through to the firebase-app impl.\n */\n\n/**\n * @template T\n * @param {function((function(T): void),\n * (function(!Error): void))} resolver\n */\n\nimport { PromiseImpl } from '../../utils/promise';\n\nexport function make(\n resolver: (p1: (p1: T) => void, p2: (p1: Error) => void) => void\n): Promise {\n return new PromiseImpl(resolver);\n}\n\n/**\n * @template T\n */\nexport function resolve(value: T): Promise {\n return PromiseImpl.resolve(value) as Promise;\n}\n\nexport function reject(error: Error): Promise {\n return PromiseImpl.reject(error) as Promise;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/promise_external.ts","/**\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\n/**\n * @return False if the object is undefined or null, true otherwise.\n */\nexport function isDef(p: any): boolean {\n return p != null;\n}\n\nexport function isJustDef(p: any): boolean {\n return p !== void 0;\n}\n\nexport function isFunction(p: any): boolean {\n return typeof p === 'function';\n}\n\nexport function isObject(p: any): boolean {\n return typeof p === 'object';\n}\n\nexport function isNonNullObject(p: any): boolean {\n return isObject(p) && p !== null;\n}\n\nexport function isNonArrayObject(p: any): boolean {\n return isObject(p) && !Array.isArray(p);\n}\n\nexport function isString(p: any): boolean {\n return typeof p === 'string' || p instanceof String;\n}\n\nexport function isNumber(p: any): boolean {\n return typeof p === 'number' || p instanceof Number;\n}\n\nexport function isNativeBlob(p: any): boolean {\n return isNativeBlobDefined() && p instanceof Blob;\n}\n\nexport function isNativeBlobDefined(): boolean {\n return typeof Blob !== 'undefined';\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/type.ts","/**\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 */\nimport * as type from './type';\n\n/**\n * Returns the Object resulting from parsing the given JSON, or null if the\n * given string does not represent a JSON object.\n */\nexport function jsonObjectOrNull(s: string): { [name: string]: any } | null {\n let obj;\n try {\n obj = JSON.parse(s);\n } catch (e) {\n return null;\n }\n if (type.isNonArrayObject(obj)) {\n return obj;\n } else {\n return null;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/json.ts","/**\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\n/**\n * @fileoverview Contains helper methods for manipulating paths.\n */\n\n/**\n * @return Null if the path is already at the root.\n */\nexport function parent(path: string): string | null {\n if (path.length == 0) {\n return null;\n }\n let index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n let newPath = path.slice(0, index);\n return newPath;\n}\n\nexport function child(path: string, childPath: string): string {\n let canonicalChildPath = childPath\n .split('/')\n .filter(function(component) {\n return component.length > 0;\n })\n .join('/');\n if (path.length === 0) {\n return canonicalChildPath;\n } else {\n return path + '/' + canonicalChildPath;\n }\n}\n\n/**\n * Returns the last component of a path.\n * '/foo/bar' -> 'bar'\n * '/foo/bar/baz/' -> 'baz/'\n * '/a' -> 'a'\n */\nexport function lastComponent(path: string): string {\n let index = path.lastIndexOf('/', path.length - 2);\n if (index === -1) {\n return path;\n } else {\n return path.slice(index + 1);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/path.ts","/**\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\n/**\n * @fileoverview Functions to create and manipulate URLs for the server API.\n */\nimport * as constants from './constants';\nimport * as object from './object';\n\nexport function makeNormalUrl(urlPart: string): string {\n return constants.domainBase + constants.apiBaseUrl + urlPart;\n}\n\nexport function makeDownloadUrl(urlPart: string): string {\n return constants.downloadBase + constants.apiBaseUrl + urlPart;\n}\n\nexport function makeUploadUrl(urlPart: string): string {\n return constants.domainBase + constants.apiUploadBaseUrl + urlPart;\n}\n\nexport function makeQueryString(params: { [key: string]: string }): string {\n let encode = encodeURIComponent;\n let queryPart = '?';\n object.forEach(params, function(key, val) {\n let nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n });\n\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/url.ts","/**\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\n/**\n * @fileoverview Documentation for the metadata format\n */\nimport { Metadata } from '../metadata';\n\nimport { AuthWrapper } from './authwrapper';\nimport * as json from './json';\nimport { Location } from './location';\nimport * as path from './path';\nimport * as type from './type';\nimport * as UrlUtils from './url';\n\nexport function noXform_(metadata: Metadata, value: any): any {\n return value;\n}\n\n/**\n * @struct\n */\nexport class Mapping {\n local: string;\n writable: boolean;\n xform: (p1: Metadata, p2: any) => any;\n\n constructor(\n public server: string,\n opt_local?: string | null,\n opt_writable?: boolean,\n opt_xform?: (p1: Metadata, p2: any) => any | null\n ) {\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n}\ntype Mappings = Mapping[];\n\nexport { Mappings };\n\nlet mappings_: Mappings | null = null;\n\nexport function xformPath(fullPath: any): string {\n let valid = type.isString(fullPath);\n if (!valid || fullPath.length < 2) {\n return fullPath;\n } else {\n fullPath = fullPath as string;\n return path.lastComponent(fullPath);\n }\n}\n\nexport function getMappings(): Mappings {\n if (mappings_) {\n return mappings_;\n }\n let mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n\n function mappingsXformPath(metadata: Metadata, fullPath: any): string {\n return xformPath(fullPath);\n }\n let nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n\n /**\n * Coerces the second param to a number, if it is defined.\n */\n function xformSize(metadata: Metadata, size: any): number | null | undefined {\n if (type.isDef(size)) {\n return +(size as number);\n } else {\n return size;\n }\n }\n let sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n\n /**\n * Transforms a comma-separated string of tokens into a list of download\n * URLs.\n */\n function xformTokens(metadata: Metadata, tokens: any): string[] {\n let valid = type.isString(tokens) && tokens.length > 0;\n if (!valid) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return [];\n }\n let encode = encodeURIComponent;\n let tokensList = tokens.split(',');\n let urls = tokensList.map(function(token: string) {\n let bucket: string = metadata['bucket'] as string;\n let path: string = metadata['fullPath'] as string;\n let urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n let base = UrlUtils.makeDownloadUrl(urlPart);\n let queryString = UrlUtils.makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls;\n }\n mappings.push(\n new Mapping('downloadTokens', 'downloadURLs', false, xformTokens)\n );\n mappings_ = mappings;\n return mappings_;\n}\n\nexport function addRef(metadata: Metadata, authWrapper: AuthWrapper) {\n function generateRef() {\n let bucket: string = metadata['bucket'] as string;\n let path: string = metadata['fullPath'] as string;\n let loc = new Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n Object.defineProperty(metadata, 'ref', { get: generateRef });\n}\n\nexport function fromResource(\n authWrapper: AuthWrapper,\n resource: { [name: string]: any },\n mappings: Mappings\n): Metadata {\n let metadata: Metadata = {} as Metadata;\n metadata['type'] = 'file';\n let len = mappings.length;\n for (let i = 0; i < len; i++) {\n let mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n addRef(metadata, authWrapper);\n return metadata;\n}\n\nexport function fromResourceString(\n authWrapper: AuthWrapper,\n resourceString: string,\n mappings: Mappings\n): Metadata | null {\n let obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n let resource = obj as Metadata;\n return fromResource(authWrapper, resource, mappings);\n}\n\nexport function toResourceString(\n metadata: Metadata,\n mappings: Mappings\n): string {\n let resource: {\n [prop: string]: any;\n } = {};\n let len = mappings.length;\n for (let i = 0; i < len; i++) {\n let mapping = mappings[i];\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n return JSON.stringify(resource);\n}\n\nexport function metadataValidator(p: any) {\n let validType = p && type.isObject(p);\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n for (let key in p) {\n let val = p[key];\n if (key === 'customMetadata') {\n if (!type.isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n } else {\n if (type.isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/metadata.ts","/**\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 */\nimport * as errorsExports from './error';\nimport { errors } from './error';\nimport * as MetadataUtils from './metadata';\nimport * as type from './type';\n\n/**\n * @param name Name of the function.\n * @param specs Argument specs.\n * @param passed The actual arguments passed to the function.\n * @throws {fbs.Error} If the arguments are invalid.\n */\nexport function validate(name: string, specs: ArgSpec[], passed: IArguments) {\n let minArgs = specs.length;\n let maxArgs = specs.length;\n for (let i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n let validLength = minArgs <= passed.length && passed.length <= maxArgs;\n if (!validLength) {\n throw errorsExports.invalidArgumentCount(\n minArgs,\n maxArgs,\n name,\n passed.length\n );\n }\n for (let i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n } catch (e) {\n if (e instanceof Error) {\n throw errorsExports.invalidArgument(i, name, e.message);\n } else {\n throw errorsExports.invalidArgument(i, name, e);\n }\n }\n }\n}\n\n/**\n * @struct\n */\nexport class ArgSpec {\n validator: (p1: any) => void;\n optional: boolean;\n\n constructor(validator: (p1: any) => void, opt_optional?: boolean) {\n let self = this;\n this.validator = function(p: any) {\n if (self.optional && !type.isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!opt_optional;\n }\n}\n\nexport function and_(v1: (p1: any) => void, v2: Function): (p1: any) => void {\n return function(p) {\n v1(p);\n v2(p);\n };\n}\n\nexport function stringSpec(\n opt_validator?: (p1: any) => void | null,\n opt_optional?: boolean\n): ArgSpec {\n function stringValidator(p: any) {\n if (!type.isString(p)) {\n throw 'Expected string.';\n }\n }\n let validator;\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n } else {\n validator = stringValidator;\n }\n return new ArgSpec(validator, opt_optional);\n}\n\nexport function uploadDataSpec(): ArgSpec {\n function validator(p: any) {\n let valid =\n p instanceof Uint8Array ||\n p instanceof ArrayBuffer ||\n (type.isNativeBlobDefined() && p instanceof Blob);\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n return new ArgSpec(validator);\n}\n\nexport function metadataSpec(opt_optional?: boolean): ArgSpec {\n return new ArgSpec(MetadataUtils.metadataValidator, opt_optional);\n}\n\nexport function nonNegativeNumberSpec(): ArgSpec {\n function validator(p: any) {\n let valid = type.isNumber(p) && p >= 0;\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n return new ArgSpec(validator);\n}\n\nexport function looseObjectSpec(\n opt_validator?: ((p1: any) => void) | null,\n opt_optional?: boolean\n): ArgSpec {\n function validator(p: any) {\n let isLooseObject = p === null || (type.isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\n\nexport function nullFunctionSpec(opt_optional?: boolean): ArgSpec {\n function validator(p: any) {\n let valid = p === null || type.isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new ArgSpec(validator, opt_optional);\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/args.ts","/**\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/**\n * @fileoverview Some methods copied from goog.fs.\n * We don't include goog.fs because it pulls in a bunch of Deferred code that\n * bloats the size of the released binary.\n */\nimport * as array from './array';\nimport * as type from './type';\n\ndeclare var IBlobBuilder;\ndeclare var BlobBuilder;\ndeclare var WebKitBlobBuilder;\n\nfunction getBlobBuilder(): (typeof IBlobBuilder) | undefined {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n } else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n } else {\n return undefined;\n }\n}\n\n/**\n * Concatenates one or more values together and converts them to a Blob.\n *\n * @param var_args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob(...var_args: (string | Blob | ArrayBuffer)[]): Blob {\n let BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n let bb = new BlobBuilder();\n for (let i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n return bb.getBlob();\n } else {\n if (type.isNativeBlobDefined()) {\n return new Blob(var_args);\n } else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n\n/**\n * Slices the blob. The returned blob contains data from the start byte\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\n *\n * @param blob The blob to be sliced.\n * @param start Index of the starting byte.\n * @param end Index of the ending byte.\n * @return The blob slice or null if not supported.\n */\nexport function sliceBlob(blob: Blob, start: number, end: number): Blob | null {\n if ((blob as any).webkitSlice) {\n return (blob as any).webkitSlice(start, end);\n } else if ((blob as any).mozSlice) {\n return (blob as any).mozSlice(start, end);\n } else if (blob.slice) {\n return blob.slice(start, end);\n }\n return null;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/fs.ts","/**\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\n/**\n * Returns true if the object is contained in the array (compared with ===).\n * @template T\n */\nexport function contains(array: T[], elem: T): boolean {\n return array.indexOf(elem) !== -1;\n}\n\n/**\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\n * @template T\n */\nexport function clone(arraylike: T[]): T[] {\n return Array.prototype.slice.call(arraylike);\n}\n\n/**\n * Removes the given element from the given array, if it is contained.\n * Directly modifies the passed-in array.\n * @template T\n */\nexport function remove(array: T[], elem: T) {\n const i = array.indexOf(elem);\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/array.ts","/**\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\n/**\n * @fileoverview Defines methods for interacting with the network.\n */\n\nimport { Metadata } from '../metadata';\n\nimport * as array from './array';\nimport { AuthWrapper } from './authwrapper';\nimport { FbsBlob } from './blob';\nimport * as errorsExports from './error';\nimport { FirebaseStorageError } from './error';\nimport { errors } from './error';\nimport { Location } from './location';\nimport * as MetadataUtils from './metadata';\nimport * as object from './object';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport { XhrIo } from './xhrio';\n\n/**\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\n */\nexport function handlerCheck(cndn: boolean) {\n if (!cndn) {\n throw errorsExports.unknown();\n }\n}\n\nexport function metadataHandler(\n authWrapper: AuthWrapper,\n mappings: MetadataUtils.Mappings\n): (p1: XhrIo, p2: string) => Metadata {\n function handler(xhr: XhrIo, text: string): Metadata {\n let metadata = MetadataUtils.fromResourceString(\n authWrapper,\n text,\n mappings\n );\n handlerCheck(metadata !== null);\n return metadata as Metadata;\n }\n return handler;\n}\n\nexport function sharedErrorHandler(\n location: Location\n): (p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError {\n function errorHandler(\n xhr: XhrIo,\n err: FirebaseStorageError\n ): FirebaseStorageError {\n let newErr;\n if (xhr.getStatus() === 401) {\n newErr = errorsExports.unauthenticated();\n } else {\n if (xhr.getStatus() === 402) {\n newErr = errorsExports.quotaExceeded(location.bucket);\n } else {\n if (xhr.getStatus() === 403) {\n newErr = errorsExports.unauthorized(location.path);\n } else {\n newErr = err;\n }\n }\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\n\nexport function objectErrorHandler(\n location: Location\n): (p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError {\n let shared = sharedErrorHandler(location);\n\n function errorHandler(\n xhr: XhrIo,\n err: FirebaseStorageError\n ): FirebaseStorageError {\n let newErr = shared(xhr, err);\n if (xhr.getStatus() === 404) {\n newErr = errorsExports.objectNotFound(location.path);\n }\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n return errorHandler;\n}\n\nexport function getMetadata(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings\n): RequestInfo {\n let urlPart = location.fullServerUrl();\n let url = UrlUtils.makeNormalUrl(urlPart);\n let method = 'GET';\n let timeout = authWrapper.maxOperationRetryTime();\n let requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(authWrapper, mappings),\n timeout\n );\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function updateMetadata(\n authWrapper: AuthWrapper,\n location: Location,\n metadata: Metadata,\n mappings: MetadataUtils.Mappings\n): RequestInfo {\n let urlPart = location.fullServerUrl();\n let url = UrlUtils.makeNormalUrl(urlPart);\n let method = 'PATCH';\n let body = MetadataUtils.toResourceString(metadata, mappings);\n let headers = { 'Content-Type': 'application/json; charset=utf-8' };\n let timeout = authWrapper.maxOperationRetryTime();\n let requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(authWrapper, mappings),\n timeout\n );\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function deleteObject(\n authWrapper: AuthWrapper,\n location: Location\n): RequestInfo {\n let urlPart = location.fullServerUrl();\n let url = UrlUtils.makeNormalUrl(urlPart);\n let method = 'DELETE';\n let timeout = authWrapper.maxOperationRetryTime();\n\n function handler(xhr: XhrIo, text: string) {}\n let requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nexport function determineContentType_(\n metadata: Metadata | null,\n blob: FbsBlob | null\n): string {\n return (\n (metadata && metadata['contentType']) ||\n (blob && blob.type()) ||\n 'application/octet-stream'\n );\n}\n\nexport function metadataForUpload_(\n location: Location,\n blob: FbsBlob,\n opt_metadata?: Metadata | null\n): Metadata {\n let metadata = object.clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n return metadata;\n}\n\nexport function multipartUpload(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings,\n blob: FbsBlob,\n opt_metadata?: Metadata | null\n): RequestInfo {\n let urlPart = location.bucketOnlyServerUrl();\n let headers: { [prop: string]: string } = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n\n function genBoundary() {\n let str = '';\n for (let i = 0; i < 2; i++) {\n str = str + Math.random().toString().slice(2);\n }\n return str;\n }\n let boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n let metadata = metadataForUpload_(location, blob, opt_metadata);\n let metadataString = MetadataUtils.toResourceString(metadata, mappings);\n let preBlobPart =\n '--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' +\n metadataString +\n '\\r\\n--' +\n boundary +\n '\\r\\n' +\n 'Content-Type: ' +\n metadata['contentType'] +\n '\\r\\n\\r\\n';\n let postBlobPart = '\\r\\n--' + boundary + '--';\n let body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n let urlParams = { name: metadata['fullPath'] };\n let url = UrlUtils.makeUploadUrl(urlPart);\n let method = 'POST';\n let timeout = authWrapper.maxUploadRetryTime();\n let requestInfo = new RequestInfo(\n url,\n method,\n metadataHandler(authWrapper, mappings),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param current The number of bytes that have been uploaded so far.\n * @param total The total number of bytes in the upload.\n * @param opt_finalized True if the server has finished the upload.\n * @param opt_metadata The upload metadata, should\n * only be passed if opt_finalized is true.\n * @struct\n */\nexport class ResumableUploadStatus {\n finalized: boolean;\n metadata: Metadata | null;\n\n constructor(\n public current: number,\n public total: number,\n finalized?: boolean,\n metadata?: Metadata | null\n ) {\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n}\n\nexport function checkResumeHeader_(xhr: XhrIo, opt_allowed?: string[]): string {\n let status;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n } catch (e) {\n handlerCheck(false);\n }\n let allowed = opt_allowed || ['active'];\n handlerCheck(array.contains(allowed, status));\n return status as string;\n}\n\nexport function createResumableUpload(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings,\n blob: FbsBlob,\n opt_metadata?: Metadata | null\n): RequestInfo {\n let urlPart = location.bucketOnlyServerUrl();\n let metadata = metadataForUpload_(location, blob, opt_metadata);\n let urlParams = { name: metadata['fullPath'] };\n let url = UrlUtils.makeUploadUrl(urlPart);\n let method = 'POST';\n let headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n let body = MetadataUtils.toResourceString(metadata, mappings);\n let timeout = authWrapper.maxUploadRetryTime();\n\n function handler(xhr: XhrIo, text: string): string {\n checkResumeHeader_(xhr);\n let url;\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n } catch (e) {\n handlerCheck(false);\n }\n handlerCheck(type.isString(url));\n return url as string;\n }\n let requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n */\nexport function getResumableUploadStatus(\n authWrapper: AuthWrapper,\n location: Location,\n url: string,\n blob: FbsBlob\n): RequestInfo {\n let headers = { 'X-Goog-Upload-Command': 'query' };\n\n function handler(xhr: XhrIo, text: string): ResumableUploadStatus {\n let status = checkResumeHeader_(xhr, ['active', 'final']);\n let sizeString;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n } catch (e) {\n handlerCheck(false);\n }\n let size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n let method = 'POST';\n let timeout = authWrapper.maxUploadRetryTime();\n let requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n/**\n * Any uploads via the resumable upload API must transfer a number of bytes\n * that is a multiple of this number.\n */\nexport const resumableUploadChunkSize: number = 256 * 1024;\n\n/**\n * @param url From a call to fbs.requests.createResumableUpload.\n * @param chunkSize Number of bytes to upload.\n * @param opt_status The previous status.\n * If not passed or null, we start from the beginning.\n * @throws fbs.Error If the upload is already complete, the passed in status\n * has a final size inconsistent with the blob, or the blob cannot be sliced\n * for upload.\n */\nexport function continueResumableUpload(\n location: Location,\n authWrapper: AuthWrapper,\n url: string,\n blob: FbsBlob,\n chunkSize: number,\n mappings: MetadataUtils.Mappings,\n opt_status?: ResumableUploadStatus | null,\n opt_progressCallback?: ((p1: number, p2: number) => void) | null\n): RequestInfo {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n let status = new ResumableUploadStatus(0, 0);\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n } else {\n status.current = 0;\n status.total = blob.size();\n }\n if (blob.size() !== status.total) {\n throw errorsExports.serverFileWrongSize();\n }\n let bytesLeft = status.total - status.current;\n let bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n let startByte = status.current;\n let endByte = startByte + bytesToUpload;\n let uploadCommand =\n bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n let headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n let body = blob.slice(startByte, endByte);\n if (body === null) {\n throw errorsExports.cannotSliceBlob();\n }\n\n function handler(xhr: XhrIo, text: string): ResumableUploadStatus {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n let uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n let newCurrent = status.current + bytesToUpload;\n let size = blob.size();\n let metadata;\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n } else {\n metadata = null;\n }\n return new ResumableUploadStatus(\n newCurrent,\n size,\n uploadStatus === 'final',\n metadata\n );\n }\n let method = 'POST';\n let timeout = authWrapper.maxUploadRetryTime();\n let requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/requests.ts","/**\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\n/**\n * @fileoverview Method for invoking a callback asynchronously.\n */\nimport * as promiseimpl from './promise_external';\n\n/**\n * Returns a function that invokes f with its arguments asynchronously as a\n * microtask, i.e. as soon as possible after the current script returns back\n * into browser code.\n */\nexport function async(f: Function): Function {\n return function(...argsToForward: any[]) {\n promiseimpl.resolve(true).then(function() {\n f.apply(null, argsToForward);\n });\n };\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/async.ts","/**\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\n/**\n * @fileoverview Provides a method for running a function with exponential\n * backoff.\n */\ntype id = (p1: boolean) => void;\n\nexport { id };\n\n/**\n * @param f May be invoked\n * before the function returns.\n * @param callback Get all the arguments passed to the function\n * passed to f, including the initial boolean.\n */\nexport function start(\n f: (\n p1: (success: boolean, ...rest: any[]) => void,\n canceled: boolean\n ) => void,\n callback: Function,\n timeout: number\n): id {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n let waitSeconds = 1;\n // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n let timeoutId: any = null;\n let hitTimeout = false;\n let cancelState = 0;\n\n function canceled() {\n return cancelState === 2;\n }\n let triggeredCallback = false;\n\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n\n function callWithDelay(millis: number): void {\n timeoutId = setTimeout(function() {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n\n function handler(success: boolean, ...var_args: any[]): void {\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n let mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n let waitMillis;\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n } else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n callWithDelay(waitMillis);\n }\n let stopped = false;\n\n function stop(wasTimeout: boolean): void {\n if (stopped) {\n return;\n }\n stopped = true;\n if (triggeredCallback) {\n return;\n }\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n clearTimeout(timeoutId);\n callWithDelay(0);\n } else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n callWithDelay(0);\n setTimeout(function() {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n\n/**\n * Stops the retry loop from repeating.\n * If the function is currently \"in between\" retries, it is invoked immediately\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\n * after the current invocation finishes iff the current invocation would have\n * triggered another retry.\n */\nexport function stop(id: id) {\n id(false);\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/backoff.ts","/**\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\n/**\n * @fileoverview Defines methods used to actually send HTTP requests from\n * abstract representations.\n */\nimport * as array from './array';\nimport * as backoff from './backoff';\nimport * as errorsExports from './error';\nimport { FirebaseStorageError } from './error';\nimport { errors } from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport * as XhrIoExports from './xhrio';\nimport { Headers, XhrIo } from './xhrio';\nimport { XhrIoPool } from './xhriopool';\nimport { FirebaseNamespace } from '../../app/firebase_app';\nimport firebase from '../../app';\n\n/**\n * @template T\n */\nexport interface Request {\n getPromise(): Promise;\n\n /**\n * Cancels the request. IMPORTANT: the promise may still be resolved with an\n * appropriate value (if the request is finished before you call this method,\n * but the promise has not yet been resolved), so don't just assume it will be\n * rejected if you call this function.\n * @param appDelete True if the cancelation came from the app being deleted.\n */\n cancel(appDelete?: boolean): void;\n}\n\n/**\n * @struct\n * @template T\n */\nclass NetworkRequest implements Request {\n private url_: string;\n private method_: string;\n private headers_: Headers;\n private body_: string | Blob | Uint8Array | null;\n private successCodes_: number[];\n private additionalRetryCodes_: number[];\n private pendingXhr_: XhrIo | null = null;\n private backoffId_: backoff.id | null = null;\n private resolve_: Function | null = null;\n private reject_: Function | null = null;\n private canceled_: boolean = false;\n private appDelete_: boolean = false;\n private callback_: (p1: XhrIo, p2: string) => T;\n private errorCallback_:\n | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)\n | null;\n private progressCallback_: ((p1: number, p2: number) => void) | null;\n private timeout_: number;\n private pool_: XhrIoPool;\n promise_: Promise;\n\n constructor(\n url: string,\n method: string,\n headers: Headers,\n body: string | Blob | Uint8Array | null,\n successCodes: number[],\n additionalRetryCodes: number[],\n callback: (p1: XhrIo, p2: string) => T,\n errorCallback:\n | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)\n | null,\n timeout: number,\n progressCallback: ((p1: number, p2: number) => void) | null,\n pool: XhrIoPool\n ) {\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n let self = this;\n this.promise_ = promiseimpl.make(function(resolve, reject) {\n self.resolve_ = resolve;\n self.reject_ = reject;\n self.start_();\n });\n }\n\n /**\n * Actually starts the retry loop.\n */\n private start_() {\n let self = this;\n\n function doTheRequest(\n backoffCallback: (p1: boolean, ...p2: any[]) => void,\n canceled: boolean\n ) {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n let xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n\n function progressListener(progressEvent: ProgressEvent) {\n let loaded = progressEvent.loaded;\n let total = progressEvent.lengthComputable ? progressEvent.total : -1;\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then(function(xhr: XhrIo) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr as XhrIo;\n let hitServer =\n xhr.getErrorCode() === XhrIoExports.ErrorCode.NO_ERROR;\n let status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n let wasCanceled =\n xhr.getErrorCode() === XhrIoExports.ErrorCode.ABORT;\n backoffCallback(\n false,\n new RequestEndStatus(false, null, wasCanceled)\n );\n return;\n }\n let successCode = array.contains(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n\n /**\n * @param requestWentThrough True if the request eventually went\n * through, false if it hit the retry limit or was canceled.\n */\n function backoffDone(\n requestWentThrough: boolean,\n status: RequestEndStatus\n ) {\n let resolve = self.resolve_ as Function;\n let reject = self.reject_ as Function;\n let xhr = status.xhr as XhrIo;\n if (status.wasSuccessCode) {\n try {\n let result = self.callback_(xhr, xhr.getResponseText());\n if (type.isJustDef(result)) {\n resolve(result);\n } else {\n resolve();\n }\n } catch (e) {\n reject(e);\n }\n } else {\n if (xhr !== null) {\n let err = errorsExports.unknown();\n err.setServerResponseProp(xhr.getResponseText());\n if (self.errorCallback_) {\n reject(self.errorCallback_(xhr, err));\n } else {\n reject(err);\n }\n } else {\n if (status.canceled) {\n let err = self.appDelete_\n ? errorsExports.appDeleted()\n : errorsExports.canceled();\n reject(err);\n } else {\n let err = errorsExports.retryLimitExceeded();\n reject(err);\n }\n }\n }\n }\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n } else {\n this.backoffId_ = backoff.start(doTheRequest, backoffDone, this.timeout_);\n }\n }\n\n /** @inheritDoc */\n getPromise() {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(appDelete?: boolean) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n if (this.backoffId_ !== null) {\n backoff.stop(this.backoffId_);\n }\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n }\n\n private isRetryStatusCode_(status: number): boolean {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n let isFiveHundredCode = status >= 500 && status < 600;\n let extraRetryCodes = [\n // Request Timeout: web server didn't receive full request in time.\n 408,\n // Too Many Requests: you're getting rate-limited, basically.\n 429\n ];\n let isExtraRetryCode = array.contains(extraRetryCodes, status);\n let isRequestSpecificRetryCode = array.contains(\n this.additionalRetryCodes_,\n status\n );\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n }\n}\n\n/**\n * A collection of information about the result of a network request.\n * @param opt_canceled Defaults to false.\n * @struct\n */\nexport class RequestEndStatus {\n /**\n * True if the request was canceled.\n */\n canceled: boolean;\n\n constructor(\n public wasSuccessCode: boolean,\n public xhr: XhrIo | null,\n opt_canceled?: boolean\n ) {\n this.canceled = !!opt_canceled;\n }\n}\n\nexport function addAuthHeader_(headers: Headers, authToken: string | null) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\n\nexport function addVersionHeader_(headers: Headers) {\n let number =\n typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n\n/**\n * @template T\n */\nexport function makeRequest(\n requestInfo: RequestInfo,\n authToken: string | null,\n pool: XhrIoPool\n): Request {\n let queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);\n let url = requestInfo.url + queryPart;\n let headers = object.clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest(\n url,\n requestInfo.method,\n headers,\n requestInfo.body,\n requestInfo.successCodes,\n requestInfo.additionalRetryCodes,\n requestInfo.handler,\n requestInfo.errorHandler,\n requestInfo.timeout,\n requestInfo.progressCallback,\n pool\n );\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/request.ts","/**\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 */\nimport { StringFormat } from './storage/implementation/string';\nimport { TaskEvent } from './storage/implementation/taskenums';\nimport { TaskState } from './storage/implementation/taskenums';\nimport { XhrIoPool } from './storage/implementation/xhriopool';\nimport { Reference } from './storage/reference';\nimport { Service } from './storage/service';\nimport firebase from './app';\nimport { FirebaseApp, FirebaseServiceFactory } from './app/firebase_app';\n/**\n * Type constant for Firebase Storage.\n */\nconst STORAGE_TYPE = 'storage';\n\nfunction factory(app: FirebaseApp, unused: any, opt_url?: string): Service {\n return new Service(app, new XhrIoPool(), opt_url);\n}\n\nexport function registerStorage(instance) {\n let namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: Service,\n Reference: Reference\n };\n instance.INTERNAL.registerService(\n STORAGE_TYPE,\n factory as FirebaseServiceFactory,\n namespaceExports,\n undefined,\n // Allow multiple storage instances per app.\n true\n );\n}\n\nregisterStorage(firebase);\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage.ts","/**\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/**\n * @fileoverview Constants used in the Firebase Storage library.\n */\n\n/**\n * Domain and scheme for API calls.\n */\nexport const domainBase: string = 'https://firebasestorage.googleapis.com';\n\n/**\n * Domain and scheme for object downloads.\n */\nexport const downloadBase: string = 'https://firebasestorage.googleapis.com';\n\n/**\n * Base URL for non-upload calls to the API.\n */\nexport const apiBaseUrl: string = '/v0';\n\n/**\n * Base URL for upload calls to the API.\n */\nexport const apiUploadBaseUrl: string = '/v0';\n\nexport function setDomainBase(domainBase: string) {\n domainBase = domainBase;\n}\n\nexport const configOption: string = 'storageBucket';\n\n/**\n * 1 minute\n */\nexport const shortMaxOperationRetryTime: number = 1 * 60 * 1000;\n\n/**\n * 2 minutes\n */\nexport const defaultMaxOperationRetryTime: number = 2 * 60 * 1000;\n\n/**\n * 10 minutes\n */\nexport const defaultMaxUploadRetryTime: number = 10 * 60 * 100;\n\n/**\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\n * enough for us to use it directly.\n */\nexport const minSafeInteger: number = -9007199254740991;\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/constants.ts","/**\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\n/**\n * @fileoverview A lightweight wrapper around XMLHttpRequest with a\n * goog.net.XhrIo-like interface.\n */\n\nexport type Headers = { [name: string]: string | number };\n\nexport interface XhrIo {\n send(\n url: string,\n method: string,\n opt_body?: ArrayBufferView | Blob | string | null,\n opt_headers?: Headers\n ): Promise;\n\n getErrorCode(): ErrorCode;\n\n getStatus(): number;\n\n getResponseText(): string;\n\n /**\n * Abort the request.\n */\n abort(): void;\n\n getResponseHeader(header: string): string | null;\n\n addUploadProgressListener(listener: (p1: Event) => void): void;\n\n removeUploadProgressListener(listener: (p1: Event) => void): void;\n}\n\n/**\n * @enum{number}\n */\nexport enum ErrorCode {\n NO_ERROR = 0,\n NETWORK_ERROR = 1,\n ABORT = 2\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/xhrio.ts","/**\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 */\nimport * as errorsExports from './error';\nimport * as object from './object';\nimport * as promiseimpl from './promise_external';\nimport * as type from './type';\nimport * as XhrIoExports from './xhrio';\nimport { Headers, XhrIo } from './xhrio';\n\n/**\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\n * doesn't work in React Native on Android.\n */\nexport class NetworkXhrIo implements XhrIo {\n private xhr_: XMLHttpRequest;\n private errorCode_: XhrIoExports.ErrorCode;\n private sendPromise_: Promise;\n private sent_: boolean = false;\n\n constructor() {\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = XhrIoExports.ErrorCode.NO_ERROR;\n this.sendPromise_ = promiseimpl.make((resolve, reject) => {\n this.xhr_.addEventListener('abort', event => {\n this.errorCode_ = XhrIoExports.ErrorCode.ABORT;\n resolve(this);\n });\n this.xhr_.addEventListener('error', event => {\n this.errorCode_ = XhrIoExports.ErrorCode.NETWORK_ERROR;\n resolve(this);\n });\n this.xhr_.addEventListener('load', event => {\n resolve(this);\n });\n });\n }\n\n /**\n * @override\n */\n send(\n url: string,\n method: string,\n opt_body?: ArrayBufferView | Blob | string | null,\n opt_headers?: Headers\n ): Promise {\n if (this.sent_) {\n throw errorsExports.internalError('cannot .send() more than once');\n }\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n if (type.isDef(opt_headers)) {\n const headers = opt_headers as Headers;\n object.forEach(headers, (key, val) => {\n this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n if (type.isDef(opt_body)) {\n this.xhr_.send(opt_body);\n } else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n }\n\n /**\n * @override\n */\n getErrorCode(): XhrIoExports.ErrorCode {\n if (!this.sent_) {\n throw errorsExports.internalError(\n 'cannot .getErrorCode() before sending'\n );\n }\n return this.errorCode_;\n }\n\n /**\n * @override\n */\n getStatus(): number {\n if (!this.sent_) {\n throw errorsExports.internalError('cannot .getStatus() before sending');\n }\n try {\n return this.xhr_.status;\n } catch (e) {\n return -1;\n }\n }\n\n /**\n * @override\n */\n getResponseText(): string {\n if (!this.sent_) {\n throw errorsExports.internalError(\n 'cannot .getResponseText() before sending'\n );\n }\n return this.xhr_.responseText;\n }\n\n /**\n * Aborts the request.\n * @override\n */\n abort() {\n this.xhr_.abort();\n }\n\n /**\n * @override\n */\n getResponseHeader(header: string): string | null {\n return this.xhr_.getResponseHeader(header);\n }\n\n /**\n * @override\n */\n addUploadProgressListener(listener: (p1: Event) => void) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n }\n\n /**\n * @override\n */\n removeUploadProgressListener(listener: (p1: Event) => void) {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/xhrio_network.ts","/**\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\n/**\n * @fileoverview Replacement for goog.net.XhrIoPool that works with fbs.XhrIo.\n */\nimport { XhrIo } from './xhrio';\nimport { NetworkXhrIo } from './xhrio_network';\n\n/**\n * Factory-like class for creating XhrIo instances.\n */\nexport class XhrIoPool {\n createXhrIo(): XhrIo {\n return new NetworkXhrIo();\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/xhriopool.ts","/**\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\n/**\n * @fileoverview Functionality related to the parsing/composition of bucket/\n * object location.\n */\nimport * as errorsExports from './error';\nimport { errors } from './error';\n\n/**\n * @struct\n */\nexport class Location {\n private path_: string;\n\n constructor(public readonly bucket: string, path: string) {\n this.path_ = path;\n }\n\n get path(): string {\n return this.path_;\n }\n\n fullServerUrl(): string {\n let encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n }\n\n bucketOnlyServerUrl(): string {\n let encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n }\n\n static makeFromBucketSpec(bucketString: string): Location {\n let bucketLocation;\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n } catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n if (bucketLocation.path === '') {\n return bucketLocation;\n } else {\n throw errorsExports.invalidDefaultBucket(bucketString);\n }\n }\n\n static makeFromUrl(url: string): Location {\n let location = null;\n let bucketDomain = '([A-Za-z0-9.\\\\-]+)';\n\n function gsModify(loc: Location) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n let gsPath = '(/(.*))?$';\n let path = '(/([^?#]*).*)?$';\n let gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n let gsIndices = { bucket: 1, path: 3 };\n\n function httpModify(loc: Location) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n let version = 'v[A-Za-z0-9_]+';\n let httpRegex = new RegExp(\n '^https?://firebasestorage\\\\.googleapis\\\\.com/' +\n version +\n '/b/' +\n bucketDomain +\n '/o' +\n path,\n 'i'\n );\n let httpIndices = { bucket: 1, path: 3 };\n let groups = [\n { regex: gsRegex, indices: gsIndices, postModify: gsModify },\n { regex: httpRegex, indices: httpIndices, postModify: httpModify }\n ];\n for (let i = 0; i < groups.length; i++) {\n let group = groups[i];\n let captures = group.regex.exec(url);\n if (captures) {\n let bucketValue = captures[group.indices.bucket];\n let pathValue = captures[group.indices.path];\n if (!pathValue) {\n pathValue = '';\n }\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n if (location == null) {\n throw errorsExports.invalidUrl(url);\n }\n return location;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/location.ts","/**\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\n/**\n * @file Provides a Blob-like wrapper for various binary types (including the\n * native Blob type). This makes it possible to upload types like ArrayBuffers,\n * making uploads possible in environments without the native Blob type.\n */\nimport * as fs from './fs';\nimport * as string from './string';\nimport { StringFormat } from './string';\nimport * as type from './type';\n\n/**\n * @param opt_elideCopy If true, doesn't copy mutable input data\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\n * modified after this blob's construction.\n */\nexport class FbsBlob {\n private data_: Blob | Uint8Array;\n private size_: number;\n private type_: string;\n\n constructor(data: Blob | Uint8Array | ArrayBuffer, opt_elideCopy?: boolean) {\n let size: number = 0;\n let blobType: string = '';\n if (type.isNativeBlob(data)) {\n this.data_ = data as Blob;\n size = (data as Blob).size;\n blobType = (data as Blob).type;\n } else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n } else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n size = this.data_.length;\n } else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data as Uint8Array;\n } else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data as Uint8Array);\n }\n size = data.length;\n }\n this.size_ = size;\n this.type_ = blobType;\n }\n\n size(): number {\n return this.size_;\n }\n\n type(): string {\n return this.type_;\n }\n\n slice(startByte: number, endByte: number): FbsBlob | null {\n if (type.isNativeBlob(this.data_)) {\n let realBlob = this.data_ as Blob;\n let sliced = fs.sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n } else {\n let slice = new Uint8Array(\n (this.data_ as Uint8Array).buffer,\n startByte,\n endByte - startByte\n );\n return new FbsBlob(slice, true);\n }\n }\n\n static getBlob(...var_args: (string | FbsBlob)[]): FbsBlob | null {\n if (type.isNativeBlobDefined()) {\n var blobby: (Blob | Uint8Array | string)[] = var_args.map(function(\n val: string | FbsBlob\n ): Blob | Uint8Array | string {\n if (val instanceof FbsBlob) {\n return val.data_;\n } else {\n return val;\n }\n });\n return new FbsBlob(fs.getBlob.apply(null, blobby));\n } else {\n let uint8Arrays: Uint8Array[] = var_args.map(function(\n val: string | FbsBlob\n ): Uint8Array {\n if (type.isString(val)) {\n return string.dataFromString(StringFormat.RAW, val as string).data;\n } else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return (val as FbsBlob).data_ as Uint8Array;\n }\n });\n let finalLength = 0;\n uint8Arrays.forEach(function(array: Uint8Array): void {\n finalLength += array.byteLength;\n });\n let merged = new Uint8Array(finalLength);\n let index = 0;\n uint8Arrays.forEach(function(array: Uint8Array) {\n for (let i = 0; i < array.length; i++) {\n merged[index++] = array[i];\n }\n });\n return new FbsBlob(merged, true);\n }\n }\n\n uploadData(): Blob | Uint8Array {\n return this.data_;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/blob.ts","/**\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 */\nimport { FirebaseStorageError } from './error';\nimport { Headers, XhrIo } from './xhrio';\n\nexport type UrlParams = { [name: string]: string };\n\nexport class RequestInfo {\n urlParams: UrlParams = {};\n headers: Headers = {};\n body: Blob | string | Uint8Array | null = null;\n\n errorHandler:\n | ((p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError)\n | null = null;\n\n /**\n * Called with the current number of bytes uploaded and total size (-1 if not\n * computable) of the request body (i.e. used to report upload progress).\n */\n progressCallback: ((p1: number, p2: number) => void) | null = null;\n successCodes: number[] = [200];\n additionalRetryCodes: number[] = [];\n\n constructor(\n public url: string,\n public method: string,\n /**\n * Returns the value with which to resolve the request's promise. Only called\n * if the request is successful. Throw from this function to reject the\n * returned Request's promise with the thrown error.\n * Note: The XhrIo passed to this function may be reused after this callback\n * returns. Do not keep a reference to it in any way.\n */\n public handler: (p1: XhrIo, p2: string) => T,\n public timeout: number\n ) {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/requestinfo.ts","/**\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 */\nimport * as type from './type';\n\ntype NextFn = (value: T) => void;\ntype ErrorFn = (error: Error) => void;\ntype CompleteFn = () => void;\ntype Unsubscribe = () => void;\n\ntype Subscribe = (\n next: NextFn | { [name: string]: string | null },\n error?: ErrorFn,\n complete?: CompleteFn\n) => Unsubscribe;\n\nexport { NextFn, ErrorFn, CompleteFn, Unsubscribe, Subscribe };\n\n/**\n * @struct\n */\nexport class Observer {\n next: NextFn | null;\n error: ErrorFn | null;\n complete: CompleteFn | null;\n\n constructor(\n nextOrObserver: NextFn | { [name: string]: string | null } | null,\n opt_error?: ErrorFn | null,\n opt_complete?: CompleteFn | null\n ) {\n let asFunctions =\n type.isFunction(nextOrObserver) ||\n type.isDef(opt_error) ||\n type.isDef(opt_complete);\n if (asFunctions) {\n this.next = nextOrObserver as NextFn | null;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n } else {\n const observer = nextOrObserver as {\n next?: NextFn | null;\n error?: ErrorFn | null;\n complete?: CompleteFn | null;\n };\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/observer.ts","/**\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 */\nimport { TaskState } from './implementation/taskenums';\nimport * as type from './implementation/type';\nimport { Metadata } from './metadata';\nimport { Reference } from './reference';\nimport { UploadTask } from './task';\n\nexport class UploadTaskSnapshot {\n constructor(\n readonly bytesTransferred: number,\n readonly totalBytes: number,\n readonly state: TaskState,\n readonly metadata: Metadata | null,\n readonly task: UploadTask,\n readonly ref: Reference\n ) {}\n\n get downloadURL(): string | null {\n if (this.metadata !== null) {\n let urls = this.metadata['downloadURLs'];\n if (urls != null && urls[0] != null) {\n return urls[0];\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/tasksnapshot.ts","/**\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/**\n * @fileoverview Defines types for interacting with blob transfer tasks.\n */\n\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { FbsBlob } from './implementation/blob';\nimport { FirebaseStorageError } from './implementation/error';\nimport { InternalTaskState } from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport {\n NextFn,\n ErrorFn,\n CompleteFn,\n Unsubscribe,\n Observer\n} from './implementation/observer';\nimport { Request } from './implementation/request';\nimport * as RequestExports from './implementation/request';\nimport { Subscribe } from './implementation/observer';\nimport { TaskEvent, TaskState } from './implementation/taskenums';\nimport { UploadTaskSnapshot } from './tasksnapshot';\nimport * as fbsArgs from './implementation/args';\nimport { ArgSpec } from './implementation/args';\nimport * as fbsArray from './implementation/array';\nimport { async as fbsAsync } from './implementation/async';\nimport { errors as fbsErrors } from './implementation/error';\nimport * as errors from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as fbsMetadata from './implementation/metadata';\nimport * as fbsPromiseimpl from './implementation/promise_external';\nimport { RequestInfo } from './implementation/requestinfo';\nimport * as fbsRequests from './implementation/requests';\nimport * as fbsTaskEnums from './implementation/taskenums';\nimport * as typeUtils from './implementation/type';\nimport { Reference } from './reference';\n\n/**\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\n * upload and manage callbacks for various events.\n */\nexport class UploadTask {\n private ref_: Reference;\n private authWrapper_: AuthWrapper;\n private location_: Location;\n private blob_: FbsBlob;\n private metadata_: Metadata | null;\n private mappings_: fbsMetadata.Mappings;\n private transferred_: number = 0;\n private needToFetchStatus_: boolean = false;\n private needToFetchMetadata_: boolean = false;\n private observers_: Observer[] = [];\n private resumable_: boolean;\n private state_: InternalTaskState;\n private error_: Error | null = null;\n private uploadUrl_: string | null = null;\n private request_: Request | null = null;\n private chunkMultiplier_: number = 1;\n private errorHandler_: (p1: FirebaseStorageError) => void;\n private metadataErrorHandler_: (p1: FirebaseStorageError) => void;\n private resolve_: ((p1: UploadTaskSnapshot) => void) | null = null;\n private reject_: ((p1: Error) => void) | null = null;\n private promise_: Promise;\n\n /**\n * @param ref The firebaseStorage.Reference object this task came\n * from, untyped to avoid cyclic dependencies.\n * @param blob The blob to upload.\n */\n constructor(\n ref: Reference,\n authWrapper: AuthWrapper,\n location: Location,\n mappings: fbsMetadata.Mappings,\n blob: FbsBlob,\n metadata: Metadata | null = null\n ) {\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n this.errorHandler_ = error => {\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n if (error.codeEquals(errors.Code.CANCELED)) {\n this.needToFetchStatus_ = true;\n this.completeTransitions_();\n } else {\n this.error_ = error;\n this.transition_(InternalTaskState.ERROR);\n }\n };\n this.metadataErrorHandler_ = error => {\n this.request_ = null;\n if (error.codeEquals(errors.Code.CANCELED)) {\n this.completeTransitions_();\n } else {\n this.error_ = error;\n this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = fbsPromiseimpl.make((resolve, reject) => {\n this.resolve_ = resolve;\n this.reject_ = reject;\n this.start_();\n });\n\n // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n this.promise_.then(null, () => {});\n }\n\n private makeProgressCallback_(): (p1: number, p2: number) => void {\n const sizeBefore = this.transferred_;\n return (loaded, total) => {\n this.updateProgress_(sizeBefore + loaded);\n };\n }\n\n private shouldDoResumable_(blob: FbsBlob): boolean {\n return blob.size() > 256 * 1024;\n }\n\n private start_() {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n if (this.request_ !== null) {\n return;\n }\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n } else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n } else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n } else {\n this.continueUpload_();\n }\n }\n }\n } else {\n this.oneShotUpload_();\n }\n }\n\n private resolveToken_(callback: (p1: string | null) => void) {\n this.authWrapper_.getAuthToken().then(authToken => {\n switch (this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n default:\n }\n });\n }\n\n // TODO(andysoto): assert false\n\n private createResumable_() {\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.createResumableUpload(\n this.authWrapper_,\n this.location_,\n this.mappings_,\n this.blob_,\n this.metadata_\n );\n const createRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = createRequest;\n createRequest.getPromise().then((url: string) => {\n this.request_ = null;\n this.uploadUrl_ = url;\n this.needToFetchStatus_ = false;\n this.completeTransitions_();\n }, this.errorHandler_);\n });\n }\n\n private fetchStatus_() {\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this.uploadUrl_ as string;\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.getResumableUploadStatus(\n this.authWrapper_,\n this.location_,\n url,\n this.blob_\n );\n const statusRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = statusRequest;\n statusRequest.getPromise().then(status => {\n status = status as fbsRequests.ResumableUploadStatus;\n this.request_ = null;\n this.updateProgress_(status.current);\n this.needToFetchStatus_ = false;\n if (status.finalized) {\n this.needToFetchMetadata_ = true;\n }\n this.completeTransitions_();\n }, this.errorHandler_);\n });\n }\n\n private continueUpload_() {\n const chunkSize =\n fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n const status = new fbsRequests.ResumableUploadStatus(\n this.transferred_,\n this.blob_.size()\n );\n\n // TODO(andysoto): assert(this.uploadUrl_ !== null);\n const url = this.uploadUrl_ as string;\n this.resolveToken_(authToken => {\n let requestInfo;\n try {\n requestInfo = fbsRequests.continueResumableUpload(\n this.location_,\n this.authWrapper_,\n url,\n this.blob_,\n chunkSize,\n this.mappings_,\n status,\n this.makeProgressCallback_()\n );\n } catch (e) {\n this.error_ = e;\n this.transition_(InternalTaskState.ERROR);\n return;\n }\n const uploadRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = uploadRequest;\n uploadRequest\n .getPromise()\n .then((newStatus: fbsRequests.ResumableUploadStatus) => {\n this.increaseMultiplier_();\n this.request_ = null;\n this.updateProgress_(newStatus.current);\n if (newStatus.finalized) {\n this.metadata_ = newStatus.metadata;\n this.transition_(InternalTaskState.SUCCESS);\n } else {\n this.completeTransitions_();\n }\n }, this.errorHandler_);\n });\n }\n\n private increaseMultiplier_() {\n const currentSize =\n fbsRequests.resumableUploadChunkSize * this.chunkMultiplier_;\n\n // Max chunk size is 32M.\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n }\n\n private fetchMetadata_() {\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.getMetadata(\n this.authWrapper_,\n this.location_,\n this.mappings_\n );\n const metadataRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = metadataRequest;\n metadataRequest.getPromise().then(metadata => {\n this.request_ = null;\n this.metadata_ = metadata;\n this.transition_(InternalTaskState.SUCCESS);\n }, this.metadataErrorHandler_);\n });\n }\n\n private oneShotUpload_() {\n this.resolveToken_(authToken => {\n const requestInfo = fbsRequests.multipartUpload(\n this.authWrapper_,\n this.location_,\n this.mappings_,\n this.blob_,\n this.metadata_\n );\n const multipartRequest = this.authWrapper_.makeRequest(\n requestInfo,\n authToken\n );\n this.request_ = multipartRequest;\n multipartRequest.getPromise().then(metadata => {\n this.request_ = null;\n this.metadata_ = metadata;\n this.updateProgress_(this.blob_.size());\n this.transition_(InternalTaskState.SUCCESS);\n }, this.errorHandler_);\n });\n }\n\n private updateProgress_(transferred: number) {\n const old = this.transferred_;\n this.transferred_ = transferred;\n\n // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n }\n\n private transition_(state: InternalTaskState) {\n if (this.state_ === state) {\n return;\n }\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n break;\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n const wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n break;\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = errors.canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n }\n\n private completeTransitions_() {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n }\n\n get snapshot(): UploadTaskSnapshot {\n const externalState = fbsTaskEnums.taskStateFromInternalTaskState(\n this.state_\n );\n return new UploadTaskSnapshot(\n this.transferred_,\n this.blob_.size(),\n externalState,\n this.metadata_,\n this,\n this.ref_\n );\n }\n\n /**\n * Adds a callback for an event.\n * @param type The type of event to listen for.\n */\n on(\n type: TaskEvent,\n nextOrObserver = undefined,\n error = undefined,\n completed = undefined\n ): Unsubscribe | Subscribe {\n function typeValidator(_p: any) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw `Expected one of the event types: [${TaskEvent.STATE_CHANGED}].`;\n }\n }\n const nextOrObserverMessage =\n 'Expected a function or an Object with one of ' +\n '`next`, `error`, `complete` properties.';\n const nextValidator = fbsArgs.nullFunctionSpec(true).validator;\n const observerValidator = fbsArgs.looseObjectSpec(null, true).validator;\n\n function nextOrObserverValidator(p: any) {\n try {\n nextValidator(p);\n return;\n } catch (e) {}\n try {\n observerValidator(p);\n const anyDefined =\n typeUtils.isJustDef(p['next']) ||\n typeUtils.isJustDef(p['error']) ||\n typeUtils.isJustDef(p['complete']);\n if (!anyDefined) {\n throw '';\n }\n return;\n } catch (e) {\n throw nextOrObserverMessage;\n }\n }\n const specs = [\n fbsArgs.stringSpec(typeValidator),\n fbsArgs.looseObjectSpec(nextOrObserverValidator, true),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n fbsArgs.validate('on', specs, arguments);\n const self = this;\n\n function makeBinder(\n specs: ArgSpec[] | null\n ): Subscribe {\n function binder(\n nextOrObserver:\n | NextFn\n | { [name: string]: string | null }\n | null,\n error?: ErrorFn | null,\n opt_complete?: CompleteFn | null\n ) {\n if (specs !== null) {\n fbsArgs.validate('on', specs, arguments);\n }\n const observer = new Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return () => {\n self.removeObserver_(observer);\n };\n }\n return binder;\n }\n\n function binderNextOrObserverValidator(p: any) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n const binderSpecs = [\n fbsArgs.looseObjectSpec(binderNextOrObserverValidator),\n fbsArgs.nullFunctionSpec(true),\n fbsArgs.nullFunctionSpec(true)\n ];\n const typeOnly = !(\n typeUtils.isJustDef(nextOrObserver) ||\n typeUtils.isJustDef(error) ||\n typeUtils.isJustDef(completed)\n );\n if (typeOnly) {\n return makeBinder(binderSpecs);\n } else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n }\n\n /**\n * This object behaves like a Promise, and resolves with its snapshot data\n * when the upload completes.\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\n * @param onRejected The rejection callback.\n */\n then(\n onFulfilled?: ((value: UploadTaskSnapshot) => U | PromiseLike) | null,\n onRejected?: ((error: any) => U | PromiseLike) | null\n ): Promise {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(\n onFulfilled as (value: UploadTaskSnapshot) => U | PromiseLike,\n onRejected as ((error: any) => PromiseLike) | null\n );\n }\n\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n catch(onRejected: (p1: Error) => T | PromiseLike): Promise {\n return this.then(null, onRejected);\n }\n\n /**\n * Adds the given observer.\n */\n private addObserver_(observer: Observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n }\n\n /**\n * Removes the given observer.\n */\n private removeObserver_(observer: Observer) {\n fbsArray.remove(this.observers_, observer);\n }\n\n private notifyObservers_() {\n this.finishPromise_();\n const observers = fbsArray.clone(this.observers_);\n observers.forEach(observer => {\n this.notifyObserver_(observer);\n });\n }\n\n private finishPromise_() {\n if (this.resolve_ !== null) {\n let triggered = true;\n switch (fbsTaskEnums.taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n fbsAsync(this.resolve_.bind(null, this.snapshot))();\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n const toCall = this.reject_ as ((p1: Error) => void);\n fbsAsync(toCall.bind(null, this.error_ as Error))();\n break;\n default:\n triggered = false;\n break;\n }\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n }\n\n private notifyObserver_(observer: Observer) {\n const externalState = fbsTaskEnums.taskStateFromInternalTaskState(\n this.state_\n );\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_ as Error))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n fbsAsync(observer.error.bind(observer, this.error_ as Error))();\n }\n }\n }\n\n /**\n * Resumes a paused task. Has no effect on a currently running or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n resume(): boolean {\n fbsArgs.validate('resume', [], arguments);\n const valid =\n this.state_ === InternalTaskState.PAUSED ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n return valid;\n }\n\n /**\n * Pauses a currently running task. Has no effect on a paused or failed task.\n * @return True if the operation took effect, false if ignored.\n */\n pause(): boolean {\n fbsArgs.validate('pause', [], arguments);\n const valid = this.state_ === InternalTaskState.RUNNING;\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n return valid;\n }\n\n /**\n * Cancels a currently running or paused task. Has no effect on a complete or\n * failed task.\n * @return True if the operation took effect, false if ignored.\n */\n cancel(): boolean {\n fbsArgs.validate('cancel', [], arguments);\n const valid =\n this.state_ === InternalTaskState.RUNNING ||\n this.state_ === InternalTaskState.PAUSING;\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n return valid;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/task.ts","/**\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\n/**\n * @fileoverview Defines the Firebase Storage Reference class.\n */\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { FbsBlob } from './implementation/blob';\nimport * as errorsExports from './implementation/error';\nimport { errors } from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as metadata from './implementation/metadata';\nimport * as object from './implementation/object';\nimport * as path from './implementation/path';\nimport * as requests from './implementation/requests';\nimport * as fbsString from './implementation/string';\nimport { StringFormat } from './implementation/string';\nimport * as type from './implementation/type';\nimport { Metadata } from './metadata';\nimport { Service } from './service';\nimport { UploadTask } from './task';\n\n/**\n * Provides methods to interact with a bucket in the Firebase Storage service.\n * @param location An fbs.location, or the URL at\n * which to base this object, in one of the following forms:\n * gs:///\n * http[s]://firebasestorage.googleapis.com/\n * /b//o/\n * Any query or fragment strings will be ignored in the http[s]\n * format. If no value is passed, the storage object will use a URL based on\n * the project ID of the base firebase.App instance.\n */\nexport class Reference {\n protected location: Location;\n\n constructor(protected authWrapper: AuthWrapper, location: string | Location) {\n if (location instanceof Location) {\n this.location = location;\n } else {\n this.location = Location.makeFromUrl(location);\n }\n }\n\n /**\n * @return The URL for the bucket and path this object references,\n * in the form gs:///\n * @override\n */\n toString(): string {\n args.validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n }\n\n protected newRef(authWrapper: AuthWrapper, location: Location): Reference {\n return new Reference(authWrapper, location);\n }\n\n protected mappings(): metadata.Mappings {\n return metadata.getMappings();\n }\n\n /**\n * @return A reference to the object obtained by\n * appending childPath, removing any duplicate, beginning, or trailing\n * slashes.\n */\n child(childPath: string): Reference {\n args.validate('child', [args.stringSpec()], arguments);\n let newPath = path.child(this.location.path, childPath);\n let location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n }\n\n /**\n * @return A reference to the parent of the\n * current object, or null if the current object is the root.\n */\n get parent(): Reference | null {\n let newPath = path.parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n let location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n }\n\n /**\n * @return An reference to the root of this\n * object's bucket.\n */\n get root(): Reference {\n let location = new Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n }\n\n get bucket(): string {\n return this.location.bucket;\n }\n\n get fullPath(): string {\n return this.location.path;\n }\n\n get name(): string {\n return path.lastComponent(this.location.path);\n }\n\n get storage(): Service {\n return this.authWrapper.service();\n }\n\n /**\n * Uploads a blob to this object's location.\n * @param data The blob to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n put(\n data: Blob | Uint8Array | ArrayBuffer,\n metadata: Metadata | null = null\n ): UploadTask {\n args.validate(\n 'put',\n [args.uploadDataSpec(), args.metadataSpec(true)],\n arguments\n );\n this.throwIfRoot_('put');\n return new UploadTask(\n this,\n this.authWrapper,\n this.location,\n this.mappings(),\n new FbsBlob(data),\n metadata\n );\n }\n\n /**\n * Uploads a string to this object's location.\n * @param string The string to upload.\n * @param opt_format The format of the string to upload.\n * @return An UploadTask that lets you control and\n * observe the upload.\n */\n putString(\n string: string,\n format: StringFormat = StringFormat.RAW,\n opt_metadata?: Metadata\n ): UploadTask {\n args.validate(\n 'putString',\n [\n args.stringSpec(),\n args.stringSpec(fbsString.formatValidator, true),\n args.metadataSpec(true)\n ],\n arguments\n );\n this.throwIfRoot_('putString');\n let data = fbsString.dataFromString(format, string);\n let metadata = object.clone(opt_metadata);\n if (!type.isDef(metadata['contentType']) && type.isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n return new UploadTask(\n this,\n this.authWrapper,\n this.location,\n this.mappings(),\n new FbsBlob(data.data, true),\n metadata\n );\n }\n\n /**\n * Deletes the object at this location.\n * @return A promise that resolves if the deletion succeeds.\n */\n delete(): Promise {\n args.validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n let self = this;\n return this.authWrapper.getAuthToken().then(function(authToken) {\n let requestInfo = requests.deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * A promise that resolves with the metadata for this object. If this\n * object doesn't exist or metadata cannot be retreived, the promise is\n * rejected.\n */\n getMetadata(): Promise {\n args.validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n let self = this;\n return this.authWrapper.getAuthToken().then(function(authToken) {\n let requestInfo = requests.getMetadata(\n self.authWrapper,\n self.location,\n self.mappings()\n );\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * Updates the metadata for this object.\n * @param metadata The new metadata for the object.\n * Only values that have been explicitly set will be changed. Explicitly\n * setting a value to null will remove the metadata.\n * @return A promise that resolves\n * with the new metadata for this object.\n * @see firebaseStorage.Reference.prototype.getMetadata\n */\n updateMetadata(metadata: Metadata): Promise {\n args.validate('updateMetadata', [args.metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n let self = this;\n return this.authWrapper.getAuthToken().then(function(authToken) {\n let requestInfo = requests.updateMetadata(\n self.authWrapper,\n self.location,\n metadata,\n self.mappings()\n );\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * @return A promise that resolves with the download\n * URL for this object.\n */\n getDownloadURL(): Promise {\n args.validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.getMetadata().then(function(metadata) {\n let url = (metadata['downloadURLs'] as string[])[0];\n if (type.isDef(url)) {\n return url;\n } else {\n throw errorsExports.noDownloadURL();\n }\n });\n }\n\n private throwIfRoot_(name: string) {\n if (this.location.path === '') {\n throw errorsExports.invalidRootOperation(name);\n }\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/reference.ts","/**\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 */\nimport { FirebaseStorageError } from './error';\nimport * as promiseimpl from './promise_external';\nimport * as RequestExports from './request';\nimport { Request } from './request';\n\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nexport class FailRequest implements Request {\n promise_: Promise;\n\n constructor(error: FirebaseStorageError) {\n this.promise_ = promiseimpl.reject(error);\n }\n\n /** @inheritDoc */\n getPromise() {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(appDelete = false) {}\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/failrequest.ts","/**\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 */\nimport * as object from './object';\nimport * as RequestExports from './request';\nimport { Request } from './request';\nimport * as constants from './constants';\n\n/**\n * @struct\n */\nexport class RequestMap {\n private map_: { [key: number]: Request } = {};\n private id_: number;\n\n constructor() {\n this.id_ = constants.minSafeInteger;\n }\n\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n * @param r The request to register.\n */\n addRequest(r: Request) {\n let id = this.id_;\n this.id_++;\n this.map_[id] = r;\n let self = this;\n\n function unmap() {\n delete self.map_[id];\n }\n r.getPromise().then(unmap, unmap);\n }\n\n /**\n * Cancels all registered requests.\n */\n clear() {\n object.forEach(this.map_, (key: string, val: Request) => {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/requestmap.ts","/**\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 */\nimport { Reference } from '../reference';\nimport { Service } from '../service';\nimport * as constants from './constants';\nimport * as errorsExports from './error';\nimport { errors } from './error';\nimport { FailRequest } from './failrequest';\nimport { Location } from './location';\nimport * as promiseimpl from './promise_external';\nimport { Request } from './request';\nimport { RequestInfo } from './requestinfo';\nimport { requestMaker } from './requestmaker';\nimport { RequestMap } from './requestmap';\nimport * as type from './type';\nimport { XhrIoPool } from './xhriopool';\nimport { FirebaseApp, FirebaseAuthTokenData } from '../../app/firebase_app';\n\n/**\n * @param app If null, getAuthToken always resolves with null.\n * @param service The storage service associated with this auth wrapper.\n * Untyped to avoid circular type dependencies.\n * @struct\n */\nexport class AuthWrapper {\n private app_: FirebaseApp | null;\n private bucket_: string | null = null;\n\n /**\n maker\n */\n private storageRefMaker_: (p1: AuthWrapper, p2: Location) => Reference;\n private requestMaker_: requestMaker;\n private pool_: XhrIoPool;\n private service_: Service;\n private maxOperationRetryTime_: number;\n private maxUploadRetryTime_: number;\n private requestMap_: RequestMap;\n private deleted_: boolean = false;\n\n constructor(\n app: FirebaseApp | null,\n maker: (p1: AuthWrapper, p2: Location) => Reference,\n requestMaker: requestMaker,\n service: Service,\n pool: XhrIoPool\n ) {\n this.app_ = app;\n if (this.app_ !== null) {\n let options = this.app_.options;\n if (type.isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = constants.defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = constants.defaultMaxUploadRetryTime;\n this.requestMap_ = new RequestMap();\n }\n\n private static extractBucket_(config: {\n [prop: string]: any;\n }): string | null {\n let bucketString = config[constants.configOption] || null;\n if (bucketString == null) {\n return null;\n }\n let loc: Location = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n }\n\n getAuthToken(): Promise {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (\n this.app_ !== null &&\n type.isDef(this.app_.INTERNAL) &&\n type.isDef(this.app_.INTERNAL.getToken)\n ) {\n return this.app_.INTERNAL.getToken().then(\n function(response: FirebaseAuthTokenData | null): string | null {\n if (response !== null) {\n return response.accessToken;\n } else {\n return null;\n }\n },\n function(_error) {\n return null;\n }\n );\n } else {\n return promiseimpl.resolve(null) as Promise;\n }\n }\n\n bucket(): string | null {\n if (this.deleted_) {\n throw errorsExports.appDeleted();\n } else {\n return this.bucket_;\n }\n }\n\n /**\n * The service associated with this auth wrapper. Untyped to avoid circular\n * type dependencies.\n */\n service(): Service {\n return this.service_;\n }\n\n /**\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\n * at the given Location.\n * @param loc The Location.\n * @return Actually a firebaseStorage.Reference, typing not allowed\n * because of circular dependency problems.\n */\n makeStorageReference(loc: Location): Reference {\n return this.storageRefMaker_(this, loc);\n }\n\n makeRequest(\n requestInfo: RequestInfo,\n authToken: string | null\n ): Request {\n if (!this.deleted_) {\n let request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n } else {\n return new FailRequest(errorsExports.appDeleted());\n }\n }\n\n /**\n * Stop running requests and prevent more from being created.\n */\n deleteApp() {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n }\n\n maxUploadRetryTime(): number {\n return this.maxUploadRetryTime_;\n }\n\n setMaxUploadRetryTime(time: number) {\n this.maxUploadRetryTime_ = time;\n }\n\n maxOperationRetryTime(): number {\n return this.maxOperationRetryTime_;\n }\n\n setMaxOperationRetryTime(time: number) {\n this.maxOperationRetryTime_ = time;\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/implementation/authwrapper.ts","/**\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 */\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { Location } from './implementation/location';\nimport * as fbsPromiseImpl from './implementation/promise_external';\nimport * as RequestExports from './implementation/request';\nimport { Request } from './implementation/request';\nimport { XhrIoPool } from './implementation/xhriopool';\nimport { Reference } from './reference';\nimport { FirebaseApp } from '../app/firebase_app';\n\n/**\n * A service that provides firebaseStorage.Reference instances.\n * @param opt_url gs:// url to a custom Storage Bucket\n *\n * @struct\n */\nexport class Service {\n authWrapper_: AuthWrapper;\n private app_: FirebaseApp;\n private bucket_: Location | null = null;\n private internals_: ServiceInternals;\n\n constructor(app: FirebaseApp, pool: XhrIoPool, url?: string) {\n function maker(authWrapper: AuthWrapper, loc: Location) {\n return new Reference(authWrapper, loc);\n }\n this.authWrapper_ = new AuthWrapper(\n app,\n maker,\n RequestExports.makeRequest,\n this,\n pool\n );\n this.app_ = app;\n if (url != null) {\n this.bucket_ = Location.makeFromBucketSpec(url);\n } else {\n const authWrapperBucket = this.authWrapper_.bucket();\n if (authWrapperBucket != null) {\n this.bucket_ = new Location(authWrapperBucket, '');\n }\n }\n this.internals_ = new ServiceInternals(this);\n }\n\n /**\n * Returns a firebaseStorage.Reference for the given path in the default\n * bucket.\n */\n ref(path?: string): Reference {\n function validator(path: string) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n args.validate('ref', [args.stringSpec(validator, true)], arguments);\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n\n let ref = new Reference(this.authWrapper_, this.bucket_);\n if (path != null) {\n return ref.child(path);\n } else {\n return ref;\n }\n }\n\n /**\n * Returns a firebaseStorage.Reference object for the given absolute URL,\n * which must be a gs:// or http[s]:// URL.\n */\n refFromURL(url: string): Reference {\n function validator(p: string) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n Location.makeFromUrl(p);\n } catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n args.validate('refFromURL', [args.stringSpec(validator, false)], arguments);\n return new Reference(this.authWrapper_, url);\n }\n\n get maxUploadRetryTime(): number {\n return this.authWrapper_.maxUploadRetryTime();\n }\n\n setMaxUploadRetryTime(time: number) {\n args.validate(\n 'setMaxUploadRetryTime',\n [args.nonNegativeNumberSpec()],\n arguments\n );\n this.authWrapper_.setMaxUploadRetryTime(time);\n }\n\n get maxOperationRetryTime(): number {\n return this.authWrapper_.maxOperationRetryTime();\n }\n\n setMaxOperationRetryTime(time: number) {\n args.validate(\n 'setMaxOperationRetryTime',\n [args.nonNegativeNumberSpec()],\n arguments\n );\n this.authWrapper_.setMaxOperationRetryTime(time);\n }\n\n get app(): FirebaseApp {\n return this.app_;\n }\n\n get INTERNAL(): ServiceInternals {\n return this.internals_;\n }\n}\n\n/**\n * @struct\n */\nexport class ServiceInternals {\n service_: Service;\n\n constructor(service: Service) {\n this.service_ = service;\n }\n\n /**\n * Called when the associated app is deleted.\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\n */\n delete(): Promise {\n this.service_.authWrapper_.deleteApp();\n return fbsPromiseImpl.resolve(undefined);\n }\n}\n\n\n\n// WEBPACK FOOTER //\n// ./src/storage/service.ts"]}