UNPKG

6.56 MBSource Map (JSON)View Raw
1{"version":3,"file":"firebase.js","sources":["../../node_modules/whatwg-fetch/fetch.js","../../node_modules/core-js/internals/global.js","../../node_modules/core-js/internals/fails.js","../../node_modules/core-js/internals/is-object.js","../../node_modules/core-js/internals/document-create-element.js","../../node_modules/core-js/internals/an-object.js","../../node_modules/core-js/internals/to-primitive.js","../../node_modules/core-js/internals/create-property-descriptor.js","../../node_modules/core-js/internals/set-global.js","../../node_modules/core-js/internals/has.js","../../node_modules/core-js/internals/uid.js","../../node_modules/core-js/internals/well-known-symbol.js","../../node_modules/core-js/internals/is-pure.js","../../node_modules/core-js/internals/descriptors.js","../../node_modules/core-js/internals/ie8-dom-define.js","../../node_modules/core-js/internals/object-define-property.js","../../node_modules/core-js/internals/create-non-enumerable-property.js","../../node_modules/core-js/internals/shared-store.js","../../node_modules/core-js/internals/shared.js","../../node_modules/core-js/internals/native-symbol.js","../../node_modules/core-js/internals/use-symbol-as-uid.js","../../node_modules/core-js/internals/to-string-tag-support.js","../../node_modules/core-js/internals/inspect-source.js","../../node_modules/core-js/internals/shared-key.js","../../node_modules/core-js/internals/internal-state.js","../../node_modules/core-js/internals/native-weak-map.js","../../node_modules/core-js/internals/hidden-keys.js","../../node_modules/core-js/internals/classof-raw.js","../../node_modules/core-js/internals/redefine.js","../../node_modules/core-js/internals/classof.js","../../node_modules/core-js/internals/object-to-string.js","../../node_modules/core-js/modules/es.object.to-string.js","../../node_modules/core-js/internals/to-integer.js","../../node_modules/core-js/internals/require-object-coercible.js","../../node_modules/core-js/internals/string-multibyte.js","../../node_modules/core-js/internals/to-indexed-object.js","../../node_modules/core-js/internals/get-built-in.js","../../node_modules/core-js/internals/to-length.js","../../node_modules/core-js/internals/array-includes.js","../../node_modules/core-js/internals/to-absolute-index.js","../../node_modules/core-js/internals/object-keys-internal.js","../../node_modules/core-js/internals/copy-constructor-properties.js","../../node_modules/core-js/internals/is-forced.js","../../node_modules/core-js/internals/export.js","../../node_modules/core-js/internals/to-object.js","../../node_modules/core-js/internals/iterators-core.js","../../node_modules/core-js/internals/object-property-is-enumerable.js","../../node_modules/core-js/internals/indexed-object.js","../../node_modules/core-js/internals/object-get-own-property-descriptor.js","../../node_modules/core-js/internals/path.js","../../node_modules/core-js/internals/enum-bug-keys.js","../../node_modules/core-js/internals/object-get-own-property-names.js","../../node_modules/core-js/internals/object-get-own-property-symbols.js","../../node_modules/core-js/internals/own-keys.js","../../node_modules/core-js/internals/correct-prototype-getter.js","../../node_modules/core-js/internals/object-get-prototype-of.js","../../node_modules/core-js/internals/object-create.js","../../node_modules/core-js/internals/object-keys.js","../../node_modules/core-js/internals/object-define-properties.js","../../node_modules/core-js/internals/html.js","../../node_modules/core-js/internals/set-to-string-tag.js","../../node_modules/core-js/internals/create-iterator-constructor.js","../../node_modules/core-js/internals/define-iterator.js","../../node_modules/core-js/internals/iterators.js","../../node_modules/core-js/internals/object-set-prototype-of.js","../../node_modules/core-js/internals/a-possible-prototype.js","../../node_modules/core-js/modules/es.string.iterator.js","../../node_modules/core-js/internals/dom-iterables.js","../../node_modules/core-js/internals/add-to-unscopables.js","../../node_modules/core-js/modules/es.array.iterator.js","../../node_modules/core-js/modules/web.dom-collections.iterator.js","../../node_modules/core-js/internals/redefine-all.js","../../node_modules/core-js/internals/set-species.js","../../node_modules/core-js/internals/a-function.js","../../node_modules/core-js/internals/an-instance.js","../../node_modules/core-js/internals/is-array-iterator-method.js","../../node_modules/core-js/internals/function-bind-context.js","../../node_modules/core-js/internals/get-iterator-method.js","../../node_modules/core-js/internals/call-with-safe-iteration-closing.js","../../node_modules/core-js/internals/native-promise-constructor.js","../../node_modules/core-js/internals/iterate.js","../../node_modules/core-js/internals/check-correctness-of-iteration.js","../../node_modules/core-js/internals/species-constructor.js","../../node_modules/core-js/internals/task.js","../../node_modules/core-js/internals/engine-user-agent.js","../../node_modules/core-js/internals/engine-is-ios.js","../../node_modules/core-js/internals/microtask.js","../../node_modules/core-js/internals/new-promise-capability.js","../../node_modules/core-js/internals/promise-resolve.js","../../node_modules/core-js/internals/perform.js","../../node_modules/core-js/internals/engine-v8-version.js","../../node_modules/core-js/modules/es.promise.js","../../node_modules/core-js/internals/host-report-errors.js","../../node_modules/core-js/modules/es.promise.all-settled.js","../../node_modules/core-js/modules/es.promise.finally.js","../../node_modules/core-js/es/promise/index.js","../../node_modules/core-js/modules/esnext.aggregate-error.js","../../node_modules/core-js/modules/esnext.promise.try.js","../../node_modules/core-js/modules/esnext.promise.any.js","../../node_modules/core-js/internals/array-species-create.js","../../node_modules/core-js/internals/array-iteration.js","../../node_modules/core-js/internals/array-method-uses-to-length.js","../../node_modules/core-js/internals/is-array.js","../../node_modules/core-js/modules/es.array.find.js","../../node_modules/core-js/internals/entry-unbind.js","../../node_modules/core-js/modules/es.array.find-index.js","../../node_modules/core-js/es/array/find.js","../../node_modules/core-js/internals/create-property.js","../../node_modules/core-js/es/array/find-index.js","../../node_modules/core-js/modules/es.array.from.js","../../node_modules/core-js/internals/array-from.js","../../node_modules/core-js/es/array/from.js","../../node_modules/core-js/internals/array-method-is-strict.js","../../node_modules/core-js/modules/es.array.some.js","../../node_modules/core-js/es/array/some.js","../../node_modules/core-js/internals/array-buffer-view-core.js","../../node_modules/core-js/internals/array-buffer-native.js","../../node_modules/core-js/modules/es.typed-array.iterator.js","../../node_modules/core-js/internals/object-assign.js","../../node_modules/core-js/modules/es.object.assign.js","../../node_modules/core-js/es/object/assign.js","../../node_modules/core-js/internals/object-to-array.js","../../node_modules/core-js/modules/es.object.entries.js","../../node_modules/core-js/es/object/entries.js","../../node_modules/core-js/modules/es.object.values.js","../../node_modules/core-js/es/object/values.js","../../node_modules/core-js/internals/not-a-regexp.js","../../node_modules/core-js/internals/is-regexp.js","../../node_modules/core-js/internals/correct-is-regexp-logic.js","../../node_modules/core-js/modules/es.string.includes.js","../../node_modules/core-js/es/string/includes.js","../../node_modules/core-js/modules/es.string.starts-with.js","../../node_modules/core-js/es/string/starts-with.js","../../node_modules/core-js/modules/es.string.repeat.js","../../node_modules/core-js/internals/string-repeat.js","../../node_modules/core-js/es/string/repeat.js","../../node_modules/core-js/modules/es.array.concat.js","../../node_modules/core-js/internals/array-method-has-species-support.js","../../node_modules/core-js/internals/define-well-known-symbol.js","../../node_modules/core-js/modules/es.symbol.js","../../node_modules/core-js/internals/object-get-own-property-names-external.js","../../node_modules/core-js/internals/well-known-symbol-wrapped.js","../../node_modules/core-js/modules/es.symbol.async-iterator.js","../../node_modules/core-js/modules/es.symbol.description.js","../../node_modules/core-js/modules/es.symbol.has-instance.js","../../node_modules/core-js/modules/es.symbol.is-concat-spreadable.js","../../node_modules/core-js/modules/es.symbol.iterator.js","../../node_modules/core-js/modules/es.symbol.match.js","../../node_modules/core-js/modules/es.symbol.match-all.js","../../node_modules/core-js/modules/es.symbol.replace.js","../../node_modules/core-js/modules/es.symbol.search.js","../../node_modules/core-js/modules/es.symbol.species.js","../../node_modules/core-js/modules/es.symbol.split.js","../../node_modules/core-js/modules/es.symbol.to-primitive.js","../../node_modules/core-js/modules/es.symbol.to-string-tag.js","../../node_modules/core-js/modules/es.symbol.unscopables.js","../../node_modules/core-js/modules/es.math.to-string-tag.js","../../node_modules/core-js/modules/es.json.to-string-tag.js","../../node_modules/core-js/es/symbol/index.js","../../node_modules/core-js/modules/esnext.symbol.async-dispose.js","../../node_modules/core-js/modules/esnext.symbol.dispose.js","../../node_modules/core-js/modules/esnext.symbol.observable.js","../../node_modules/core-js/modules/esnext.symbol.pattern-match.js","../../node_modules/core-js/modules/esnext.symbol.replace-all.js","../../node_modules/core-js/es/symbol/iterator.js","../../node_modules/core-js/internals/collection.js","../../node_modules/core-js/internals/inherit-if-required.js","../../node_modules/core-js/internals/collection-from.js","../../node_modules/core-js/internals/freezing.js","../../node_modules/core-js/internals/internal-metadata.js","../../node_modules/core-js/internals/collection-strong.js","../../node_modules/core-js/modules/es.map.js","../../node_modules/core-js/es/map/index.js","../../node_modules/core-js/modules/esnext.map.from.js","../../node_modules/core-js/internals/collection-of.js","../../node_modules/core-js/modules/esnext.map.of.js","../../node_modules/core-js/internals/collection-delete-all.js","../../node_modules/core-js/modules/esnext.map.delete-all.js","../../node_modules/core-js/internals/get-map-iterator.js","../../node_modules/core-js/modules/esnext.map.every.js","../../node_modules/core-js/modules/esnext.map.filter.js","../../node_modules/core-js/modules/esnext.map.find.js","../../node_modules/core-js/modules/esnext.map.find-key.js","../../node_modules/core-js/modules/esnext.map.group-by.js","../../node_modules/core-js/modules/esnext.map.includes.js","../../node_modules/core-js/internals/same-value-zero.js","../../node_modules/core-js/modules/esnext.map.key-by.js","../../node_modules/core-js/modules/esnext.map.key-of.js","../../node_modules/core-js/modules/esnext.map.map-keys.js","../../node_modules/core-js/modules/esnext.map.map-values.js","../../node_modules/core-js/modules/esnext.map.merge.js","../../node_modules/core-js/modules/esnext.map.reduce.js","../../node_modules/core-js/modules/esnext.map.some.js","../../node_modules/core-js/modules/esnext.map.update.js","../../node_modules/core-js/internals/map-upsert.js","../../node_modules/core-js/modules/esnext.map.upsert.js","../../node_modules/core-js/modules/esnext.map.update-or-insert.js","../../node_modules/core-js/modules/es.set.js","../../node_modules/core-js/es/set/index.js","../../node_modules/core-js/modules/esnext.set.from.js","../../node_modules/core-js/modules/esnext.set.of.js","../../node_modules/core-js/modules/esnext.set.add-all.js","../../node_modules/core-js/internals/collection-add-all.js","../../node_modules/core-js/modules/esnext.set.delete-all.js","../../node_modules/core-js/internals/get-set-iterator.js","../../node_modules/core-js/modules/esnext.set.every.js","../../node_modules/core-js/modules/esnext.set.difference.js","../../node_modules/core-js/modules/esnext.set.filter.js","../../node_modules/core-js/modules/esnext.set.find.js","../../node_modules/core-js/modules/esnext.set.intersection.js","../../node_modules/core-js/modules/esnext.set.is-disjoint-from.js","../../node_modules/core-js/modules/esnext.set.is-subset-of.js","../../node_modules/core-js/internals/get-iterator.js","../../node_modules/core-js/modules/esnext.set.is-superset-of.js","../../node_modules/core-js/modules/esnext.set.join.js","../../node_modules/core-js/modules/esnext.set.map.js","../../node_modules/core-js/modules/esnext.set.reduce.js","../../node_modules/core-js/modules/esnext.set.some.js","../../node_modules/core-js/modules/esnext.set.symmetric-difference.js","../../node_modules/core-js/modules/esnext.set.union.js","../../node_modules/core-js/internals/is-integer.js","../../node_modules/core-js/modules/es.number.is-integer.js","../../node_modules/core-js/es/number/is-integer.js","../../node_modules/tslib/tslib.es6.js","../util/src/crypt.ts","../util/src/constants.ts","../util/src/assert.ts","../util/src/deepCopy.ts","../util/src/deferred.ts","../util/src/environment.ts","../util/src/errors.ts","../util/src/json.ts","../util/src/jwt.ts","../util/src/obj.ts","../util/src/sha1.ts","../util/src/subscribe.ts","../util/src/validation.ts","../util/src/utf8.ts","../component/src/component.ts","../component/src/constants.ts","../component/src/provider.ts","../component/src/component_container.ts","../logger/src/logger.ts","../app/src/errors.ts","../app/src/constants.ts","../app/src/logger.ts","../app/src/firebaseApp.ts","../app/src/firebaseNamespaceCore.ts","../app/src/firebaseNamespace.ts","../app/src/platformLoggerService.ts","../app/index.ts","../app/src/registerCoreComponents.ts","app/index.ts","../node_modules/google-closure-library/closure/goog/base.js","../auth/dist/ [synthetic:util/defineproperty] ","../auth/dist/ [synthetic:util/global] ","../auth/dist/ [synthetic:es6/util/makeiterator] ","../auth/dist/ [synthetic:es6/util/arrayiterator] ","../auth/dist/ [synthetic:util/polyfill] ","../auth/dist/ [synthetic:es6/promise/promise] ","../auth/dist/src/error_auth.js","../auth/dist/src/defines.js","../node_modules/google-closure-library/closure/goog/promise/thenable.js","../node_modules/google-closure-library/closure/goog/debug/error.js","../node_modules/google-closure-library/closure/goog/asserts/asserts.js","../node_modules/google-closure-library/closure/goog/async/freelist.js","../node_modules/google-closure-library/closure/goog/async/workqueue.js","../node_modules/google-closure-library/closure/goog/array/array.js","../node_modules/google-closure-library/closure/goog/string/internal.js","../node_modules/google-closure-library/closure/goog/labs/useragent/util.js","../node_modules/google-closure-library/closure/goog/object/object.js","../node_modules/google-closure-library/closure/goog/dom/asserts.js","../node_modules/google-closure-library/closure/goog/string/const.js","../node_modules/google-closure-library/closure/goog/html/trustedresourceurl.js","../node_modules/google-closure-library/closure/goog/html/safeurl.js","../node_modules/google-closure-library/closure/goog/html/safehtml.js","../node_modules/google-closure-library/closure/goog/string/string.js","../node_modules/google-closure-library/closure/goog/reflect/reflect.js","../node_modules/google-closure-library/closure/goog/useragent/useragent.js","../node_modules/google-closure-library/closure/goog/labs/useragent/browser.js","../node_modules/google-closure-library/closure/goog/labs/useragent/engine.js","../node_modules/google-closure-library/closure/goog/dom/browserfeature.js","../node_modules/google-closure-library/closure/goog/dom/dom.js","../node_modules/google-closure-library/closure/goog/async/nexttick.js","../node_modules/google-closure-library/closure/goog/async/run.js","../node_modules/google-closure-library/closure/goog/dom/safe.js","../node_modules/google-closure-library/closure/goog/promise/promise.js","../node_modules/google-closure-library/closure/goog/disposable/disposable.js","../node_modules/google-closure-library/closure/goog/debug/debug.js","../node_modules/google-closure-library/closure/goog/events/browserfeature.js","../node_modules/google-closure-library/closure/goog/events/event.js","../node_modules/google-closure-library/closure/goog/events/browserevent.js","../node_modules/google-closure-library/closure/goog/events/eventtype.js","../node_modules/google-closure-library/closure/goog/events/listenable.js","../node_modules/google-closure-library/closure/goog/events/listener.js","../node_modules/google-closure-library/closure/goog/events/listenermap.js","../node_modules/google-closure-library/closure/goog/events/events.js","../node_modules/google-closure-library/closure/goog/events/eventtarget.js","../node_modules/google-closure-library/closure/goog/timer/timer.js","../node_modules/google-closure-library/closure/goog/structs/structs.js","../node_modules/google-closure-library/closure/goog/structs/map.js","../node_modules/google-closure-library/closure/goog/uri/utils.js","../node_modules/google-closure-library/closure/goog/uri/uri.js","../auth/dist/src/iframeclient/ifchandler.js","../node_modules/google-closure-library/closure/goog/json/json.js","../auth/dist/src/utils.js","../node_modules/google-closure-library/closure/goog/window/window.js","../node_modules/google-closure-library/closure/goog/labs/useragent/platform.js","../auth/dist/src/deprecation.js","../auth/dist/src/object.js","../auth/dist/src/multifactorinfo.js","../auth/dist/src/actioncodeinfo.js","../auth/dist/src/actioncodeurl.js","../auth/dist/src/actioncodesettings.js","../node_modules/google-closure-library/closure/goog/crypt/base64.js","../auth/dist/src/idtoken.js","../auth/dist/src/idp.js","../auth/dist/src/additionaluserinfo.js","../auth/dist/src/dynamiclink.js","../auth/dist/src/multifactorsession.js","../auth/dist/src/authcredential.js","../auth/dist/src/authevent.js","../auth/dist/src/universallinksubscriber.js","../auth/dist/src/rpchandler.js","../node_modules/google-closure-library/closure/goog/net/xmlhttp.js","../auth/dist/src/error_invalidorigin.js","../auth/dist/src/error_withcredential.js","../node_modules/google-closure-library/closure/goog/net/xmlhttpfactory.js","../node_modules/google-closure-library/closure/goog/net/corsxmlhttpfactory.js","../node_modules/google-closure-library/closure/goog/debug/logrecord.js","../node_modules/google-closure-library/closure/goog/debug/logger.js","../node_modules/google-closure-library/closure/goog/net/httpstatus.js","../node_modules/google-closure-library/closure/goog/functions/functions.js","../node_modules/google-closure-library/closure/goog/log/log.js","../node_modules/google-closure-library/closure/goog/net/fetchxmlhttpfactory.js","../node_modules/google-closure-library/closure/goog/net/xhrio.js","../node_modules/google-closure-library/closure/goog/net/eventtype.js","../node_modules/google-closure-library/third_party/closure/goog/mochikit/async/deferred.js","../node_modules/google-closure-library/closure/goog/net/jsloader.js","../node_modules/google-closure-library/closure/goog/net/errorcode.js","../auth/dist/src/iframeclient/iframewrapper.js","../auth/dist/src/storage/asyncstorage.js","../auth/dist/src/storage/storage.js","../auth/dist/src/messagechannel/receiver.js","../auth/dist/src/storage/indexeddb.js","../auth/dist/src/messagechannel/postmessager.js","../auth/dist/src/messagechannel/sender.js","../auth/dist/src/messagechannel/defines.js","../auth/dist/src/storage/hybridindexeddb.js","../auth/dist/src/storage/inmemorystorage.js","../auth/dist/src/storage/localstorage.js","../auth/dist/src/storage/nullstorage.js","../auth/dist/src/storage/sessionstorage.js","../auth/dist/src/storage/factory.js","../auth/dist/src/authstorage.js","../auth/dist/src/storageautheventmanager.js","../node_modules/google-closure-library/closure/goog/crypt/sha2.js","../auth/dist/src/storageoauthhandlermanager.js","../node_modules/google-closure-library/closure/goog/crypt/hash.js","../node_modules/google-closure-library/closure/goog/crypt/sha256.js","../auth/dist/src/cordovahandler.js","../node_modules/google-closure-library/closure/goog/crypt/crypt.js","../auth/dist/src/storagependingredirectmanager.js","../auth/dist/src/autheventmanager.js","../auth/dist/src/authsettings.js","../auth/dist/src/confirmationresult.js","../auth/dist/src/idtokenresult.js","../auth/dist/src/multifactorresolver.js","../auth/dist/src/multifactorerror.js","../auth/dist/src/multifactorassertion.js","../auth/dist/src/userevent.js","../auth/dist/src/multifactoruser.js","../auth/dist/src/proactiverefresh.js","../auth/dist/src/authuser.js","../auth/dist/src/token.js","../auth/dist/src/storageredirectusermanager.js","../auth/dist/src/storageusermanager.js","../auth/dist/src/auth.js","../auth/dist/src/recaptchaverifier/grecaptcha.js","../auth/dist/src/recaptchaverifier/grecaptchamock.js","../auth/dist/src/multifactorgenerator.js","../auth/dist/src/recaptchaverifier/mockloader.js","../auth/dist/src/recaptchaverifier/realloader.js","../auth/dist/src/recaptchaverifier/recaptchaverifier.js","../auth/dist/src/args.js","../auth/dist/src/exports_lib.js","../auth/dist/src/exports_auth.js","../database/src/core/storage/DOMStorageWrapper.ts","../database/src/core/storage/MemoryStorage.ts","../database/src/core/storage/storage.ts","../database/src/core/util/util.ts","../database/src/core/util/Path.ts","../database/src/realtime/Constants.ts","../database/src/core/RepoInfo.ts","../database/src/core/util/libs/parser.ts","../database/src/core/util/validation.ts","../database/src/api/onDisconnect.ts","../database/src/api/TransactionResult.ts","../database/src/core/util/NextPushId.ts","../database/src/core/snap/Node.ts","../database/src/core/snap/indexes/Index.ts","../database/src/core/snap/indexes/KeyIndex.ts","../database/src/core/snap/snap.ts","../database/src/core/snap/LeafNode.ts","../database/src/core/snap/indexes/PriorityIndex.ts","../database/src/core/util/SortedMap.ts","../database/src/core/snap/childSet.ts","../database/src/core/snap/IndexMap.ts","../database/src/core/snap/ChildrenNode.ts","../database/src/core/snap/comparators.ts","../database/src/core/snap/nodeFromJSON.ts","../database/src/core/snap/indexes/ValueIndex.ts","../database/src/core/snap/indexes/PathIndex.ts","../database/src/api/DataSnapshot.ts","../database/src/core/view/Event.ts","../database/src/core/view/EventRegistration.ts","../database/src/api/Query.ts","../database/src/core/SparseSnapshotTree.ts","../database/src/core/util/ServerValues.ts","../database/src/core/operation/Operation.ts","../database/src/core/operation/AckUserWrite.ts","../database/src/core/util/ImmutableTree.ts","../database/src/core/operation/ListenComplete.ts","../database/src/core/operation/Overwrite.ts","../database/src/core/operation/Merge.ts","../database/src/core/view/CacheNode.ts","../database/src/core/view/ViewCache.ts","../database/src/core/view/Change.ts","../database/src/core/view/filter/IndexedFilter.ts","../database/src/core/view/ChildChangeAccumulator.ts","../database/src/core/view/CompleteChildSource.ts","../database/src/core/view/ViewProcessor.ts","../database/src/core/view/EventGenerator.ts","../database/src/core/view/View.ts","../database/src/core/SyncPoint.ts","../database/src/core/CompoundWrite.ts","../database/src/core/WriteTree.ts","../database/src/core/SyncTree.ts","../database/src/core/SnapshotHolder.ts","../database/src/core/AuthTokenProvider.ts","../database/src/core/stats/StatsCollection.ts","../database/src/core/stats/StatsManager.ts","../database/src/core/stats/StatsListener.ts","../database/src/core/stats/StatsReporter.ts","../database/src/core/view/EventQueue.ts","../database/src/core/util/EventEmitter.ts","../database/src/core/util/VisibilityMonitor.ts","../database/src/core/util/OnlineMonitor.ts","../database/src/realtime/polling/PacketReceiver.ts","../database/src/realtime/BrowserPollConnection.ts","../database/src/core/version.ts","../database/src/realtime/WebSocketConnection.ts","../database/src/realtime/TransportManager.ts","../database/src/realtime/Connection.ts","../database/src/core/ServerActions.ts","../database/src/core/PersistentConnection.ts","../database/src/core/ReadonlyRestClient.ts","../util/src/query.ts","../database/src/core/Repo.ts","../database/src/core/view/filter/RangedFilter.ts","../database/src/core/view/filter/LimitedFilter.ts","../database/src/core/view/QueryParams.ts","../database/src/api/Reference.ts","../database/src/core/util/Tree.ts","../database/src/core/Repo_transaction.ts","../database/src/core/RepoManager.ts","../database/src/api/Database.ts","../database/src/api/internal.ts","../database/src/api/test_access.ts","../database/index.ts","../../node_modules/closure-builder/third_party/closure-library/closure/goog/base.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/disposable/disposable.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/array/array.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/string/internal.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/useragent/util.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/object/object.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/reflect/reflect.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/useragent/useragent.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/useragent/browser.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/useragent/engine.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/browserfeature.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/event.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/browserevent.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/eventtype.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/listenable.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/listener.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/listenermap.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/events.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/eventtarget.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/json/json.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/freelist.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/workqueue.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/run.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/nexttick.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/timer/timer.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/async/throttle.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/events/eventhandler.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/webchanneldebug.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/requeststats.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/errorcode.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/eventtype.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/xmlhttpfactory.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/xmlhttp.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/channelrequest.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/environment.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/webchannelbase.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/structs/structs.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/structs/map.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/string/string.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/uri/utils.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/uri/uri.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/basetestchannel.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/connectionstate.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/structs/set.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/wire.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/debug/formatter.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/json/nativejsonprocessor.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/wirev8.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/netutils.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/json/hybrid.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/xhrio.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/httpstatus.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/net/rpc/httpcors.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchannel/webchannelbasetransport.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/string/path.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchanneltransport.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/labs/net/webchanneltransportfactory.js","../../node_modules/closure-builder/third_party/closure-library/closure/goog/functions/functions.js","../webchannel-wrapper/src/index.js","../firestore/src/api/credentials.ts","../firestore/src/core/version.ts","../firestore/src/auth/user.ts","../firestore/src/util/error.ts","../firestore/src/util/api.ts","../firestore/src/util/obj.ts","../firestore/src/util/input_validation.ts","../firestore/src/util/byte_string.ts","../firestore/src/api/blob.ts","../firestore/src/api/geo_point.ts","../firestore/src/api/timestamp.ts","../firestore/src/core/snapshot_version.ts","../firestore/src/model/path.ts","../firestore/src/model/document_key.ts","../firestore/src/util/sorted_map.ts","../firestore/src/util/sorted_set.ts","../firestore/src/model/transform_operation.ts","../firestore/src/model/mutation.ts","../firestore/src/util/misc.ts","../firestore/src/model/field_value.ts","../firestore/src/model/document.ts","../firestore/src/util/types.ts","../firestore/src/core/target.ts","../firestore/src/core/query.ts","../firestore/src/local/target_data.ts","../firestore/src/remote/existence_filter.ts","../firestore/src/remote/rpc_error.ts","../firestore/src/model/collections.ts","../firestore/src/remote/watch_change.ts","../firestore/src/model/document_set.ts","../firestore/src/core/view_snapshot.ts","../firestore/src/remote/remote_event.ts","../firestore/src/remote/serializer.ts","../firestore/src/platform/platform.ts","../firestore/src/util/log.ts","../firestore/src/util/assert.ts","../firestore/src/core/database_info.ts","../firestore/src/util/promise.ts","../firestore/src/model/mutation_batch.ts","../firestore/src/util/obj_map.ts","../firestore/src/local/local_view_changes.ts","../firestore/src/core/listen_sequence.ts","../firestore/src/util/async_queue.ts","../firestore/src/local/persistence_promise.ts","../firestore/src/local/lru_garbage_collector.ts","../firestore/src/local/reference_set.ts","../firestore/src/local/remote_document_change_buffer.ts","../firestore/src/local/local_store.ts","../firestore/src/local/shared_client_state_schema.ts","../firestore/src/local/shared_client_state.ts","../firestore/src/local/persistence.ts","../firestore/src/local/local_documents_view.ts","../firestore/src/local/index_free_query_engine.ts","../firestore/src/local/encoded_resource_path.ts","../firestore/src/local/memory_index_manager.ts","../firestore/src/local/memory_mutation_queue.ts","../firestore/src/local/memory_remote_document_cache.ts","../firestore/src/core/target_id_generator.ts","../firestore/src/local/memory_target_cache.ts","../firestore/src/local/memory_persistence.ts","../firestore/src/remote/backoff.ts","../firestore/src/remote/persistent_stream.ts","../firestore/src/remote/datastore.ts","../firestore/src/api/field_path.ts","../firestore/src/api/field_value.ts","../firestore/src/api/user_data_converter.ts","../firestore/src/core/view.ts","../firestore/src/core/transaction.ts","../firestore/src/remote/online_state_tracker.ts","../firestore/src/remote/remote_store.ts","../firestore/src/core/sync_engine.ts","../firestore/src/core/event_manager.ts","../firestore/src/core/transaction_runner.ts","../firestore/src/core/firestore_client.ts","../firestore/src/util/async_observer.ts","../firestore/src/api/observer.ts","../firestore/src/api/database.ts","../firestore/src/local/simple_db.ts","../firestore/src/local/indexeddb_mutation_queue.ts","../firestore/src/local/indexeddb_target_cache.ts","../firestore/src/local/indexeddb_remote_document_cache.ts","../firestore/src/local/indexeddb_schema.ts","../firestore/src/local/indexeddb_index_manager.ts","../firestore/src/local/local_serializer.ts","../firestore/src/local/indexeddb_persistence.ts","../firestore/src/platform/config.ts","../firestore/index.ts","../firestore/src/remote/connectivity_monitor_noop.ts","../firestore/src/platform_browser/browser_connectivity_monitor.ts","../firestore/src/remote/stream_bridge.ts","../firestore/src/platform_browser/webchannel_connection.ts","../firestore/src/platform_browser/browser_platform.ts","../firestore/src/platform_browser/browser_init.ts","../functions/src/api/error.ts","../functions/src/context.ts","../functions/src/serializer.ts","../functions/src/api/service.ts","../functions/src/config.ts","../../node_modules/idb/lib/idb.mjs","../functions/index.ts","../installations/src/util/constants.ts","../installations/src/util/errors.ts","../installations/src/api/common.ts","../installations/src/util/sleep.ts","../installations/src/helpers/generate-fid.ts","../installations/src/helpers/buffer-to-base64-url-safe.ts","../installations/src/util/get-key.ts","../installations/src/helpers/fid-changed.ts","../installations/src/helpers/idb-manager.ts","../installations/src/index.ts","../installations/src/helpers/get-installation-entry.ts","../installations/src/api/create-installation-request.ts","../installations/src/api/generate-auth-token-request.ts","../installations/src/helpers/refresh-auth-token.ts","../installations/src/functions/get-token.ts","../installations/src/api/delete-installation-request.ts","../installations/src/functions/on-id-change.ts","../installations/src/helpers/extract-app-config.ts","../installations/src/functions/get-id.ts","../installations/src/functions/delete-installation.ts","../messaging/src/util/errors.ts","../messaging/src/helpers/extract-app-config.ts","../messaging/src/helpers/array-to-base64.ts","../messaging/src/helpers/migrate-old-database.ts","../messaging/src/helpers/idb-manager.ts","../messaging/src/util/constants.ts","../messaging/src/core/api.ts","../messaging/src/core/token-management.ts","../messaging/src/interfaces/internal-message.ts","../messaging/src/helpers/is-console-message.ts","../messaging/src/controllers/window-controller.ts","../messaging/src/controllers/sw-controller.ts","../messaging/src/helpers/sleep.ts","../messaging/src/index.ts","../storage/src/implementation/constants.ts","../storage/src/implementation/error.ts","../storage/src/implementation/string.ts","../storage/src/implementation/taskenums.ts","../storage/src/implementation/xhrio.ts","../storage/src/implementation/type.ts","../storage/src/implementation/xhrio_network.ts","../storage/src/implementation/xhriopool.ts","../storage/src/implementation/fs.ts","../storage/src/implementation/blob.ts","../storage/src/implementation/location.ts","../storage/src/implementation/json.ts","../storage/src/implementation/path.ts","../storage/src/implementation/url.ts","../storage/src/implementation/metadata.ts","../storage/src/implementation/list.ts","../storage/src/implementation/requestinfo.ts","../storage/src/implementation/requests.ts","../storage/src/implementation/observer.ts","../storage/src/tasksnapshot.ts","../storage/src/implementation/args.ts","../storage/src/implementation/async.ts","../storage/src/task.ts","../storage/src/reference.ts","../storage/src/implementation/failrequest.ts","../storage/src/implementation/requestmap.ts","../storage/src/implementation/authwrapper.ts","../storage/src/implementation/request.ts","../storage/src/implementation/backoff.ts","../storage/src/service.ts","../storage/index.ts","../performance/src/services/api_service.ts","../performance/src/services/settings_service.ts","../performance/src/constants.ts","../performance/src/utils/errors.ts","../performance/src/services/iid_service.ts","../performance/src/utils/attributes_utils.ts","../performance/src/utils/console_logger.ts","../performance/src/services/remote_config_service.ts","../performance/src/services/initialization_service.ts","../performance/src/services/transport_service.ts","../performance/src/services/perf_logger.ts","../performance/src/utils/metric_utils.ts","../performance/src/resources/trace.ts","../performance/src/resources/network_request.ts","../performance/src/services/oob_resources_service.ts","../performance/src/controllers/perf.ts","../performance/index.ts","../analytics/src/constants.ts","../analytics/src/logger.ts","../analytics/src/helpers.ts","../analytics/src/errors.ts","../analytics/src/factory.ts","../analytics/src/functions.ts","../analytics/index.ts","../remote-config/src/client/caching_client.ts","../remote-config/src/errors.ts","../remote-config/src/client/rest_client.ts","../remote-config/src/language.ts","../remote-config/src/client/remote_config_fetch_client.ts","../remote-config/src/value.ts","../remote-config/src/remote_config.ts","../remote-config/src/storage/storage.ts","../remote-config/src/storage/storage_cache.ts","../remote-config/src/client/retrying_client.ts","../remote-config/src/client/exponential_backoff.ts","../remote-config/index.ts","src/index.cdn.ts"],"sourcesContent":["(function(self) {\n 'use strict';\n\n if (self.fetch) {\n return\n }\n\n var support = {\n searchParams: 'URLSearchParams' in self,\n iterable: 'Symbol' in self && 'iterator' in Symbol,\n blob: 'FileReader' in self && 'Blob' in self && (function() {\n try {\n new Blob()\n return true\n } catch(e) {\n return false\n }\n })(),\n formData: 'FormData' in self,\n arrayBuffer: 'ArrayBuffer' in self\n }\n\n if (support.arrayBuffer) {\n var viewClasses = [\n '[object Int8Array]',\n '[object Uint8Array]',\n '[object Uint8ClampedArray]',\n '[object Int16Array]',\n '[object Uint16Array]',\n '[object Int32Array]',\n '[object Uint32Array]',\n '[object Float32Array]',\n '[object Float64Array]'\n ]\n\n var isDataView = function(obj) {\n return obj && DataView.prototype.isPrototypeOf(obj)\n }\n\n var isArrayBufferView = ArrayBuffer.isView || function(obj) {\n return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1\n }\n }\n\n function normalizeName(name) {\n if (typeof name !== 'string') {\n name = String(name)\n }\n if (/[^a-z0-9\\-#$%&'*+.\\^_`|~]/i.test(name)) {\n throw new TypeError('Invalid character in header field name')\n }\n return name.toLowerCase()\n }\n\n function normalizeValue(value) {\n if (typeof value !== 'string') {\n value = String(value)\n }\n return value\n }\n\n // Build a destructive iterator for the value list\n function iteratorFor(items) {\n var iterator = {\n next: function() {\n var value = items.shift()\n return {done: value === undefined, value: value}\n }\n }\n\n if (support.iterable) {\n iterator[Symbol.iterator] = function() {\n return iterator\n }\n }\n\n return iterator\n }\n\n function Headers(headers) {\n this.map = {}\n\n if (headers instanceof Headers) {\n headers.forEach(function(value, name) {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(headers)) {\n headers.forEach(function(header) {\n this.append(header[0], header[1])\n }, this)\n } else if (headers) {\n Object.getOwnPropertyNames(headers).forEach(function(name) {\n this.append(name, headers[name])\n }, this)\n }\n }\n\n Headers.prototype.append = function(name, value) {\n name = normalizeName(name)\n value = normalizeValue(value)\n var oldValue = this.map[name]\n this.map[name] = oldValue ? oldValue+','+value : value\n }\n\n Headers.prototype['delete'] = function(name) {\n delete this.map[normalizeName(name)]\n }\n\n Headers.prototype.get = function(name) {\n name = normalizeName(name)\n return this.has(name) ? this.map[name] : null\n }\n\n Headers.prototype.has = function(name) {\n return this.map.hasOwnProperty(normalizeName(name))\n }\n\n Headers.prototype.set = function(name, value) {\n this.map[normalizeName(name)] = normalizeValue(value)\n }\n\n Headers.prototype.forEach = function(callback, thisArg) {\n for (var name in this.map) {\n if (this.map.hasOwnProperty(name)) {\n callback.call(thisArg, this.map[name], name, this)\n }\n }\n }\n\n Headers.prototype.keys = function() {\n var items = []\n this.forEach(function(value, name) { items.push(name) })\n return iteratorFor(items)\n }\n\n Headers.prototype.values = function() {\n var items = []\n this.forEach(function(value) { items.push(value) })\n return iteratorFor(items)\n }\n\n Headers.prototype.entries = function() {\n var items = []\n this.forEach(function(value, name) { items.push([name, value]) })\n return iteratorFor(items)\n }\n\n if (support.iterable) {\n Headers.prototype[Symbol.iterator] = Headers.prototype.entries\n }\n\n function consumed(body) {\n if (body.bodyUsed) {\n return Promise.reject(new TypeError('Already read'))\n }\n body.bodyUsed = true\n }\n\n function fileReaderReady(reader) {\n return new Promise(function(resolve, reject) {\n reader.onload = function() {\n resolve(reader.result)\n }\n reader.onerror = function() {\n reject(reader.error)\n }\n })\n }\n\n function readBlobAsArrayBuffer(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsArrayBuffer(blob)\n return promise\n }\n\n function readBlobAsText(blob) {\n var reader = new FileReader()\n var promise = fileReaderReady(reader)\n reader.readAsText(blob)\n return promise\n }\n\n function readArrayBufferAsText(buf) {\n var view = new Uint8Array(buf)\n var chars = new Array(view.length)\n\n for (var i = 0; i < view.length; i++) {\n chars[i] = String.fromCharCode(view[i])\n }\n return chars.join('')\n }\n\n function bufferClone(buf) {\n if (buf.slice) {\n return buf.slice(0)\n } else {\n var view = new Uint8Array(buf.byteLength)\n view.set(new Uint8Array(buf))\n return view.buffer\n }\n }\n\n function Body() {\n this.bodyUsed = false\n\n this._initBody = function(body) {\n this._bodyInit = body\n if (!body) {\n this._bodyText = ''\n } else if (typeof body === 'string') {\n this._bodyText = body\n } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {\n this._bodyBlob = body\n } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {\n this._bodyFormData = body\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this._bodyText = body.toString()\n } else if (support.arrayBuffer && support.blob && isDataView(body)) {\n this._bodyArrayBuffer = bufferClone(body.buffer)\n // IE 10-11 can't handle a DataView body.\n this._bodyInit = new Blob([this._bodyArrayBuffer])\n } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {\n this._bodyArrayBuffer = bufferClone(body)\n } else {\n throw new Error('unsupported BodyInit type')\n }\n\n if (!this.headers.get('content-type')) {\n if (typeof body === 'string') {\n this.headers.set('content-type', 'text/plain;charset=UTF-8')\n } else if (this._bodyBlob && this._bodyBlob.type) {\n this.headers.set('content-type', this._bodyBlob.type)\n } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {\n this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8')\n }\n }\n }\n\n if (support.blob) {\n this.blob = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return Promise.resolve(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(new Blob([this._bodyArrayBuffer]))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as blob')\n } else {\n return Promise.resolve(new Blob([this._bodyText]))\n }\n }\n\n this.arrayBuffer = function() {\n if (this._bodyArrayBuffer) {\n return consumed(this) || Promise.resolve(this._bodyArrayBuffer)\n } else {\n return this.blob().then(readBlobAsArrayBuffer)\n }\n }\n }\n\n this.text = function() {\n var rejected = consumed(this)\n if (rejected) {\n return rejected\n }\n\n if (this._bodyBlob) {\n return readBlobAsText(this._bodyBlob)\n } else if (this._bodyArrayBuffer) {\n return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer))\n } else if (this._bodyFormData) {\n throw new Error('could not read FormData body as text')\n } else {\n return Promise.resolve(this._bodyText)\n }\n }\n\n if (support.formData) {\n this.formData = function() {\n return this.text().then(decode)\n }\n }\n\n this.json = function() {\n return this.text().then(JSON.parse)\n }\n\n return this\n }\n\n // HTTP methods whose capitalization should be normalized\n var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']\n\n function normalizeMethod(method) {\n var upcased = method.toUpperCase()\n return (methods.indexOf(upcased) > -1) ? upcased : method\n }\n\n function Request(input, options) {\n options = options || {}\n var body = options.body\n\n if (input instanceof Request) {\n if (input.bodyUsed) {\n throw new TypeError('Already read')\n }\n this.url = input.url\n this.credentials = input.credentials\n if (!options.headers) {\n this.headers = new Headers(input.headers)\n }\n this.method = input.method\n this.mode = input.mode\n if (!body && input._bodyInit != null) {\n body = input._bodyInit\n input.bodyUsed = true\n }\n } else {\n this.url = String(input)\n }\n\n this.credentials = options.credentials || this.credentials || 'omit'\n if (options.headers || !this.headers) {\n this.headers = new Headers(options.headers)\n }\n this.method = normalizeMethod(options.method || this.method || 'GET')\n this.mode = options.mode || this.mode || null\n this.referrer = null\n\n if ((this.method === 'GET' || this.method === 'HEAD') && body) {\n throw new TypeError('Body not allowed for GET or HEAD requests')\n }\n this._initBody(body)\n }\n\n Request.prototype.clone = function() {\n return new Request(this, { body: this._bodyInit })\n }\n\n function decode(body) {\n var form = new FormData()\n body.trim().split('&').forEach(function(bytes) {\n if (bytes) {\n var split = bytes.split('=')\n var name = split.shift().replace(/\\+/g, ' ')\n var value = split.join('=').replace(/\\+/g, ' ')\n form.append(decodeURIComponent(name), decodeURIComponent(value))\n }\n })\n return form\n }\n\n function parseHeaders(rawHeaders) {\n var headers = new Headers()\n // Replace instances of \\r\\n and \\n followed by at least one space or horizontal tab with a space\n // https://tools.ietf.org/html/rfc7230#section-3.2\n var preProcessedHeaders = rawHeaders.replace(/\\r?\\n[\\t ]+/g, ' ')\n preProcessedHeaders.split(/\\r?\\n/).forEach(function(line) {\n var parts = line.split(':')\n var key = parts.shift().trim()\n if (key) {\n var value = parts.join(':').trim()\n headers.append(key, value)\n }\n })\n return headers\n }\n\n Body.call(Request.prototype)\n\n function Response(bodyInit, options) {\n if (!options) {\n options = {}\n }\n\n this.type = 'default'\n this.status = options.status === undefined ? 200 : options.status\n this.ok = this.status >= 200 && this.status < 300\n this.statusText = 'statusText' in options ? options.statusText : 'OK'\n this.headers = new Headers(options.headers)\n this.url = options.url || ''\n this._initBody(bodyInit)\n }\n\n Body.call(Response.prototype)\n\n Response.prototype.clone = function() {\n return new Response(this._bodyInit, {\n status: this.status,\n statusText: this.statusText,\n headers: new Headers(this.headers),\n url: this.url\n })\n }\n\n Response.error = function() {\n var response = new Response(null, {status: 0, statusText: ''})\n response.type = 'error'\n return response\n }\n\n var redirectStatuses = [301, 302, 303, 307, 308]\n\n Response.redirect = function(url, status) {\n if (redirectStatuses.indexOf(status) === -1) {\n throw new RangeError('Invalid status code')\n }\n\n return new Response(null, {status: status, headers: {location: url}})\n }\n\n self.Headers = Headers\n self.Request = Request\n self.Response = Response\n\n self.fetch = function(input, init) {\n return new Promise(function(resolve, reject) {\n var request = new Request(input, init)\n var xhr = new XMLHttpRequest()\n\n xhr.onload = function() {\n var options = {\n status: xhr.status,\n statusText: xhr.statusText,\n headers: parseHeaders(xhr.getAllResponseHeaders() || '')\n }\n options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL')\n var body = 'response' in xhr ? xhr.response : xhr.responseText\n resolve(new Response(body, options))\n }\n\n xhr.onerror = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.ontimeout = function() {\n reject(new TypeError('Network request failed'))\n }\n\n xhr.open(request.method, request.url, true)\n\n if (request.credentials === 'include') {\n xhr.withCredentials = true\n } else if (request.credentials === 'omit') {\n xhr.withCredentials = false\n }\n\n if ('responseType' in xhr && support.blob) {\n xhr.responseType = 'blob'\n }\n\n request.headers.forEach(function(value, name) {\n xhr.setRequestHeader(name, value)\n })\n\n xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)\n })\n }\n self.fetch.polyfill = true\n})(typeof self !== 'undefined' ? self : this);\n","var check = function (it) {\n return it && it.Math == Math && it;\n};\n\n// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nmodule.exports =\n // eslint-disable-next-line no-undef\n check(typeof globalThis == 'object' && globalThis) ||\n check(typeof window == 'object' && window) ||\n check(typeof self == 'object' && self) ||\n check(typeof global == 'object' && global) ||\n // eslint-disable-next-line no-new-func\n Function('return this')();\n","module.exports = function (exec) {\n try {\n return !!exec();\n } catch (error) {\n return true;\n }\n};\n","module.exports = function (it) {\n return typeof it === 'object' ? it !== null : typeof it === 'function';\n};\n","var global = require('../internals/global');\nvar isObject = require('../internals/is-object');\n\nvar document = global.document;\n// typeof document.createElement is 'object' in old IE\nvar EXISTS = isObject(document) && isObject(document.createElement);\n\nmodule.exports = function (it) {\n return EXISTS ? document.createElement(it) : {};\n};\n","var isObject = require('../internals/is-object');\n\nmodule.exports = function (it) {\n if (!isObject(it)) {\n throw TypeError(String(it) + ' is not an object');\n } return it;\n};\n","var isObject = require('../internals/is-object');\n\n// `ToPrimitive` abstract operation\n// https://tc39.github.io/ecma262/#sec-toprimitive\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (input, PREFERRED_STRING) {\n if (!isObject(input)) return input;\n var fn, val;\n if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;\n if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","var global = require('../internals/global');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\n\nmodule.exports = function (key, value) {\n try {\n createNonEnumerableProperty(global, key, value);\n } catch (error) {\n global[key] = value;\n } return value;\n};\n","var hasOwnProperty = {}.hasOwnProperty;\n\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n","var id = 0;\nvar postfix = Math.random();\n\nmodule.exports = function (key) {\n return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);\n};\n","var global = require('../internals/global');\nvar shared = require('../internals/shared');\nvar has = require('../internals/has');\nvar uid = require('../internals/uid');\nvar NATIVE_SYMBOL = require('../internals/native-symbol');\nvar USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid');\n\nvar WellKnownSymbolsStore = shared('wks');\nvar Symbol = global.Symbol;\nvar createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;\n\nmodule.exports = function (name) {\n if (!has(WellKnownSymbolsStore, name)) {\n if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name];\n else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);\n } return WellKnownSymbolsStore[name];\n};\n","module.exports = false;\n","var fails = require('../internals/fails');\n\n// Thank's IE8 for his funny defineProperty\nmodule.exports = !fails(function () {\n return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;\n});\n","var DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar createElement = require('../internals/document-create-element');\n\n// Thank's IE8 for his funny defineProperty\nmodule.exports = !DESCRIPTORS && !fails(function () {\n return Object.defineProperty(createElement('div'), 'a', {\n get: function () { return 7; }\n }).a != 7;\n});\n","var DESCRIPTORS = require('../internals/descriptors');\nvar IE8_DOM_DEFINE = require('../internals/ie8-dom-define');\nvar anObject = require('../internals/an-object');\nvar toPrimitive = require('../internals/to-primitive');\n\nvar nativeDefineProperty = Object.defineProperty;\n\n// `Object.defineProperty` method\n// https://tc39.github.io/ecma262/#sec-object.defineproperty\nexports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPrimitive(P, true);\n anObject(Attributes);\n if (IE8_DOM_DEFINE) try {\n return nativeDefineProperty(O, P, Attributes);\n } catch (error) { /* empty */ }\n if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');\n if ('value' in Attributes) O[P] = Attributes.value;\n return O;\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar definePropertyModule = require('../internals/object-define-property');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\n\nmodule.exports = DESCRIPTORS ? function (object, key, value) {\n return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n","var global = require('../internals/global');\nvar setGlobal = require('../internals/set-global');\n\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || setGlobal(SHARED, {});\n\nmodule.exports = store;\n","var IS_PURE = require('../internals/is-pure');\nvar store = require('../internals/shared-store');\n\n(module.exports = function (key, value) {\n return store[key] || (store[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: '3.6.4',\n mode: IS_PURE ? 'pure' : 'global',\n copyright: '© 2020 Denis Pushkarev (zloirock.ru)'\n});\n","var fails = require('../internals/fails');\n\nmodule.exports = !!Object.getOwnPropertySymbols && !fails(function () {\n // Chrome 38 Symbol has incorrect toString conversion\n // eslint-disable-next-line no-undef\n return !String(Symbol());\n});\n","var NATIVE_SYMBOL = require('../internals/native-symbol');\n\nmodule.exports = NATIVE_SYMBOL\n // eslint-disable-next-line no-undef\n && !Symbol.sham\n // eslint-disable-next-line no-undef\n && typeof Symbol.iterator == 'symbol';\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar test = {};\n\ntest[TO_STRING_TAG] = 'z';\n\nmodule.exports = String(test) === '[object z]';\n","var store = require('../internals/shared-store');\n\nvar functionToString = Function.toString;\n\n// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper\nif (typeof store.inspectSource != 'function') {\n store.inspectSource = function (it) {\n return functionToString.call(it);\n };\n}\n\nmodule.exports = store.inspectSource;\n","var shared = require('../internals/shared');\nvar uid = require('../internals/uid');\n\nvar keys = shared('keys');\n\nmodule.exports = function (key) {\n return keys[key] || (keys[key] = uid(key));\n};\n","var NATIVE_WEAK_MAP = require('../internals/native-weak-map');\nvar global = require('../internals/global');\nvar isObject = require('../internals/is-object');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar objectHas = require('../internals/has');\nvar sharedKey = require('../internals/shared-key');\nvar hiddenKeys = require('../internals/hidden-keys');\n\nvar WeakMap = global.WeakMap;\nvar set, get, has;\n\nvar enforce = function (it) {\n return has(it) ? get(it) : set(it, {});\n};\n\nvar getterFor = function (TYPE) {\n return function (it) {\n var state;\n if (!isObject(it) || (state = get(it)).type !== TYPE) {\n throw TypeError('Incompatible receiver, ' + TYPE + ' required');\n } return state;\n };\n};\n\nif (NATIVE_WEAK_MAP) {\n var store = new WeakMap();\n var wmget = store.get;\n var wmhas = store.has;\n var wmset = store.set;\n set = function (it, metadata) {\n wmset.call(store, it, metadata);\n return metadata;\n };\n get = function (it) {\n return wmget.call(store, it) || {};\n };\n has = function (it) {\n return wmhas.call(store, it);\n };\n} else {\n var STATE = sharedKey('state');\n hiddenKeys[STATE] = true;\n set = function (it, metadata) {\n createNonEnumerableProperty(it, STATE, metadata);\n return metadata;\n };\n get = function (it) {\n return objectHas(it, STATE) ? it[STATE] : {};\n };\n has = function (it) {\n return objectHas(it, STATE);\n };\n}\n\nmodule.exports = {\n set: set,\n get: get,\n has: has,\n enforce: enforce,\n getterFor: getterFor\n};\n","var global = require('../internals/global');\nvar inspectSource = require('../internals/inspect-source');\n\nvar WeakMap = global.WeakMap;\n\nmodule.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));\n","module.exports = {};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","var global = require('../internals/global');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar has = require('../internals/has');\nvar setGlobal = require('../internals/set-global');\nvar inspectSource = require('../internals/inspect-source');\nvar InternalStateModule = require('../internals/internal-state');\n\nvar getInternalState = InternalStateModule.get;\nvar enforceInternalState = InternalStateModule.enforce;\nvar TEMPLATE = String(String).split('String');\n\n(module.exports = function (O, key, value, options) {\n var unsafe = options ? !!options.unsafe : false;\n var simple = options ? !!options.enumerable : false;\n var noTargetGet = options ? !!options.noTargetGet : false;\n if (typeof value == 'function') {\n if (typeof key == 'string' && !has(value, 'name')) createNonEnumerableProperty(value, 'name', key);\n enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');\n }\n if (O === global) {\n if (simple) O[key] = value;\n else setGlobal(key, value);\n return;\n } else if (!unsafe) {\n delete O[key];\n } else if (!noTargetGet && O[key]) {\n simple = true;\n }\n if (simple) O[key] = value;\n else createNonEnumerableProperty(O, key, value);\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, 'toString', function toString() {\n return typeof this == 'function' && getInternalState(this).source || inspectSource(this);\n});\n","var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar classofRaw = require('../internals/classof-raw');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\n// ES3 wrong here\nvar CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (error) { /* empty */ }\n};\n\n// getting tag from ES6+ `Object.prototype.toString`\nmodule.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {\n var O, tag, result;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag\n // builtinTag case\n : CORRECT_ARGUMENTS ? classofRaw(O)\n // ES3 arguments fallback\n : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;\n};\n","'use strict';\nvar TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar classof = require('../internals/classof');\n\n// `Object.prototype.toString` method implementation\n// https://tc39.github.io/ecma262/#sec-object.prototype.tostring\nmodule.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() {\n return '[object ' + classof(this) + ']';\n};\n","var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar redefine = require('../internals/redefine');\nvar toString = require('../internals/object-to-string');\n\n// `Object.prototype.toString` method\n// https://tc39.github.io/ecma262/#sec-object.prototype.tostring\nif (!TO_STRING_TAG_SUPPORT) {\n redefine(Object.prototype, 'toString', toString, { unsafe: true });\n}\n","var ceil = Math.ceil;\nvar floor = Math.floor;\n\n// `ToInteger` abstract operation\n// https://tc39.github.io/ecma262/#sec-tointeger\nmodule.exports = function (argument) {\n return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);\n};\n","// `RequireObjectCoercible` abstract operation\n// https://tc39.github.io/ecma262/#sec-requireobjectcoercible\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","var toInteger = require('../internals/to-integer');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `String.prototype.{ codePointAt, at }` methods implementation\nvar createMethod = function (CONVERT_TO_STRING) {\n return function ($this, pos) {\n var S = String(requireObjectCoercible($this));\n var position = toInteger(pos);\n var size = S.length;\n var first, second;\n if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;\n first = S.charCodeAt(position);\n return first < 0xD800 || first > 0xDBFF || position + 1 === size\n || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF\n ? CONVERT_TO_STRING ? S.charAt(position) : first\n : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;\n };\n};\n\nmodule.exports = {\n // `String.prototype.codePointAt` method\n // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat\n codeAt: createMethod(false),\n // `String.prototype.at` method\n // https://github.com/mathiasbynens/String.prototype.at\n charAt: createMethod(true)\n};\n","// toObject with fallback for non-array-like ES3 strings\nvar IndexedObject = require('../internals/indexed-object');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\nmodule.exports = function (it) {\n return IndexedObject(requireObjectCoercible(it));\n};\n","var path = require('../internals/path');\nvar global = require('../internals/global');\n\nvar aFunction = function (variable) {\n return typeof variable == 'function' ? variable : undefined;\n};\n\nmodule.exports = function (namespace, method) {\n return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])\n : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];\n};\n","var toInteger = require('../internals/to-integer');\n\nvar min = Math.min;\n\n// `ToLength` abstract operation\n// https://tc39.github.io/ecma262/#sec-tolength\nmodule.exports = function (argument) {\n return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991\n};\n","var toIndexedObject = require('../internals/to-indexed-object');\nvar toLength = require('../internals/to-length');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\n\n// `Array.prototype.{ indexOf, includes }` methods implementation\nvar createMethod = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIndexedObject($this);\n var length = toLength(O.length);\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare\n if (IS_INCLUDES && el != el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare\n if (value != value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) {\n if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.includes` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.includes\n includes: createMethod(true),\n // `Array.prototype.indexOf` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.indexof\n indexOf: createMethod(false)\n};\n","var toInteger = require('../internals/to-integer');\n\nvar max = Math.max;\nvar min = Math.min;\n\n// Helper for a popular repeating case of the spec:\n// Let integer be ? ToInteger(index).\n// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).\nmodule.exports = function (index, length) {\n var integer = toInteger(index);\n return integer < 0 ? max(integer + length, 0) : min(integer, length);\n};\n","var has = require('../internals/has');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar indexOf = require('../internals/array-includes').indexOf;\nvar hiddenKeys = require('../internals/hidden-keys');\n\nmodule.exports = function (object, names) {\n var O = toIndexedObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has(O, key = names[i++])) {\n ~indexOf(result, key) || result.push(key);\n }\n return result;\n};\n","var has = require('../internals/has');\nvar ownKeys = require('../internals/own-keys');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar definePropertyModule = require('../internals/object-define-property');\n\nmodule.exports = function (target, source) {\n var keys = ownKeys(source);\n var defineProperty = definePropertyModule.f;\n var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));\n }\n};\n","var fails = require('../internals/fails');\n\nvar replacement = /#|\\.prototype\\./;\n\nvar isForced = function (feature, detection) {\n var value = data[normalize(feature)];\n return value == POLYFILL ? true\n : value == NATIVE ? false\n : typeof detection == 'function' ? fails(detection)\n : !!detection;\n};\n\nvar normalize = isForced.normalize = function (string) {\n return String(string).replace(replacement, '.').toLowerCase();\n};\n\nvar data = isForced.data = {};\nvar NATIVE = isForced.NATIVE = 'N';\nvar POLYFILL = isForced.POLYFILL = 'P';\n\nmodule.exports = isForced;\n","var global = require('../internals/global');\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar setGlobal = require('../internals/set-global');\nvar copyConstructorProperties = require('../internals/copy-constructor-properties');\nvar isForced = require('../internals/is-forced');\n\n/*\n options.target - name of the target object\n options.global - target is the global object\n options.stat - export as static methods of target\n options.proto - export as prototype methods of target\n options.real - real prototype method for the `pure` version\n options.forced - export even if the native feature is available\n options.bind - bind methods to the target, required for the `pure` version\n options.wrap - wrap constructors to preventing global pollution, required for the `pure` version\n options.unsafe - use the simple assignment of property instead of delete + defineProperty\n options.sham - add a flag to not completely full polyfills\n options.enumerable - export as enumerable property\n options.noTargetGet - prevent calling a getter on target\n*/\nmodule.exports = function (options, source) {\n var TARGET = options.target;\n var GLOBAL = options.global;\n var STATIC = options.stat;\n var FORCED, target, key, targetProperty, sourceProperty, descriptor;\n if (GLOBAL) {\n target = global;\n } else if (STATIC) {\n target = global[TARGET] || setGlobal(TARGET, {});\n } else {\n target = (global[TARGET] || {}).prototype;\n }\n if (target) for (key in source) {\n sourceProperty = source[key];\n if (options.noTargetGet) {\n descriptor = getOwnPropertyDescriptor(target, key);\n targetProperty = descriptor && descriptor.value;\n } else targetProperty = target[key];\n FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);\n // contained in target\n if (!FORCED && targetProperty !== undefined) {\n if (typeof sourceProperty === typeof targetProperty) continue;\n copyConstructorProperties(sourceProperty, targetProperty);\n }\n // add a flag to not completely full polyfills\n if (options.sham || (targetProperty && targetProperty.sham)) {\n createNonEnumerableProperty(sourceProperty, 'sham', true);\n }\n // extend global\n redefine(target, key, sourceProperty, options);\n }\n};\n","var requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `ToObject` abstract operation\n// https://tc39.github.io/ecma262/#sec-toobject\nmodule.exports = function (argument) {\n return Object(requireObjectCoercible(argument));\n};\n","'use strict';\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar has = require('../internals/has');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar IS_PURE = require('../internals/is-pure');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar BUGGY_SAFARI_ITERATORS = false;\n\nvar returnThis = function () { return this; };\n\n// `%IteratorPrototype%` object\n// https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object\nvar IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;\n\nif ([].keys) {\n arrayIterator = [].keys();\n // Safari 8 has buggy iterators w/o `next`\n if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;\n else {\n PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));\n if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;\n }\n}\n\nif (IteratorPrototype == undefined) IteratorPrototype = {};\n\n// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()\nif (!IS_PURE && !has(IteratorPrototype, ITERATOR)) {\n createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);\n}\n\nmodule.exports = {\n IteratorPrototype: IteratorPrototype,\n BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS\n};\n","'use strict';\nvar nativePropertyIsEnumerable = {}.propertyIsEnumerable;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// Nashorn ~ JDK8 bug\nvar NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);\n\n// `Object.prototype.propertyIsEnumerable` method implementation\n// https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable\nexports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {\n var descriptor = getOwnPropertyDescriptor(this, V);\n return !!descriptor && descriptor.enumerable;\n} : nativePropertyIsEnumerable;\n","var fails = require('../internals/fails');\nvar classof = require('../internals/classof-raw');\n\nvar split = ''.split;\n\n// fallback for non-array-like ES3 and non-enumerable old V8 strings\nmodule.exports = fails(function () {\n // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346\n // eslint-disable-next-line no-prototype-builtins\n return !Object('z').propertyIsEnumerable(0);\n}) ? function (it) {\n return classof(it) == 'String' ? split.call(it, '') : Object(it);\n} : Object;\n","var DESCRIPTORS = require('../internals/descriptors');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toPrimitive = require('../internals/to-primitive');\nvar has = require('../internals/has');\nvar IE8_DOM_DEFINE = require('../internals/ie8-dom-define');\n\nvar nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// `Object.getOwnPropertyDescriptor` method\n// https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor\nexports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {\n O = toIndexedObject(O);\n P = toPrimitive(P, true);\n if (IE8_DOM_DEFINE) try {\n return nativeGetOwnPropertyDescriptor(O, P);\n } catch (error) { /* empty */ }\n if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);\n};\n","var global = require('../internals/global');\n\nmodule.exports = global;\n","// IE8- don't enum bug keys\nmodule.exports = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf'\n];\n","var internalObjectKeys = require('../internals/object-keys-internal');\nvar enumBugKeys = require('../internals/enum-bug-keys');\n\nvar hiddenKeys = enumBugKeys.concat('length', 'prototype');\n\n// `Object.getOwnPropertyNames` method\n// https://tc39.github.io/ecma262/#sec-object.getownpropertynames\nexports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return internalObjectKeys(O, hiddenKeys);\n};\n","exports.f = Object.getOwnPropertySymbols;\n","var getBuiltIn = require('../internals/get-built-in');\nvar getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar anObject = require('../internals/an-object');\n\n// all object keys, includes non-enumerable and symbols\nmodule.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {\n var keys = getOwnPropertyNamesModule.f(anObject(it));\n var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;\n return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;\n};\n","var fails = require('../internals/fails');\n\nmodule.exports = !fails(function () {\n function F() { /* empty */ }\n F.prototype.constructor = null;\n return Object.getPrototypeOf(new F()) !== F.prototype;\n});\n","var has = require('../internals/has');\nvar toObject = require('../internals/to-object');\nvar sharedKey = require('../internals/shared-key');\nvar CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');\n\nvar IE_PROTO = sharedKey('IE_PROTO');\nvar ObjectPrototype = Object.prototype;\n\n// `Object.getPrototypeOf` method\n// https://tc39.github.io/ecma262/#sec-object.getprototypeof\nmodule.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {\n O = toObject(O);\n if (has(O, IE_PROTO)) return O[IE_PROTO];\n if (typeof O.constructor == 'function' && O instanceof O.constructor) {\n return O.constructor.prototype;\n } return O instanceof Object ? ObjectPrototype : null;\n};\n","var anObject = require('../internals/an-object');\nvar defineProperties = require('../internals/object-define-properties');\nvar enumBugKeys = require('../internals/enum-bug-keys');\nvar hiddenKeys = require('../internals/hidden-keys');\nvar html = require('../internals/html');\nvar documentCreateElement = require('../internals/document-create-element');\nvar sharedKey = require('../internals/shared-key');\n\nvar GT = '>';\nvar LT = '<';\nvar PROTOTYPE = 'prototype';\nvar SCRIPT = 'script';\nvar IE_PROTO = sharedKey('IE_PROTO');\n\nvar EmptyConstructor = function () { /* empty */ };\n\nvar scriptTag = function (content) {\n return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;\n};\n\n// Create object with fake `null` prototype: use ActiveX Object with cleared prototype\nvar NullProtoObjectViaActiveX = function (activeXDocument) {\n activeXDocument.write(scriptTag(''));\n activeXDocument.close();\n var temp = activeXDocument.parentWindow.Object;\n activeXDocument = null; // avoid memory leak\n return temp;\n};\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar NullProtoObjectViaIFrame = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = documentCreateElement('iframe');\n var JS = 'java' + SCRIPT + ':';\n var iframeDocument;\n iframe.style.display = 'none';\n html.appendChild(iframe);\n // https://github.com/zloirock/core-js/issues/475\n iframe.src = String(JS);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(scriptTag('document.F=Object'));\n iframeDocument.close();\n return iframeDocument.F;\n};\n\n// Check for document.domain and active x support\n// No need to use active x approach when document.domain is not set\n// see https://github.com/es-shims/es5-shim/issues/150\n// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346\n// avoid IE GC bug\nvar activeXDocument;\nvar NullProtoObject = function () {\n try {\n /* global ActiveXObject */\n activeXDocument = document.domain && new ActiveXObject('htmlfile');\n } catch (error) { /* ignore */ }\n NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();\n var length = enumBugKeys.length;\n while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];\n return NullProtoObject();\n};\n\nhiddenKeys[IE_PROTO] = true;\n\n// `Object.create` method\n// https://tc39.github.io/ecma262/#sec-object.create\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n EmptyConstructor[PROTOTYPE] = anObject(O);\n result = new EmptyConstructor();\n EmptyConstructor[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = NullProtoObject();\n return Properties === undefined ? result : defineProperties(result, Properties);\n};\n","var internalObjectKeys = require('../internals/object-keys-internal');\nvar enumBugKeys = require('../internals/enum-bug-keys');\n\n// `Object.keys` method\n// https://tc39.github.io/ecma262/#sec-object.keys\nmodule.exports = Object.keys || function keys(O) {\n return internalObjectKeys(O, enumBugKeys);\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar definePropertyModule = require('../internals/object-define-property');\nvar anObject = require('../internals/an-object');\nvar objectKeys = require('../internals/object-keys');\n\n// `Object.defineProperties` method\n// https://tc39.github.io/ecma262/#sec-object.defineproperties\nmodule.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {\n anObject(O);\n var keys = objectKeys(Properties);\n var length = keys.length;\n var index = 0;\n var key;\n while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);\n return O;\n};\n","var getBuiltIn = require('../internals/get-built-in');\n\nmodule.exports = getBuiltIn('document', 'documentElement');\n","var defineProperty = require('../internals/object-define-property').f;\nvar has = require('../internals/has');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\n\nmodule.exports = function (it, TAG, STATIC) {\n if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {\n defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG });\n }\n};\n","'use strict';\nvar IteratorPrototype = require('../internals/iterators-core').IteratorPrototype;\nvar create = require('../internals/object-create');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar Iterators = require('../internals/iterators');\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (IteratorConstructor, NAME, next) {\n var TO_STRING_TAG = NAME + ' Iterator';\n IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) });\n setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);\n Iterators[TO_STRING_TAG] = returnThis;\n return IteratorConstructor;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar createIteratorConstructor = require('../internals/create-iterator-constructor');\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar IS_PURE = require('../internals/is-pure');\nvar Iterators = require('../internals/iterators');\nvar IteratorsCore = require('../internals/iterators-core');\n\nvar IteratorPrototype = IteratorsCore.IteratorPrototype;\nvar BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;\nvar ITERATOR = wellKnownSymbol('iterator');\nvar KEYS = 'keys';\nvar VALUES = 'values';\nvar ENTRIES = 'entries';\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {\n createIteratorConstructor(IteratorConstructor, NAME, next);\n\n var getIterationMethod = function (KIND) {\n if (KIND === DEFAULT && defaultIterator) return defaultIterator;\n if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];\n switch (KIND) {\n case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };\n case VALUES: return function values() { return new IteratorConstructor(this, KIND); };\n case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };\n } return function () { return new IteratorConstructor(this); };\n };\n\n var TO_STRING_TAG = NAME + ' Iterator';\n var INCORRECT_VALUES_NAME = false;\n var IterablePrototype = Iterable.prototype;\n var nativeIterator = IterablePrototype[ITERATOR]\n || IterablePrototype['@@iterator']\n || DEFAULT && IterablePrototype[DEFAULT];\n var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);\n var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;\n var CurrentIteratorPrototype, methods, KEY;\n\n // fix native\n if (anyNativeIterator) {\n CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));\n if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {\n if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {\n if (setPrototypeOf) {\n setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);\n } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {\n createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);\n }\n }\n // Set @@toStringTag to native iterators\n setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);\n if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;\n }\n }\n\n // fix Array#{values, @@iterator}.name in V8 / FF\n if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {\n INCORRECT_VALUES_NAME = true;\n defaultIterator = function values() { return nativeIterator.call(this); };\n }\n\n // define iterator\n if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {\n createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);\n }\n Iterators[NAME] = defaultIterator;\n\n // export additional methods\n if (DEFAULT) {\n methods = {\n values: getIterationMethod(VALUES),\n keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),\n entries: getIterationMethod(ENTRIES)\n };\n if (FORCED) for (KEY in methods) {\n if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {\n redefine(IterablePrototype, KEY, methods[KEY]);\n }\n } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);\n }\n\n return methods;\n};\n","module.exports = {};\n","var anObject = require('../internals/an-object');\nvar aPossiblePrototype = require('../internals/a-possible-prototype');\n\n// `Object.setPrototypeOf` method\n// https://tc39.github.io/ecma262/#sec-object.setprototypeof\n// Works with __proto__ only. Old v8 can't work with null proto objects.\n/* eslint-disable no-proto */\nmodule.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {\n var CORRECT_SETTER = false;\n var test = {};\n var setter;\n try {\n setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;\n setter.call(test, []);\n CORRECT_SETTER = test instanceof Array;\n } catch (error) { /* empty */ }\n return function setPrototypeOf(O, proto) {\n anObject(O);\n aPossiblePrototype(proto);\n if (CORRECT_SETTER) setter.call(O, proto);\n else O.__proto__ = proto;\n return O;\n };\n}() : undefined);\n","var isObject = require('../internals/is-object');\n\nmodule.exports = function (it) {\n if (!isObject(it) && it !== null) {\n throw TypeError(\"Can't set \" + String(it) + ' as a prototype');\n } return it;\n};\n","'use strict';\nvar charAt = require('../internals/string-multibyte').charAt;\nvar InternalStateModule = require('../internals/internal-state');\nvar defineIterator = require('../internals/define-iterator');\n\nvar STRING_ITERATOR = 'String Iterator';\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);\n\n// `String.prototype[@@iterator]` method\n// https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator\ndefineIterator(String, 'String', function (iterated) {\n setInternalState(this, {\n type: STRING_ITERATOR,\n string: String(iterated),\n index: 0\n });\n// `%StringIteratorPrototype%.next` method\n// https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next\n}, function next() {\n var state = getInternalState(this);\n var string = state.string;\n var index = state.index;\n var point;\n if (index >= string.length) return { value: undefined, done: true };\n point = charAt(string, index);\n state.index += point.length;\n return { value: point, done: false };\n});\n","// iterable DOM collections\n// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods\nmodule.exports = {\n CSSRuleList: 0,\n CSSStyleDeclaration: 0,\n CSSValueList: 0,\n ClientRectList: 0,\n DOMRectList: 0,\n DOMStringList: 0,\n DOMTokenList: 1,\n DataTransferItemList: 0,\n FileList: 0,\n HTMLAllCollection: 0,\n HTMLCollection: 0,\n HTMLFormElement: 0,\n HTMLSelectElement: 0,\n MediaList: 0,\n MimeTypeArray: 0,\n NamedNodeMap: 0,\n NodeList: 1,\n PaintRequestList: 0,\n Plugin: 0,\n PluginArray: 0,\n SVGLengthList: 0,\n SVGNumberList: 0,\n SVGPathSegList: 0,\n SVGPointList: 0,\n SVGStringList: 0,\n SVGTransformList: 0,\n SourceBufferList: 0,\n StyleSheetList: 0,\n TextTrackCueList: 0,\n TextTrackList: 0,\n TouchList: 0\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\nvar create = require('../internals/object-create');\nvar definePropertyModule = require('../internals/object-define-property');\n\nvar UNSCOPABLES = wellKnownSymbol('unscopables');\nvar ArrayPrototype = Array.prototype;\n\n// Array.prototype[@@unscopables]\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables\nif (ArrayPrototype[UNSCOPABLES] == undefined) {\n definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {\n configurable: true,\n value: create(null)\n });\n}\n\n// add a key to Array.prototype[@@unscopables]\nmodule.exports = function (key) {\n ArrayPrototype[UNSCOPABLES][key] = true;\n};\n","'use strict';\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar addToUnscopables = require('../internals/add-to-unscopables');\nvar Iterators = require('../internals/iterators');\nvar InternalStateModule = require('../internals/internal-state');\nvar defineIterator = require('../internals/define-iterator');\n\nvar ARRAY_ITERATOR = 'Array Iterator';\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);\n\n// `Array.prototype.entries` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.entries\n// `Array.prototype.keys` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.keys\n// `Array.prototype.values` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.values\n// `Array.prototype[@@iterator]` method\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator\n// `CreateArrayIterator` internal method\n// https://tc39.github.io/ecma262/#sec-createarrayiterator\nmodule.exports = defineIterator(Array, 'Array', function (iterated, kind) {\n setInternalState(this, {\n type: ARRAY_ITERATOR,\n target: toIndexedObject(iterated), // target\n index: 0, // next index\n kind: kind // kind\n });\n// `%ArrayIteratorPrototype%.next` method\n// https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next\n}, function () {\n var state = getInternalState(this);\n var target = state.target;\n var kind = state.kind;\n var index = state.index++;\n if (!target || index >= target.length) {\n state.target = undefined;\n return { value: undefined, done: true };\n }\n if (kind == 'keys') return { value: index, done: false };\n if (kind == 'values') return { value: target[index], done: false };\n return { value: [index, target[index]], done: false };\n}, 'values');\n\n// argumentsList[@@iterator] is %ArrayProto_values%\n// https://tc39.github.io/ecma262/#sec-createunmappedargumentsobject\n// https://tc39.github.io/ecma262/#sec-createmappedargumentsobject\nIterators.Arguments = Iterators.Array;\n\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables('keys');\naddToUnscopables('values');\naddToUnscopables('entries');\n","var global = require('../internals/global');\nvar DOMIterables = require('../internals/dom-iterables');\nvar ArrayIteratorMethods = require('../modules/es.array.iterator');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar ArrayValues = ArrayIteratorMethods.values;\n\nfor (var COLLECTION_NAME in DOMIterables) {\n var Collection = global[COLLECTION_NAME];\n var CollectionPrototype = Collection && Collection.prototype;\n if (CollectionPrototype) {\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype[ITERATOR] !== ArrayValues) try {\n createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);\n } catch (error) {\n CollectionPrototype[ITERATOR] = ArrayValues;\n }\n if (!CollectionPrototype[TO_STRING_TAG]) {\n createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);\n }\n if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {\n createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);\n } catch (error) {\n CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];\n }\n }\n }\n}\n","var redefine = require('../internals/redefine');\n\nmodule.exports = function (target, src, options) {\n for (var key in src) redefine(target, key, src[key], options);\n return target;\n};\n","'use strict';\nvar getBuiltIn = require('../internals/get-built-in');\nvar definePropertyModule = require('../internals/object-define-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar DESCRIPTORS = require('../internals/descriptors');\n\nvar SPECIES = wellKnownSymbol('species');\n\nmodule.exports = function (CONSTRUCTOR_NAME) {\n var Constructor = getBuiltIn(CONSTRUCTOR_NAME);\n var defineProperty = definePropertyModule.f;\n\n if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {\n defineProperty(Constructor, SPECIES, {\n configurable: true,\n get: function () { return this; }\n });\n }\n};\n","module.exports = function (it) {\n if (typeof it != 'function') {\n throw TypeError(String(it) + ' is not a function');\n } return it;\n};\n","module.exports = function (it, Constructor, name) {\n if (!(it instanceof Constructor)) {\n throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');\n } return it;\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\nvar Iterators = require('../internals/iterators');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar ArrayPrototype = Array.prototype;\n\n// check on default Array iterator\nmodule.exports = function (it) {\n return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);\n};\n","var aFunction = require('../internals/a-function');\n\n// optional / simple context binding\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 0: return function () {\n return fn.call(that);\n };\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","var classof = require('../internals/classof');\nvar Iterators = require('../internals/iterators');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\n\nmodule.exports = function (it) {\n if (it != undefined) return it[ITERATOR]\n || it['@@iterator']\n || Iterators[classof(it)];\n};\n","var anObject = require('../internals/an-object');\n\n// call something on iterator step with safe closing on error\nmodule.exports = function (iterator, fn, value, ENTRIES) {\n try {\n return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);\n // 7.4.6 IteratorClose(iterator, completion)\n } catch (error) {\n var returnMethod = iterator['return'];\n if (returnMethod !== undefined) anObject(returnMethod.call(iterator));\n throw error;\n }\n};\n","var global = require('../internals/global');\n\nmodule.exports = global.Promise;\n","var anObject = require('../internals/an-object');\nvar isArrayIteratorMethod = require('../internals/is-array-iterator-method');\nvar toLength = require('../internals/to-length');\nvar bind = require('../internals/function-bind-context');\nvar getIteratorMethod = require('../internals/get-iterator-method');\nvar callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');\n\nvar Result = function (stopped, result) {\n this.stopped = stopped;\n this.result = result;\n};\n\nvar iterate = module.exports = function (iterable, fn, that, AS_ENTRIES, IS_ITERATOR) {\n var boundFunction = bind(fn, that, AS_ENTRIES ? 2 : 1);\n var iterator, iterFn, index, length, result, next, step;\n\n if (IS_ITERATOR) {\n iterator = iterable;\n } else {\n iterFn = getIteratorMethod(iterable);\n if (typeof iterFn != 'function') throw TypeError('Target is not iterable');\n // optimisation for array iterators\n if (isArrayIteratorMethod(iterFn)) {\n for (index = 0, length = toLength(iterable.length); length > index; index++) {\n result = AS_ENTRIES\n ? boundFunction(anObject(step = iterable[index])[0], step[1])\n : boundFunction(iterable[index]);\n if (result && result instanceof Result) return result;\n } return new Result(false);\n }\n iterator = iterFn.call(iterable);\n }\n\n next = iterator.next;\n while (!(step = next.call(iterator)).done) {\n result = callWithSafeIterationClosing(iterator, boundFunction, step.value, AS_ENTRIES);\n if (typeof result == 'object' && result && result instanceof Result) return result;\n } return new Result(false);\n};\n\niterate.stop = function (result) {\n return new Result(true, result);\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar SAFE_CLOSING = false;\n\ntry {\n var called = 0;\n var iteratorWithReturn = {\n next: function () {\n return { done: !!called++ };\n },\n 'return': function () {\n SAFE_CLOSING = true;\n }\n };\n iteratorWithReturn[ITERATOR] = function () {\n return this;\n };\n // eslint-disable-next-line no-throw-literal\n Array.from(iteratorWithReturn, function () { throw 2; });\n} catch (error) { /* empty */ }\n\nmodule.exports = function (exec, SKIP_CLOSING) {\n if (!SKIP_CLOSING && !SAFE_CLOSING) return false;\n var ITERATION_SUPPORT = false;\n try {\n var object = {};\n object[ITERATOR] = function () {\n return {\n next: function () {\n return { done: ITERATION_SUPPORT = true };\n }\n };\n };\n exec(object);\n } catch (error) { /* empty */ }\n return ITERATION_SUPPORT;\n};\n","var anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar SPECIES = wellKnownSymbol('species');\n\n// `SpeciesConstructor` abstract operation\n// https://tc39.github.io/ecma262/#sec-speciesconstructor\nmodule.exports = function (O, defaultConstructor) {\n var C = anObject(O).constructor;\n var S;\n return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? defaultConstructor : aFunction(S);\n};\n","var global = require('../internals/global');\nvar fails = require('../internals/fails');\nvar classof = require('../internals/classof-raw');\nvar bind = require('../internals/function-bind-context');\nvar html = require('../internals/html');\nvar createElement = require('../internals/document-create-element');\nvar IS_IOS = require('../internals/engine-is-ios');\n\nvar location = global.location;\nvar set = global.setImmediate;\nvar clear = global.clearImmediate;\nvar process = global.process;\nvar MessageChannel = global.MessageChannel;\nvar Dispatch = global.Dispatch;\nvar counter = 0;\nvar queue = {};\nvar ONREADYSTATECHANGE = 'onreadystatechange';\nvar defer, channel, port;\n\nvar run = function (id) {\n // eslint-disable-next-line no-prototype-builtins\n if (queue.hasOwnProperty(id)) {\n var fn = queue[id];\n delete queue[id];\n fn();\n }\n};\n\nvar runner = function (id) {\n return function () {\n run(id);\n };\n};\n\nvar listener = function (event) {\n run(event.data);\n};\n\nvar post = function (id) {\n // old engines have not location.origin\n global.postMessage(id + '', location.protocol + '//' + location.host);\n};\n\n// Node.js 0.9+ & IE10+ has setImmediate, otherwise:\nif (!set || !clear) {\n set = function setImmediate(fn) {\n var args = [];\n var i = 1;\n while (arguments.length > i) args.push(arguments[i++]);\n queue[++counter] = function () {\n // eslint-disable-next-line no-new-func\n (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);\n };\n defer(counter);\n return counter;\n };\n clear = function clearImmediate(id) {\n delete queue[id];\n };\n // Node.js 0.8-\n if (classof(process) == 'process') {\n defer = function (id) {\n process.nextTick(runner(id));\n };\n // Sphere (JS game engine) Dispatch API\n } else if (Dispatch && Dispatch.now) {\n defer = function (id) {\n Dispatch.now(runner(id));\n };\n // Browsers with MessageChannel, includes WebWorkers\n // except iOS - https://github.com/zloirock/core-js/issues/624\n } else if (MessageChannel && !IS_IOS) {\n channel = new MessageChannel();\n port = channel.port2;\n channel.port1.onmessage = listener;\n defer = bind(port.postMessage, port, 1);\n // Browsers with postMessage, skip WebWorkers\n // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'\n } else if (global.addEventListener && typeof postMessage == 'function' && !global.importScripts && !fails(post)) {\n defer = post;\n global.addEventListener('message', listener, false);\n // IE8-\n } else if (ONREADYSTATECHANGE in createElement('script')) {\n defer = function (id) {\n html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {\n html.removeChild(this);\n run(id);\n };\n };\n // Rest old browsers\n } else {\n defer = function (id) {\n setTimeout(runner(id), 0);\n };\n }\n}\n\nmodule.exports = {\n set: set,\n clear: clear\n};\n","var getBuiltIn = require('../internals/get-built-in');\n\nmodule.exports = getBuiltIn('navigator', 'userAgent') || '';\n","var userAgent = require('../internals/engine-user-agent');\n\nmodule.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent);\n","var global = require('../internals/global');\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar classof = require('../internals/classof-raw');\nvar macrotask = require('../internals/task').set;\nvar IS_IOS = require('../internals/engine-is-ios');\n\nvar MutationObserver = global.MutationObserver || global.WebKitMutationObserver;\nvar process = global.process;\nvar Promise = global.Promise;\nvar IS_NODE = classof(process) == 'process';\n// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`\nvar queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask');\nvar queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;\n\nvar flush, head, last, notify, toggle, node, promise, then;\n\n// modern engines have queueMicrotask method\nif (!queueMicrotask) {\n flush = function () {\n var parent, fn;\n if (IS_NODE && (parent = process.domain)) parent.exit();\n while (head) {\n fn = head.fn;\n head = head.next;\n try {\n fn();\n } catch (error) {\n if (head) notify();\n else last = undefined;\n throw error;\n }\n } last = undefined;\n if (parent) parent.enter();\n };\n\n // Node.js\n if (IS_NODE) {\n notify = function () {\n process.nextTick(flush);\n };\n // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339\n } else if (MutationObserver && !IS_IOS) {\n toggle = true;\n node = document.createTextNode('');\n new MutationObserver(flush).observe(node, { characterData: true });\n notify = function () {\n node.data = toggle = !toggle;\n };\n // environments with maybe non-completely correct, but existent Promise\n } else if (Promise && Promise.resolve) {\n // Promise.resolve without an argument throws an error in LG WebOS 2\n promise = Promise.resolve(undefined);\n then = promise.then;\n notify = function () {\n then.call(promise, flush);\n };\n // for other environments - macrotask based on:\n // - setImmediate\n // - MessageChannel\n // - window.postMessag\n // - onreadystatechange\n // - setTimeout\n } else {\n notify = function () {\n // strange IE + webpack dev server bug - use .call(global)\n macrotask.call(global, flush);\n };\n }\n}\n\nmodule.exports = queueMicrotask || function (fn) {\n var task = { fn: fn, next: undefined };\n if (last) last.next = task;\n if (!head) {\n head = task;\n notify();\n } last = task;\n};\n","'use strict';\nvar aFunction = require('../internals/a-function');\n\nvar PromiseCapability = function (C) {\n var resolve, reject;\n this.promise = new C(function ($$resolve, $$reject) {\n if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');\n resolve = $$resolve;\n reject = $$reject;\n });\n this.resolve = aFunction(resolve);\n this.reject = aFunction(reject);\n};\n\n// 25.4.1.5 NewPromiseCapability(C)\nmodule.exports.f = function (C) {\n return new PromiseCapability(C);\n};\n","var anObject = require('../internals/an-object');\nvar isObject = require('../internals/is-object');\nvar newPromiseCapability = require('../internals/new-promise-capability');\n\nmodule.exports = function (C, x) {\n anObject(C);\n if (isObject(x) && x.constructor === C) return x;\n var promiseCapability = newPromiseCapability.f(C);\n var resolve = promiseCapability.resolve;\n resolve(x);\n return promiseCapability.promise;\n};\n","module.exports = function (exec) {\n try {\n return { error: false, value: exec() };\n } catch (error) {\n return { error: true, value: error };\n }\n};\n","var global = require('../internals/global');\nvar userAgent = require('../internals/engine-user-agent');\n\nvar process = global.process;\nvar versions = process && process.versions;\nvar v8 = versions && versions.v8;\nvar match, version;\n\nif (v8) {\n match = v8.split('.');\n version = match[0] + match[1];\n} else if (userAgent) {\n match = userAgent.match(/Edge\\/(\\d+)/);\n if (!match || match[1] >= 74) {\n match = userAgent.match(/Chrome\\/(\\d+)/);\n if (match) version = match[1];\n }\n}\n\nmodule.exports = version && +version;\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar global = require('../internals/global');\nvar getBuiltIn = require('../internals/get-built-in');\nvar NativePromise = require('../internals/native-promise-constructor');\nvar redefine = require('../internals/redefine');\nvar redefineAll = require('../internals/redefine-all');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar setSpecies = require('../internals/set-species');\nvar isObject = require('../internals/is-object');\nvar aFunction = require('../internals/a-function');\nvar anInstance = require('../internals/an-instance');\nvar classof = require('../internals/classof-raw');\nvar inspectSource = require('../internals/inspect-source');\nvar iterate = require('../internals/iterate');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\nvar speciesConstructor = require('../internals/species-constructor');\nvar task = require('../internals/task').set;\nvar microtask = require('../internals/microtask');\nvar promiseResolve = require('../internals/promise-resolve');\nvar hostReportErrors = require('../internals/host-report-errors');\nvar newPromiseCapabilityModule = require('../internals/new-promise-capability');\nvar perform = require('../internals/perform');\nvar InternalStateModule = require('../internals/internal-state');\nvar isForced = require('../internals/is-forced');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar SPECIES = wellKnownSymbol('species');\nvar PROMISE = 'Promise';\nvar getInternalState = InternalStateModule.get;\nvar setInternalState = InternalStateModule.set;\nvar getInternalPromiseState = InternalStateModule.getterFor(PROMISE);\nvar PromiseConstructor = NativePromise;\nvar TypeError = global.TypeError;\nvar document = global.document;\nvar process = global.process;\nvar $fetch = getBuiltIn('fetch');\nvar newPromiseCapability = newPromiseCapabilityModule.f;\nvar newGenericPromiseCapability = newPromiseCapability;\nvar IS_NODE = classof(process) == 'process';\nvar DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);\nvar UNHANDLED_REJECTION = 'unhandledrejection';\nvar REJECTION_HANDLED = 'rejectionhandled';\nvar PENDING = 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\nvar HANDLED = 1;\nvar UNHANDLED = 2;\nvar Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;\n\nvar FORCED = isForced(PROMISE, function () {\n var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);\n if (!GLOBAL_CORE_JS_PROMISE) {\n // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables\n // https://bugs.chromium.org/p/chromium/issues/detail?id=830565\n // We can't detect it synchronously, so just check versions\n if (V8_VERSION === 66) return true;\n // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test\n if (!IS_NODE && typeof PromiseRejectionEvent != 'function') return true;\n }\n // We need Promise#finally in the pure version for preventing prototype pollution\n if (IS_PURE && !PromiseConstructor.prototype['finally']) return true;\n // We can't use @@species feature detection in V8 since it causes\n // deoptimization and performance degradation\n // https://github.com/zloirock/core-js/issues/679\n if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false;\n // Detect correctness of subclassing with @@species support\n var promise = PromiseConstructor.resolve(1);\n var FakePromise = function (exec) {\n exec(function () { /* empty */ }, function () { /* empty */ });\n };\n var constructor = promise.constructor = {};\n constructor[SPECIES] = FakePromise;\n return !(promise.then(function () { /* empty */ }) instanceof FakePromise);\n});\n\nvar INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) {\n PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });\n});\n\n// helpers\nvar isThenable = function (it) {\n var then;\n return isObject(it) && typeof (then = it.then) == 'function' ? then : false;\n};\n\nvar notify = function (promise, state, isReject) {\n if (state.notified) return;\n state.notified = true;\n var chain = state.reactions;\n microtask(function () {\n var value = state.value;\n var ok = state.state == FULFILLED;\n var index = 0;\n // variable length - can't use forEach\n while (chain.length > index) {\n var reaction = chain[index++];\n var handler = ok ? reaction.ok : reaction.fail;\n var resolve = reaction.resolve;\n var reject = reaction.reject;\n var domain = reaction.domain;\n var result, then, exited;\n try {\n if (handler) {\n if (!ok) {\n if (state.rejection === UNHANDLED) onHandleUnhandled(promise, state);\n state.rejection = HANDLED;\n }\n if (handler === true) result = value;\n else {\n if (domain) domain.enter();\n result = handler(value); // can throw\n if (domain) {\n domain.exit();\n exited = true;\n }\n }\n if (result === reaction.promise) {\n reject(TypeError('Promise-chain cycle'));\n } else if (then = isThenable(result)) {\n then.call(result, resolve, reject);\n } else resolve(result);\n } else reject(value);\n } catch (error) {\n if (domain && !exited) domain.exit();\n reject(error);\n }\n }\n state.reactions = [];\n state.notified = false;\n if (isReject && !state.rejection) onUnhandled(promise, state);\n });\n};\n\nvar dispatchEvent = function (name, promise, reason) {\n var event, handler;\n if (DISPATCH_EVENT) {\n event = document.createEvent('Event');\n event.promise = promise;\n event.reason = reason;\n event.initEvent(name, false, true);\n global.dispatchEvent(event);\n } else event = { promise: promise, reason: reason };\n if (handler = global['on' + name]) handler(event);\n else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);\n};\n\nvar onUnhandled = function (promise, state) {\n task.call(global, function () {\n var value = state.value;\n var IS_UNHANDLED = isUnhandled(state);\n var result;\n if (IS_UNHANDLED) {\n result = perform(function () {\n if (IS_NODE) {\n process.emit('unhandledRejection', value, promise);\n } else dispatchEvent(UNHANDLED_REJECTION, promise, value);\n });\n // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should\n state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;\n if (result.error) throw result.value;\n }\n });\n};\n\nvar isUnhandled = function (state) {\n return state.rejection !== HANDLED && !state.parent;\n};\n\nvar onHandleUnhandled = function (promise, state) {\n task.call(global, function () {\n if (IS_NODE) {\n process.emit('rejectionHandled', promise);\n } else dispatchEvent(REJECTION_HANDLED, promise, state.value);\n });\n};\n\nvar bind = function (fn, promise, state, unwrap) {\n return function (value) {\n fn(promise, state, value, unwrap);\n };\n};\n\nvar internalReject = function (promise, state, value, unwrap) {\n if (state.done) return;\n state.done = true;\n if (unwrap) state = unwrap;\n state.value = value;\n state.state = REJECTED;\n notify(promise, state, true);\n};\n\nvar internalResolve = function (promise, state, value, unwrap) {\n if (state.done) return;\n state.done = true;\n if (unwrap) state = unwrap;\n try {\n if (promise === value) throw TypeError(\"Promise can't be resolved itself\");\n var then = isThenable(value);\n if (then) {\n microtask(function () {\n var wrapper = { done: false };\n try {\n then.call(value,\n bind(internalResolve, promise, wrapper, state),\n bind(internalReject, promise, wrapper, state)\n );\n } catch (error) {\n internalReject(promise, wrapper, error, state);\n }\n });\n } else {\n state.value = value;\n state.state = FULFILLED;\n notify(promise, state, false);\n }\n } catch (error) {\n internalReject(promise, { done: false }, error, state);\n }\n};\n\n// constructor polyfill\nif (FORCED) {\n // 25.4.3.1 Promise(executor)\n PromiseConstructor = function Promise(executor) {\n anInstance(this, PromiseConstructor, PROMISE);\n aFunction(executor);\n Internal.call(this);\n var state = getInternalState(this);\n try {\n executor(bind(internalResolve, this, state), bind(internalReject, this, state));\n } catch (error) {\n internalReject(this, state, error);\n }\n };\n // eslint-disable-next-line no-unused-vars\n Internal = function Promise(executor) {\n setInternalState(this, {\n type: PROMISE,\n done: false,\n notified: false,\n parent: false,\n reactions: [],\n rejection: false,\n state: PENDING,\n value: undefined\n });\n };\n Internal.prototype = redefineAll(PromiseConstructor.prototype, {\n // `Promise.prototype.then` method\n // https://tc39.github.io/ecma262/#sec-promise.prototype.then\n then: function then(onFulfilled, onRejected) {\n var state = getInternalPromiseState(this);\n var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));\n reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;\n reaction.fail = typeof onRejected == 'function' && onRejected;\n reaction.domain = IS_NODE ? process.domain : undefined;\n state.parent = true;\n state.reactions.push(reaction);\n if (state.state != PENDING) notify(this, state, false);\n return reaction.promise;\n },\n // `Promise.prototype.catch` method\n // https://tc39.github.io/ecma262/#sec-promise.prototype.catch\n 'catch': function (onRejected) {\n return this.then(undefined, onRejected);\n }\n });\n OwnPromiseCapability = function () {\n var promise = new Internal();\n var state = getInternalState(promise);\n this.promise = promise;\n this.resolve = bind(internalResolve, promise, state);\n this.reject = bind(internalReject, promise, state);\n };\n newPromiseCapabilityModule.f = newPromiseCapability = function (C) {\n return C === PromiseConstructor || C === PromiseWrapper\n ? new OwnPromiseCapability(C)\n : newGenericPromiseCapability(C);\n };\n\n if (!IS_PURE && typeof NativePromise == 'function') {\n nativeThen = NativePromise.prototype.then;\n\n // wrap native Promise#then for native async functions\n redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) {\n var that = this;\n return new PromiseConstructor(function (resolve, reject) {\n nativeThen.call(that, resolve, reject);\n }).then(onFulfilled, onRejected);\n // https://github.com/zloirock/core-js/issues/640\n }, { unsafe: true });\n\n // wrap fetch result\n if (typeof $fetch == 'function') $({ global: true, enumerable: true, forced: true }, {\n // eslint-disable-next-line no-unused-vars\n fetch: function fetch(input /* , init */) {\n return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments));\n }\n });\n }\n}\n\n$({ global: true, wrap: true, forced: FORCED }, {\n Promise: PromiseConstructor\n});\n\nsetToStringTag(PromiseConstructor, PROMISE, false, true);\nsetSpecies(PROMISE);\n\nPromiseWrapper = getBuiltIn(PROMISE);\n\n// statics\n$({ target: PROMISE, stat: true, forced: FORCED }, {\n // `Promise.reject` method\n // https://tc39.github.io/ecma262/#sec-promise.reject\n reject: function reject(r) {\n var capability = newPromiseCapability(this);\n capability.reject.call(undefined, r);\n return capability.promise;\n }\n});\n\n$({ target: PROMISE, stat: true, forced: IS_PURE || FORCED }, {\n // `Promise.resolve` method\n // https://tc39.github.io/ecma262/#sec-promise.resolve\n resolve: function resolve(x) {\n return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x);\n }\n});\n\n$({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, {\n // `Promise.all` method\n // https://tc39.github.io/ecma262/#sec-promise.all\n all: function all(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var resolve = capability.resolve;\n var reject = capability.reject;\n var result = perform(function () {\n var $promiseResolve = aFunction(C.resolve);\n var values = [];\n var counter = 0;\n var remaining = 1;\n iterate(iterable, function (promise) {\n var index = counter++;\n var alreadyCalled = false;\n values.push(undefined);\n remaining++;\n $promiseResolve.call(C, promise).then(function (value) {\n if (alreadyCalled) return;\n alreadyCalled = true;\n values[index] = value;\n --remaining || resolve(values);\n }, reject);\n });\n --remaining || resolve(values);\n });\n if (result.error) reject(result.value);\n return capability.promise;\n },\n // `Promise.race` method\n // https://tc39.github.io/ecma262/#sec-promise.race\n race: function race(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var reject = capability.reject;\n var result = perform(function () {\n var $promiseResolve = aFunction(C.resolve);\n iterate(iterable, function (promise) {\n $promiseResolve.call(C, promise).then(capability.resolve, reject);\n });\n });\n if (result.error) reject(result.value);\n return capability.promise;\n }\n});\n","var global = require('../internals/global');\n\nmodule.exports = function (a, b) {\n var console = global.console;\n if (console && console.error) {\n arguments.length === 1 ? console.error(a) : console.error(a, b);\n }\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar aFunction = require('../internals/a-function');\nvar newPromiseCapabilityModule = require('../internals/new-promise-capability');\nvar perform = require('../internals/perform');\nvar iterate = require('../internals/iterate');\n\n// `Promise.allSettled` method\n// https://github.com/tc39/proposal-promise-allSettled\n$({ target: 'Promise', stat: true }, {\n allSettled: function allSettled(iterable) {\n var C = this;\n var capability = newPromiseCapabilityModule.f(C);\n var resolve = capability.resolve;\n var reject = capability.reject;\n var result = perform(function () {\n var promiseResolve = aFunction(C.resolve);\n var values = [];\n var counter = 0;\n var remaining = 1;\n iterate(iterable, function (promise) {\n var index = counter++;\n var alreadyCalled = false;\n values.push(undefined);\n remaining++;\n promiseResolve.call(C, promise).then(function (value) {\n if (alreadyCalled) return;\n alreadyCalled = true;\n values[index] = { status: 'fulfilled', value: value };\n --remaining || resolve(values);\n }, function (e) {\n if (alreadyCalled) return;\n alreadyCalled = true;\n values[index] = { status: 'rejected', reason: e };\n --remaining || resolve(values);\n });\n });\n --remaining || resolve(values);\n });\n if (result.error) reject(result.value);\n return capability.promise;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar NativePromise = require('../internals/native-promise-constructor');\nvar fails = require('../internals/fails');\nvar getBuiltIn = require('../internals/get-built-in');\nvar speciesConstructor = require('../internals/species-constructor');\nvar promiseResolve = require('../internals/promise-resolve');\nvar redefine = require('../internals/redefine');\n\n// Safari bug https://bugs.webkit.org/show_bug.cgi?id=200829\nvar NON_GENERIC = !!NativePromise && fails(function () {\n NativePromise.prototype['finally'].call({ then: function () { /* empty */ } }, function () { /* empty */ });\n});\n\n// `Promise.prototype.finally` method\n// https://tc39.github.io/ecma262/#sec-promise.prototype.finally\n$({ target: 'Promise', proto: true, real: true, forced: NON_GENERIC }, {\n 'finally': function (onFinally) {\n var C = speciesConstructor(this, getBuiltIn('Promise'));\n var isFunction = typeof onFinally == 'function';\n return this.then(\n isFunction ? function (x) {\n return promiseResolve(C, onFinally()).then(function () { return x; });\n } : onFinally,\n isFunction ? function (e) {\n return promiseResolve(C, onFinally()).then(function () { throw e; });\n } : onFinally\n );\n }\n});\n\n// patch native Promise.prototype for native async functions\nif (!IS_PURE && typeof NativePromise == 'function' && !NativePromise.prototype['finally']) {\n redefine(NativePromise.prototype, 'finally', getBuiltIn('Promise').prototype['finally']);\n}\n","require('../../modules/es.object.to-string');\nrequire('../../modules/es.string.iterator');\nrequire('../../modules/web.dom-collections.iterator');\nrequire('../../modules/es.promise');\nrequire('../../modules/es.promise.all-settled');\nrequire('../../modules/es.promise.finally');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Promise;\n","'use strict';\nvar $ = require('../internals/export');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar create = require('../internals/object-create');\nvar defineProperty = require('../internals/object-define-property');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar iterate = require('../internals/iterate');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar InternalStateModule = require('../internals/internal-state');\n\nvar setInternalState = InternalStateModule.set;\nvar getInternalAggregateErrorState = InternalStateModule.getterFor('AggregateError');\n\nvar $AggregateError = function AggregateError(errors, message) {\n var that = this;\n if (!(that instanceof $AggregateError)) return new $AggregateError(errors, message);\n if (setPrototypeOf) {\n that = setPrototypeOf(new Error(message), getPrototypeOf(that));\n }\n var errorsArray = [];\n iterate(errors, errorsArray.push, errorsArray);\n if (DESCRIPTORS) setInternalState(that, { errors: errorsArray, type: 'AggregateError' });\n else that.errors = errorsArray;\n if (message !== undefined) createNonEnumerableProperty(that, 'message', String(message));\n return that;\n};\n\n$AggregateError.prototype = create(Error.prototype, {\n constructor: createPropertyDescriptor(5, $AggregateError),\n message: createPropertyDescriptor(5, ''),\n name: createPropertyDescriptor(5, 'AggregateError')\n});\n\nif (DESCRIPTORS) defineProperty.f($AggregateError.prototype, 'errors', {\n get: function () {\n return getInternalAggregateErrorState(this).errors;\n },\n configurable: true\n});\n\n$({ global: true }, {\n AggregateError: $AggregateError\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar newPromiseCapabilityModule = require('../internals/new-promise-capability');\nvar perform = require('../internals/perform');\n\n// `Promise.try` method\n// https://github.com/tc39/proposal-promise-try\n$({ target: 'Promise', stat: true }, {\n 'try': function (callbackfn) {\n var promiseCapability = newPromiseCapabilityModule.f(this);\n var result = perform(callbackfn);\n (result.error ? promiseCapability.reject : promiseCapability.resolve)(result.value);\n return promiseCapability.promise;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar aFunction = require('../internals/a-function');\nvar getBuiltIn = require('../internals/get-built-in');\nvar newPromiseCapabilityModule = require('../internals/new-promise-capability');\nvar perform = require('../internals/perform');\nvar iterate = require('../internals/iterate');\n\nvar PROMISE_ANY_ERROR = 'No one promise resolved';\n\n// `Promise.any` method\n// https://github.com/tc39/proposal-promise-any\n$({ target: 'Promise', stat: true }, {\n any: function any(iterable) {\n var C = this;\n var capability = newPromiseCapabilityModule.f(C);\n var resolve = capability.resolve;\n var reject = capability.reject;\n var result = perform(function () {\n var promiseResolve = aFunction(C.resolve);\n var errors = [];\n var counter = 0;\n var remaining = 1;\n var alreadyResolved = false;\n iterate(iterable, function (promise) {\n var index = counter++;\n var alreadyRejected = false;\n errors.push(undefined);\n remaining++;\n promiseResolve.call(C, promise).then(function (value) {\n if (alreadyRejected || alreadyResolved) return;\n alreadyResolved = true;\n resolve(value);\n }, function (e) {\n if (alreadyRejected || alreadyResolved) return;\n alreadyRejected = true;\n errors[index] = e;\n --remaining || reject(new (getBuiltIn('AggregateError'))(errors, PROMISE_ANY_ERROR));\n });\n });\n --remaining || reject(new (getBuiltIn('AggregateError'))(errors, PROMISE_ANY_ERROR));\n });\n if (result.error) reject(result.value);\n return capability.promise;\n }\n});\n","var isObject = require('../internals/is-object');\nvar isArray = require('../internals/is-array');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar SPECIES = wellKnownSymbol('species');\n\n// `ArraySpeciesCreate` abstract operation\n// https://tc39.github.io/ecma262/#sec-arrayspeciescreate\nmodule.exports = function (originalArray, length) {\n var C;\n if (isArray(originalArray)) {\n C = originalArray.constructor;\n // cross-realm fallback\n if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;\n else if (isObject(C)) {\n C = C[SPECIES];\n if (C === null) C = undefined;\n }\n } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);\n};\n","var bind = require('../internals/function-bind-context');\nvar IndexedObject = require('../internals/indexed-object');\nvar toObject = require('../internals/to-object');\nvar toLength = require('../internals/to-length');\nvar arraySpeciesCreate = require('../internals/array-species-create');\n\nvar push = [].push;\n\n// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation\nvar createMethod = function (TYPE) {\n var IS_MAP = TYPE == 1;\n var IS_FILTER = TYPE == 2;\n var IS_SOME = TYPE == 3;\n var IS_EVERY = TYPE == 4;\n var IS_FIND_INDEX = TYPE == 6;\n var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;\n return function ($this, callbackfn, that, specificCreate) {\n var O = toObject($this);\n var self = IndexedObject(O);\n var boundFunction = bind(callbackfn, that, 3);\n var length = toLength(self.length);\n var index = 0;\n var create = specificCreate || arraySpeciesCreate;\n var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;\n var value, result;\n for (;length > index; index++) if (NO_HOLES || index in self) {\n value = self[index];\n result = boundFunction(value, index, O);\n if (TYPE) {\n if (IS_MAP) target[index] = result; // map\n else if (result) switch (TYPE) {\n case 3: return true; // some\n case 5: return value; // find\n case 6: return index; // findIndex\n case 2: push.call(target, value); // filter\n } else if (IS_EVERY) return false; // every\n }\n }\n return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.forEach` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.foreach\n forEach: createMethod(0),\n // `Array.prototype.map` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.map\n map: createMethod(1),\n // `Array.prototype.filter` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.filter\n filter: createMethod(2),\n // `Array.prototype.some` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.some\n some: createMethod(3),\n // `Array.prototype.every` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.every\n every: createMethod(4),\n // `Array.prototype.find` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.find\n find: createMethod(5),\n // `Array.prototype.findIndex` method\n // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex\n findIndex: createMethod(6)\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar has = require('../internals/has');\n\nvar defineProperty = Object.defineProperty;\nvar cache = {};\n\nvar thrower = function (it) { throw it; };\n\nmodule.exports = function (METHOD_NAME, options) {\n if (has(cache, METHOD_NAME)) return cache[METHOD_NAME];\n if (!options) options = {};\n var method = [][METHOD_NAME];\n var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false;\n var argument0 = has(options, 0) ? options[0] : thrower;\n var argument1 = has(options, 1) ? options[1] : undefined;\n\n return cache[METHOD_NAME] = !!method && !fails(function () {\n if (ACCESSORS && !DESCRIPTORS) return true;\n var O = { length: -1 };\n\n if (ACCESSORS) defineProperty(O, 1, { enumerable: true, get: thrower });\n else O[1] = 1;\n\n method.call(O, argument0, argument1);\n });\n};\n","var classof = require('../internals/classof-raw');\n\n// `IsArray` abstract operation\n// https://tc39.github.io/ecma262/#sec-isarray\nmodule.exports = Array.isArray || function isArray(arg) {\n return classof(arg) == 'Array';\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar $find = require('../internals/array-iteration').find;\nvar addToUnscopables = require('../internals/add-to-unscopables');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar FIND = 'find';\nvar SKIPS_HOLES = true;\n\nvar USES_TO_LENGTH = arrayMethodUsesToLength(FIND);\n\n// Shouldn't skip holes\nif (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });\n\n// `Array.prototype.find` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.find\n$({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH }, {\n find: function find(callbackfn /* , that = undefined */) {\n return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables(FIND);\n","var global = require('../internals/global');\nvar bind = require('../internals/function-bind-context');\n\nvar call = Function.call;\n\nmodule.exports = function (CONSTRUCTOR, METHOD, length) {\n return bind(call, global[CONSTRUCTOR].prototype[METHOD], length);\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar $findIndex = require('../internals/array-iteration').findIndex;\nvar addToUnscopables = require('../internals/add-to-unscopables');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar FIND_INDEX = 'findIndex';\nvar SKIPS_HOLES = true;\n\nvar USES_TO_LENGTH = arrayMethodUsesToLength(FIND_INDEX);\n\n// Shouldn't skip holes\nif (FIND_INDEX in []) Array(1)[FIND_INDEX](function () { SKIPS_HOLES = false; });\n\n// `Array.prototype.findIndex` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.findindex\n$({ target: 'Array', proto: true, forced: SKIPS_HOLES || !USES_TO_LENGTH }, {\n findIndex: function findIndex(callbackfn /* , that = undefined */) {\n return $findIndex(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n\n// https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables(FIND_INDEX);\n","require('../../modules/es.array.find');\nvar entryUnbind = require('../../internals/entry-unbind');\n\nmodule.exports = entryUnbind('Array', 'find');\n","'use strict';\nvar toPrimitive = require('../internals/to-primitive');\nvar definePropertyModule = require('../internals/object-define-property');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\n\nmodule.exports = function (object, key, value) {\n var propertyKey = toPrimitive(key);\n if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));\n else object[propertyKey] = value;\n};\n","require('../../modules/es.array.find-index');\nvar entryUnbind = require('../../internals/entry-unbind');\n\nmodule.exports = entryUnbind('Array', 'findIndex');\n","var $ = require('../internals/export');\nvar from = require('../internals/array-from');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\n\nvar INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {\n Array.from(iterable);\n});\n\n// `Array.from` method\n// https://tc39.github.io/ecma262/#sec-array.from\n$({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {\n from: from\n});\n","'use strict';\nvar bind = require('../internals/function-bind-context');\nvar toObject = require('../internals/to-object');\nvar callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');\nvar isArrayIteratorMethod = require('../internals/is-array-iterator-method');\nvar toLength = require('../internals/to-length');\nvar createProperty = require('../internals/create-property');\nvar getIteratorMethod = require('../internals/get-iterator-method');\n\n// `Array.from` method implementation\n// https://tc39.github.io/ecma262/#sec-array.from\nmodule.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {\n var O = toObject(arrayLike);\n var C = typeof this == 'function' ? this : Array;\n var argumentsLength = arguments.length;\n var mapfn = argumentsLength > 1 ? arguments[1] : undefined;\n var mapping = mapfn !== undefined;\n var iteratorMethod = getIteratorMethod(O);\n var index = 0;\n var length, result, step, iterator, next, value;\n if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2);\n // if the target is not iterable or it's an array with the default iterator - use a simple case\n if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {\n iterator = iteratorMethod.call(O);\n next = iterator.next;\n result = new C();\n for (;!(step = next.call(iterator)).done; index++) {\n value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;\n createProperty(result, index, value);\n }\n } else {\n length = toLength(O.length);\n result = new C(length);\n for (;length > index; index++) {\n value = mapping ? mapfn(O[index], index) : O[index];\n createProperty(result, index, value);\n }\n }\n result.length = index;\n return result;\n};\n","require('../../modules/es.string.iterator');\nrequire('../../modules/es.array.from');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Array.from;\n","'use strict';\nvar fails = require('../internals/fails');\n\nmodule.exports = function (METHOD_NAME, argument) {\n var method = [][METHOD_NAME];\n return !!method && fails(function () {\n // eslint-disable-next-line no-useless-call,no-throw-literal\n method.call(null, argument || function () { throw 1; }, 1);\n });\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar $some = require('../internals/array-iteration').some;\nvar arrayMethodIsStrict = require('../internals/array-method-is-strict');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar STRICT_METHOD = arrayMethodIsStrict('some');\nvar USES_TO_LENGTH = arrayMethodUsesToLength('some');\n\n// `Array.prototype.some` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.some\n$({ target: 'Array', proto: true, forced: !STRICT_METHOD || !USES_TO_LENGTH }, {\n some: function some(callbackfn /* , thisArg */) {\n return $some(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n","require('../../modules/es.array.some');\nvar entryUnbind = require('../../internals/entry-unbind');\n\nmodule.exports = entryUnbind('Array', 'some');\n","'use strict';\nvar NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar isObject = require('../internals/is-object');\nvar has = require('../internals/has');\nvar classof = require('../internals/classof');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar defineProperty = require('../internals/object-define-property').f;\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar uid = require('../internals/uid');\n\nvar Int8Array = global.Int8Array;\nvar Int8ArrayPrototype = Int8Array && Int8Array.prototype;\nvar Uint8ClampedArray = global.Uint8ClampedArray;\nvar Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;\nvar TypedArray = Int8Array && getPrototypeOf(Int8Array);\nvar TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);\nvar ObjectPrototype = Object.prototype;\nvar isPrototypeOf = ObjectPrototype.isPrototypeOf;\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');\n// Fixing native typed arrays in Opera Presto crashes the browser, see #595\nvar NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';\nvar TYPED_ARRAY_TAG_REQIRED = false;\nvar NAME;\n\nvar TypedArrayConstructorsList = {\n Int8Array: 1,\n Uint8Array: 1,\n Uint8ClampedArray: 1,\n Int16Array: 2,\n Uint16Array: 2,\n Int32Array: 4,\n Uint32Array: 4,\n Float32Array: 4,\n Float64Array: 8\n};\n\nvar isView = function isView(it) {\n var klass = classof(it);\n return klass === 'DataView' || has(TypedArrayConstructorsList, klass);\n};\n\nvar isTypedArray = function (it) {\n return isObject(it) && has(TypedArrayConstructorsList, classof(it));\n};\n\nvar aTypedArray = function (it) {\n if (isTypedArray(it)) return it;\n throw TypeError('Target is not a typed array');\n};\n\nvar aTypedArrayConstructor = function (C) {\n if (setPrototypeOf) {\n if (isPrototypeOf.call(TypedArray, C)) return C;\n } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) {\n var TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) {\n return C;\n }\n } throw TypeError('Target is not a typed array constructor');\n};\n\nvar exportTypedArrayMethod = function (KEY, property, forced) {\n if (!DESCRIPTORS) return;\n if (forced) for (var ARRAY in TypedArrayConstructorsList) {\n var TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) {\n delete TypedArrayConstructor.prototype[KEY];\n }\n }\n if (!TypedArrayPrototype[KEY] || forced) {\n redefine(TypedArrayPrototype, KEY, forced ? property\n : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property);\n }\n};\n\nvar exportTypedArrayStaticMethod = function (KEY, property, forced) {\n var ARRAY, TypedArrayConstructor;\n if (!DESCRIPTORS) return;\n if (setPrototypeOf) {\n if (forced) for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) {\n delete TypedArrayConstructor[KEY];\n }\n }\n if (!TypedArray[KEY] || forced) {\n // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable\n try {\n return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property);\n } catch (error) { /* empty */ }\n } else return;\n }\n for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {\n redefine(TypedArrayConstructor, KEY, property);\n }\n }\n};\n\nfor (NAME in TypedArrayConstructorsList) {\n if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false;\n}\n\n// WebKit bug - typed arrays constructors prototype is Object.prototype\nif (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) {\n // eslint-disable-next-line no-shadow\n TypedArray = function TypedArray() {\n throw TypeError('Incorrect invocation');\n };\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);\n }\n}\n\nif (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {\n TypedArrayPrototype = TypedArray.prototype;\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);\n }\n}\n\n// WebKit bug - one more object in Uint8ClampedArray prototype chain\nif (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {\n setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);\n}\n\nif (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) {\n TYPED_ARRAY_TAG_REQIRED = true;\n defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {\n return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;\n } });\n for (NAME in TypedArrayConstructorsList) if (global[NAME]) {\n createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);\n }\n}\n\nmodule.exports = {\n NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,\n TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,\n aTypedArray: aTypedArray,\n aTypedArrayConstructor: aTypedArrayConstructor,\n exportTypedArrayMethod: exportTypedArrayMethod,\n exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,\n isView: isView,\n isTypedArray: isTypedArray,\n TypedArray: TypedArray,\n TypedArrayPrototype: TypedArrayPrototype\n};\n","module.exports = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined';\n","'use strict';\nvar global = require('../internals/global');\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar ArrayIterators = require('../modules/es.array.iterator');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar Uint8Array = global.Uint8Array;\nvar arrayValues = ArrayIterators.values;\nvar arrayKeys = ArrayIterators.keys;\nvar arrayEntries = ArrayIterators.entries;\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar nativeTypedArrayIterator = Uint8Array && Uint8Array.prototype[ITERATOR];\n\nvar CORRECT_ITER_NAME = !!nativeTypedArrayIterator\n && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined);\n\nvar typedArrayValues = function values() {\n return arrayValues.call(aTypedArray(this));\n};\n\n// `%TypedArray%.prototype.entries` method\n// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.entries\nexportTypedArrayMethod('entries', function entries() {\n return arrayEntries.call(aTypedArray(this));\n});\n// `%TypedArray%.prototype.keys` method\n// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.keys\nexportTypedArrayMethod('keys', function keys() {\n return arrayKeys.call(aTypedArray(this));\n});\n// `%TypedArray%.prototype.values` method\n// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.values\nexportTypedArrayMethod('values', typedArrayValues, !CORRECT_ITER_NAME);\n// `%TypedArray%.prototype[@@iterator]` method\n// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype-@@iterator\nexportTypedArrayMethod(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME);\n","'use strict';\nvar DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar objectKeys = require('../internals/object-keys');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar toObject = require('../internals/to-object');\nvar IndexedObject = require('../internals/indexed-object');\n\nvar nativeAssign = Object.assign;\nvar defineProperty = Object.defineProperty;\n\n// `Object.assign` method\n// https://tc39.github.io/ecma262/#sec-object.assign\nmodule.exports = !nativeAssign || fails(function () {\n // should have correct order of operations (Edge bug)\n if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', {\n enumerable: true,\n get: function () {\n defineProperty(this, 'b', {\n value: 3,\n enumerable: false\n });\n }\n }), { b: 2 })).b !== 1) return true;\n // should work with symbols and should have deterministic property order (V8 bug)\n var A = {};\n var B = {};\n // eslint-disable-next-line no-undef\n var symbol = Symbol();\n var alphabet = 'abcdefghijklmnopqrst';\n A[symbol] = 7;\n alphabet.split('').forEach(function (chr) { B[chr] = chr; });\n return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;\n}) ? function assign(target, source) { // eslint-disable-line no-unused-vars\n var T = toObject(target);\n var argumentsLength = arguments.length;\n var index = 1;\n var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;\n var propertyIsEnumerable = propertyIsEnumerableModule.f;\n while (argumentsLength > index) {\n var S = IndexedObject(arguments[index++]);\n var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);\n var length = keys.length;\n var j = 0;\n var key;\n while (length > j) {\n key = keys[j++];\n if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];\n }\n } return T;\n} : nativeAssign;\n","var $ = require('../internals/export');\nvar assign = require('../internals/object-assign');\n\n// `Object.assign` method\n// https://tc39.github.io/ecma262/#sec-object.assign\n$({ target: 'Object', stat: true, forced: Object.assign !== assign }, {\n assign: assign\n});\n","require('../../modules/es.object.assign');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Object.assign;\n","var DESCRIPTORS = require('../internals/descriptors');\nvar objectKeys = require('../internals/object-keys');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar propertyIsEnumerable = require('../internals/object-property-is-enumerable').f;\n\n// `Object.{ entries, values }` methods implementation\nvar createMethod = function (TO_ENTRIES) {\n return function (it) {\n var O = toIndexedObject(it);\n var keys = objectKeys(O);\n var length = keys.length;\n var i = 0;\n var result = [];\n var key;\n while (length > i) {\n key = keys[i++];\n if (!DESCRIPTORS || propertyIsEnumerable.call(O, key)) {\n result.push(TO_ENTRIES ? [key, O[key]] : O[key]);\n }\n }\n return result;\n };\n};\n\nmodule.exports = {\n // `Object.entries` method\n // https://tc39.github.io/ecma262/#sec-object.entries\n entries: createMethod(true),\n // `Object.values` method\n // https://tc39.github.io/ecma262/#sec-object.values\n values: createMethod(false)\n};\n","var $ = require('../internals/export');\nvar $entries = require('../internals/object-to-array').entries;\n\n// `Object.entries` method\n// https://tc39.github.io/ecma262/#sec-object.entries\n$({ target: 'Object', stat: true }, {\n entries: function entries(O) {\n return $entries(O);\n }\n});\n","require('../../modules/es.object.entries');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Object.entries;\n","var $ = require('../internals/export');\nvar $values = require('../internals/object-to-array').values;\n\n// `Object.values` method\n// https://tc39.github.io/ecma262/#sec-object.values\n$({ target: 'Object', stat: true }, {\n values: function values(O) {\n return $values(O);\n }\n});\n","require('../../modules/es.object.values');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Object.values;\n","var isRegExp = require('../internals/is-regexp');\n\nmodule.exports = function (it) {\n if (isRegExp(it)) {\n throw TypeError(\"The method doesn't accept regular expressions\");\n } return it;\n};\n","var isObject = require('../internals/is-object');\nvar classof = require('../internals/classof-raw');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar MATCH = wellKnownSymbol('match');\n\n// `IsRegExp` abstract operation\n// https://tc39.github.io/ecma262/#sec-isregexp\nmodule.exports = function (it) {\n var isRegExp;\n return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp');\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar MATCH = wellKnownSymbol('match');\n\nmodule.exports = function (METHOD_NAME) {\n var regexp = /./;\n try {\n '/./'[METHOD_NAME](regexp);\n } catch (e) {\n try {\n regexp[MATCH] = false;\n return '/./'[METHOD_NAME](regexp);\n } catch (f) { /* empty */ }\n } return false;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar notARegExp = require('../internals/not-a-regexp');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\nvar correctIsRegExpLogic = require('../internals/correct-is-regexp-logic');\n\n// `String.prototype.includes` method\n// https://tc39.github.io/ecma262/#sec-string.prototype.includes\n$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, {\n includes: function includes(searchString /* , position = 0 */) {\n return !!~String(requireObjectCoercible(this))\n .indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n","require('../../modules/es.string.includes');\nvar entryUnbind = require('../../internals/entry-unbind');\n\nmodule.exports = entryUnbind('String', 'includes');\n","'use strict';\nvar $ = require('../internals/export');\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar toLength = require('../internals/to-length');\nvar notARegExp = require('../internals/not-a-regexp');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\nvar correctIsRegExpLogic = require('../internals/correct-is-regexp-logic');\nvar IS_PURE = require('../internals/is-pure');\n\nvar nativeStartsWith = ''.startsWith;\nvar min = Math.min;\n\nvar CORRECT_IS_REGEXP_LOGIC = correctIsRegExpLogic('startsWith');\n// https://github.com/zloirock/core-js/pull/702\nvar MDN_POLYFILL_BUG = !IS_PURE && !CORRECT_IS_REGEXP_LOGIC && !!function () {\n var descriptor = getOwnPropertyDescriptor(String.prototype, 'startsWith');\n return descriptor && !descriptor.writable;\n}();\n\n// `String.prototype.startsWith` method\n// https://tc39.github.io/ecma262/#sec-string.prototype.startswith\n$({ target: 'String', proto: true, forced: !MDN_POLYFILL_BUG && !CORRECT_IS_REGEXP_LOGIC }, {\n startsWith: function startsWith(searchString /* , position = 0 */) {\n var that = String(requireObjectCoercible(this));\n notARegExp(searchString);\n var index = toLength(min(arguments.length > 1 ? arguments[1] : undefined, that.length));\n var search = String(searchString);\n return nativeStartsWith\n ? nativeStartsWith.call(that, search, index)\n : that.slice(index, index + search.length) === search;\n }\n});\n","require('../../modules/es.string.starts-with');\nvar entryUnbind = require('../../internals/entry-unbind');\n\nmodule.exports = entryUnbind('String', 'startsWith');\n","var $ = require('../internals/export');\nvar repeat = require('../internals/string-repeat');\n\n// `String.prototype.repeat` method\n// https://tc39.github.io/ecma262/#sec-string.prototype.repeat\n$({ target: 'String', proto: true }, {\n repeat: repeat\n});\n","'use strict';\nvar toInteger = require('../internals/to-integer');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `String.prototype.repeat` method implementation\n// https://tc39.github.io/ecma262/#sec-string.prototype.repeat\nmodule.exports = ''.repeat || function repeat(count) {\n var str = String(requireObjectCoercible(this));\n var result = '';\n var n = toInteger(count);\n if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions');\n for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;\n return result;\n};\n","require('../../modules/es.string.repeat');\nvar entryUnbind = require('../../internals/entry-unbind');\n\nmodule.exports = entryUnbind('String', 'repeat');\n","'use strict';\nvar $ = require('../internals/export');\nvar fails = require('../internals/fails');\nvar isArray = require('../internals/is-array');\nvar isObject = require('../internals/is-object');\nvar toObject = require('../internals/to-object');\nvar toLength = require('../internals/to-length');\nvar createProperty = require('../internals/create-property');\nvar arraySpeciesCreate = require('../internals/array-species-create');\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');\nvar MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;\nvar MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';\n\n// We can't use this feature detection in V8 since it causes\n// deoptimization and serious performance degradation\n// https://github.com/zloirock/core-js/issues/679\nvar IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {\n var array = [];\n array[IS_CONCAT_SPREADABLE] = false;\n return array.concat()[0] !== array;\n});\n\nvar SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');\n\nvar isConcatSpreadable = function (O) {\n if (!isObject(O)) return false;\n var spreadable = O[IS_CONCAT_SPREADABLE];\n return spreadable !== undefined ? !!spreadable : isArray(O);\n};\n\nvar FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;\n\n// `Array.prototype.concat` method\n// https://tc39.github.io/ecma262/#sec-array.prototype.concat\n// with adding support of @@isConcatSpreadable and @@species\n$({ target: 'Array', proto: true, forced: FORCED }, {\n concat: function concat(arg) { // eslint-disable-line no-unused-vars\n var O = toObject(this);\n var A = arraySpeciesCreate(O, 0);\n var n = 0;\n var i, k, length, len, E;\n for (i = -1, length = arguments.length; i < length; i++) {\n E = i === -1 ? O : arguments[i];\n if (isConcatSpreadable(E)) {\n len = toLength(E.length);\n if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);\n for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);\n } else {\n if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);\n createProperty(A, n++, E);\n }\n }\n A.length = n;\n return A;\n }\n});\n","var fails = require('../internals/fails');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar SPECIES = wellKnownSymbol('species');\n\nmodule.exports = function (METHOD_NAME) {\n // We can't use this feature detection in V8 since it causes\n // deoptimization and serious performance degradation\n // https://github.com/zloirock/core-js/issues/677\n return V8_VERSION >= 51 || !fails(function () {\n var array = [];\n var constructor = array.constructor = {};\n constructor[SPECIES] = function () {\n return { foo: 1 };\n };\n return array[METHOD_NAME](Boolean).foo !== 1;\n });\n};\n","var path = require('../internals/path');\nvar has = require('../internals/has');\nvar wrappedWellKnownSymbolModule = require('../internals/well-known-symbol-wrapped');\nvar defineProperty = require('../internals/object-define-property').f;\n\nmodule.exports = function (NAME) {\n var Symbol = path.Symbol || (path.Symbol = {});\n if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {\n value: wrappedWellKnownSymbolModule.f(NAME)\n });\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar getBuiltIn = require('../internals/get-built-in');\nvar IS_PURE = require('../internals/is-pure');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar NATIVE_SYMBOL = require('../internals/native-symbol');\nvar USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid');\nvar fails = require('../internals/fails');\nvar has = require('../internals/has');\nvar isArray = require('../internals/is-array');\nvar isObject = require('../internals/is-object');\nvar anObject = require('../internals/an-object');\nvar toObject = require('../internals/to-object');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toPrimitive = require('../internals/to-primitive');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar nativeObjectCreate = require('../internals/object-create');\nvar objectKeys = require('../internals/object-keys');\nvar getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');\nvar getOwnPropertyNamesExternal = require('../internals/object-get-own-property-names-external');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar definePropertyModule = require('../internals/object-define-property');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar shared = require('../internals/shared');\nvar sharedKey = require('../internals/shared-key');\nvar hiddenKeys = require('../internals/hidden-keys');\nvar uid = require('../internals/uid');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar wrappedWellKnownSymbolModule = require('../internals/well-known-symbol-wrapped');\nvar defineWellKnownSymbol = require('../internals/define-well-known-symbol');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar InternalStateModule = require('../internals/internal-state');\nvar $forEach = require('../internals/array-iteration').forEach;\n\nvar HIDDEN = sharedKey('hidden');\nvar SYMBOL = 'Symbol';\nvar PROTOTYPE = 'prototype';\nvar TO_PRIMITIVE = wellKnownSymbol('toPrimitive');\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(SYMBOL);\nvar ObjectPrototype = Object[PROTOTYPE];\nvar $Symbol = global.Symbol;\nvar $stringify = getBuiltIn('JSON', 'stringify');\nvar nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\nvar nativeDefineProperty = definePropertyModule.f;\nvar nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;\nvar nativePropertyIsEnumerable = propertyIsEnumerableModule.f;\nvar AllSymbols = shared('symbols');\nvar ObjectPrototypeSymbols = shared('op-symbols');\nvar StringToSymbolRegistry = shared('string-to-symbol-registry');\nvar SymbolToStringRegistry = shared('symbol-to-string-registry');\nvar WellKnownSymbolsStore = shared('wks');\nvar QObject = global.QObject;\n// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173\nvar USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;\n\n// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687\nvar setSymbolDescriptor = DESCRIPTORS && fails(function () {\n return nativeObjectCreate(nativeDefineProperty({}, 'a', {\n get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }\n })).a != 7;\n}) ? function (O, P, Attributes) {\n var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);\n if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];\n nativeDefineProperty(O, P, Attributes);\n if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {\n nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);\n }\n} : nativeDefineProperty;\n\nvar wrap = function (tag, description) {\n var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]);\n setInternalState(symbol, {\n type: SYMBOL,\n tag: tag,\n description: description\n });\n if (!DESCRIPTORS) symbol.description = description;\n return symbol;\n};\n\nvar isSymbol = USE_SYMBOL_AS_UID ? function (it) {\n return typeof it == 'symbol';\n} : function (it) {\n return Object(it) instanceof $Symbol;\n};\n\nvar $defineProperty = function defineProperty(O, P, Attributes) {\n if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);\n anObject(O);\n var key = toPrimitive(P, true);\n anObject(Attributes);\n if (has(AllSymbols, key)) {\n if (!Attributes.enumerable) {\n if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));\n O[HIDDEN][key] = true;\n } else {\n if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;\n Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });\n } return setSymbolDescriptor(O, key, Attributes);\n } return nativeDefineProperty(O, key, Attributes);\n};\n\nvar $defineProperties = function defineProperties(O, Properties) {\n anObject(O);\n var properties = toIndexedObject(Properties);\n var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));\n $forEach(keys, function (key) {\n if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);\n });\n return O;\n};\n\nvar $create = function create(O, Properties) {\n return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);\n};\n\nvar $propertyIsEnumerable = function propertyIsEnumerable(V) {\n var P = toPrimitive(V, true);\n var enumerable = nativePropertyIsEnumerable.call(this, P);\n if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;\n return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;\n};\n\nvar $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {\n var it = toIndexedObject(O);\n var key = toPrimitive(P, true);\n if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;\n var descriptor = nativeGetOwnPropertyDescriptor(it, key);\n if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {\n descriptor.enumerable = true;\n }\n return descriptor;\n};\n\nvar $getOwnPropertyNames = function getOwnPropertyNames(O) {\n var names = nativeGetOwnPropertyNames(toIndexedObject(O));\n var result = [];\n $forEach(names, function (key) {\n if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);\n });\n return result;\n};\n\nvar $getOwnPropertySymbols = function getOwnPropertySymbols(O) {\n var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;\n var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));\n var result = [];\n $forEach(names, function (key) {\n if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {\n result.push(AllSymbols[key]);\n }\n });\n return result;\n};\n\n// `Symbol` constructor\n// https://tc39.github.io/ecma262/#sec-symbol-constructor\nif (!NATIVE_SYMBOL) {\n $Symbol = function Symbol() {\n if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');\n var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);\n var tag = uid(description);\n var setter = function (value) {\n if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);\n if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;\n setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));\n };\n if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });\n return wrap(tag, description);\n };\n\n redefine($Symbol[PROTOTYPE], 'toString', function toString() {\n return getInternalState(this).tag;\n });\n\n redefine($Symbol, 'withoutSetter', function (description) {\n return wrap(uid(description), description);\n });\n\n propertyIsEnumerableModule.f = $propertyIsEnumerable;\n definePropertyModule.f = $defineProperty;\n getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor;\n getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;\n getOwnPropertySymbolsModule.f = $getOwnPropertySymbols;\n\n wrappedWellKnownSymbolModule.f = function (name) {\n return wrap(wellKnownSymbol(name), name);\n };\n\n if (DESCRIPTORS) {\n // https://github.com/tc39/proposal-Symbol-description\n nativeDefineProperty($Symbol[PROTOTYPE], 'description', {\n configurable: true,\n get: function description() {\n return getInternalState(this).description;\n }\n });\n if (!IS_PURE) {\n redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });\n }\n }\n}\n\n$({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, {\n Symbol: $Symbol\n});\n\n$forEach(objectKeys(WellKnownSymbolsStore), function (name) {\n defineWellKnownSymbol(name);\n});\n\n$({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, {\n // `Symbol.for` method\n // https://tc39.github.io/ecma262/#sec-symbol.for\n 'for': function (key) {\n var string = String(key);\n if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];\n var symbol = $Symbol(string);\n StringToSymbolRegistry[string] = symbol;\n SymbolToStringRegistry[symbol] = string;\n return symbol;\n },\n // `Symbol.keyFor` method\n // https://tc39.github.io/ecma262/#sec-symbol.keyfor\n keyFor: function keyFor(sym) {\n if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');\n if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];\n },\n useSetter: function () { USE_SETTER = true; },\n useSimple: function () { USE_SETTER = false; }\n});\n\n$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, {\n // `Object.create` method\n // https://tc39.github.io/ecma262/#sec-object.create\n create: $create,\n // `Object.defineProperty` method\n // https://tc39.github.io/ecma262/#sec-object.defineproperty\n defineProperty: $defineProperty,\n // `Object.defineProperties` method\n // https://tc39.github.io/ecma262/#sec-object.defineproperties\n defineProperties: $defineProperties,\n // `Object.getOwnPropertyDescriptor` method\n // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors\n getOwnPropertyDescriptor: $getOwnPropertyDescriptor\n});\n\n$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, {\n // `Object.getOwnPropertyNames` method\n // https://tc39.github.io/ecma262/#sec-object.getownpropertynames\n getOwnPropertyNames: $getOwnPropertyNames,\n // `Object.getOwnPropertySymbols` method\n // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols\n getOwnPropertySymbols: $getOwnPropertySymbols\n});\n\n// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives\n// https://bugs.chromium.org/p/v8/issues/detail?id=3443\n$({ target: 'Object', stat: true, forced: fails(function () { getOwnPropertySymbolsModule.f(1); }) }, {\n getOwnPropertySymbols: function getOwnPropertySymbols(it) {\n return getOwnPropertySymbolsModule.f(toObject(it));\n }\n});\n\n// `JSON.stringify` method behavior with symbols\n// https://tc39.github.io/ecma262/#sec-json.stringify\nif ($stringify) {\n var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () {\n var symbol = $Symbol();\n // MS Edge converts symbol values to JSON as {}\n return $stringify([symbol]) != '[null]'\n // WebKit converts symbol values to JSON as null\n || $stringify({ a: symbol }) != '{}'\n // V8 throws on boxed symbols\n || $stringify(Object(symbol)) != '{}';\n });\n\n $({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {\n // eslint-disable-next-line no-unused-vars\n stringify: function stringify(it, replacer, space) {\n var args = [it];\n var index = 1;\n var $replacer;\n while (arguments.length > index) args.push(arguments[index++]);\n $replacer = replacer;\n if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined\n if (!isArray(replacer)) replacer = function (key, value) {\n if (typeof $replacer == 'function') value = $replacer.call(this, key, value);\n if (!isSymbol(value)) return value;\n };\n args[1] = replacer;\n return $stringify.apply(null, args);\n }\n });\n}\n\n// `Symbol.prototype[@@toPrimitive]` method\n// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive\nif (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) {\n createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);\n}\n// `Symbol.prototype[@@toStringTag]` property\n// https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag\nsetToStringTag($Symbol, SYMBOL);\n\nhiddenKeys[HIDDEN] = true;\n","var toIndexedObject = require('../internals/to-indexed-object');\nvar nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names').f;\n\nvar toString = {}.toString;\n\nvar windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames\n ? Object.getOwnPropertyNames(window) : [];\n\nvar getWindowNames = function (it) {\n try {\n return nativeGetOwnPropertyNames(it);\n } catch (error) {\n return windowNames.slice();\n }\n};\n\n// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window\nmodule.exports.f = function getOwnPropertyNames(it) {\n return windowNames && toString.call(it) == '[object Window]'\n ? getWindowNames(it)\n : nativeGetOwnPropertyNames(toIndexedObject(it));\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nexports.f = wellKnownSymbol;\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.asyncIterator` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.asynciterator\ndefineWellKnownSymbol('asyncIterator');\n","// `Symbol.prototype.description` getter\n// https://tc39.github.io/ecma262/#sec-symbol.prototype.description\n'use strict';\nvar $ = require('../internals/export');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar has = require('../internals/has');\nvar isObject = require('../internals/is-object');\nvar defineProperty = require('../internals/object-define-property').f;\nvar copyConstructorProperties = require('../internals/copy-constructor-properties');\n\nvar NativeSymbol = global.Symbol;\n\nif (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||\n // Safari 12 bug\n NativeSymbol().description !== undefined\n)) {\n var EmptyStringDescriptionStore = {};\n // wrap Symbol constructor for correct work with undefined description\n var SymbolWrapper = function Symbol() {\n var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);\n var result = this instanceof SymbolWrapper\n ? new NativeSymbol(description)\n // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'\n : description === undefined ? NativeSymbol() : NativeSymbol(description);\n if (description === '') EmptyStringDescriptionStore[result] = true;\n return result;\n };\n copyConstructorProperties(SymbolWrapper, NativeSymbol);\n var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;\n symbolPrototype.constructor = SymbolWrapper;\n\n var symbolToString = symbolPrototype.toString;\n var native = String(NativeSymbol('test')) == 'Symbol(test)';\n var regexp = /^Symbol\\((.*)\\)[^)]+$/;\n defineProperty(symbolPrototype, 'description', {\n configurable: true,\n get: function description() {\n var symbol = isObject(this) ? this.valueOf() : this;\n var string = symbolToString.call(symbol);\n if (has(EmptyStringDescriptionStore, symbol)) return '';\n var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');\n return desc === '' ? undefined : desc;\n }\n });\n\n $({ global: true, forced: true }, {\n Symbol: SymbolWrapper\n });\n}\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.hasInstance` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.hasinstance\ndefineWellKnownSymbol('hasInstance');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.isConcatSpreadable` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.isconcatspreadable\ndefineWellKnownSymbol('isConcatSpreadable');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.iterator` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.iterator\ndefineWellKnownSymbol('iterator');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.match` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.match\ndefineWellKnownSymbol('match');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.matchAll` well-known symbol\ndefineWellKnownSymbol('matchAll');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.replace` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.replace\ndefineWellKnownSymbol('replace');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.search` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.search\ndefineWellKnownSymbol('search');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.species` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.species\ndefineWellKnownSymbol('species');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.split` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.split\ndefineWellKnownSymbol('split');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.toPrimitive` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.toprimitive\ndefineWellKnownSymbol('toPrimitive');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.toStringTag` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.tostringtag\ndefineWellKnownSymbol('toStringTag');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.unscopables` well-known symbol\n// https://tc39.github.io/ecma262/#sec-symbol.unscopables\ndefineWellKnownSymbol('unscopables');\n","var setToStringTag = require('../internals/set-to-string-tag');\n\n// Math[@@toStringTag] property\n// https://tc39.github.io/ecma262/#sec-math-@@tostringtag\nsetToStringTag(Math, 'Math', true);\n","var global = require('../internals/global');\nvar setToStringTag = require('../internals/set-to-string-tag');\n\n// JSON[@@toStringTag] property\n// https://tc39.github.io/ecma262/#sec-json-@@tostringtag\nsetToStringTag(global.JSON, 'JSON', true);\n","require('../../modules/es.array.concat');\nrequire('../../modules/es.object.to-string');\nrequire('../../modules/es.symbol');\nrequire('../../modules/es.symbol.async-iterator');\nrequire('../../modules/es.symbol.description');\nrequire('../../modules/es.symbol.has-instance');\nrequire('../../modules/es.symbol.is-concat-spreadable');\nrequire('../../modules/es.symbol.iterator');\nrequire('../../modules/es.symbol.match');\nrequire('../../modules/es.symbol.match-all');\nrequire('../../modules/es.symbol.replace');\nrequire('../../modules/es.symbol.search');\nrequire('../../modules/es.symbol.species');\nrequire('../../modules/es.symbol.split');\nrequire('../../modules/es.symbol.to-primitive');\nrequire('../../modules/es.symbol.to-string-tag');\nrequire('../../modules/es.symbol.unscopables');\nrequire('../../modules/es.math.to-string-tag');\nrequire('../../modules/es.json.to-string-tag');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Symbol;\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.asyncDispose` well-known symbol\n// https://github.com/tc39/proposal-using-statement\ndefineWellKnownSymbol('asyncDispose');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.dispose` well-known symbol\n// https://github.com/tc39/proposal-using-statement\ndefineWellKnownSymbol('dispose');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.observable` well-known symbol\n// https://github.com/tc39/proposal-observable\ndefineWellKnownSymbol('observable');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.patternMatch` well-known symbol\n// https://github.com/tc39/proposal-pattern-matching\ndefineWellKnownSymbol('patternMatch');\n","// TODO: remove from `core-js@4`\nvar defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\ndefineWellKnownSymbol('replaceAll');\n","require('../../modules/es.symbol.iterator');\nrequire('../../modules/es.string.iterator');\nrequire('../../modules/web.dom-collections.iterator');\nvar WrappedWellKnownSymbolModule = require('../../internals/well-known-symbol-wrapped');\n\nmodule.exports = WrappedWellKnownSymbolModule.f('iterator');\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar isForced = require('../internals/is-forced');\nvar redefine = require('../internals/redefine');\nvar InternalMetadataModule = require('../internals/internal-metadata');\nvar iterate = require('../internals/iterate');\nvar anInstance = require('../internals/an-instance');\nvar isObject = require('../internals/is-object');\nvar fails = require('../internals/fails');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar inheritIfRequired = require('../internals/inherit-if-required');\n\nmodule.exports = function (CONSTRUCTOR_NAME, wrapper, common) {\n var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;\n var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;\n var ADDER = IS_MAP ? 'set' : 'add';\n var NativeConstructor = global[CONSTRUCTOR_NAME];\n var NativePrototype = NativeConstructor && NativeConstructor.prototype;\n var Constructor = NativeConstructor;\n var exported = {};\n\n var fixMethod = function (KEY) {\n var nativeMethod = NativePrototype[KEY];\n redefine(NativePrototype, KEY,\n KEY == 'add' ? function add(value) {\n nativeMethod.call(this, value === 0 ? 0 : value);\n return this;\n } : KEY == 'delete' ? function (key) {\n return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);\n } : KEY == 'get' ? function get(key) {\n return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key);\n } : KEY == 'has' ? function has(key) {\n return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);\n } : function set(key, value) {\n nativeMethod.call(this, key === 0 ? 0 : key, value);\n return this;\n }\n );\n };\n\n // eslint-disable-next-line max-len\n if (isForced(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () {\n new NativeConstructor().entries().next();\n })))) {\n // create collection constructor\n Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);\n InternalMetadataModule.REQUIRED = true;\n } else if (isForced(CONSTRUCTOR_NAME, true)) {\n var instance = new Constructor();\n // early implementations not supports chaining\n var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;\n // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false\n var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });\n // most early implementations doesn't supports iterables, most modern - not close it correctly\n // eslint-disable-next-line no-new\n var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); });\n // for early implementations -0 and +0 not the same\n var BUGGY_ZERO = !IS_WEAK && fails(function () {\n // V8 ~ Chromium 42- fails only with 5+ elements\n var $instance = new NativeConstructor();\n var index = 5;\n while (index--) $instance[ADDER](index, index);\n return !$instance.has(-0);\n });\n\n if (!ACCEPT_ITERABLES) {\n Constructor = wrapper(function (dummy, iterable) {\n anInstance(dummy, Constructor, CONSTRUCTOR_NAME);\n var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor);\n if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP);\n return that;\n });\n Constructor.prototype = NativePrototype;\n NativePrototype.constructor = Constructor;\n }\n\n if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {\n fixMethod('delete');\n fixMethod('has');\n IS_MAP && fixMethod('get');\n }\n\n if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);\n\n // weak collections should not contains .clear method\n if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear;\n }\n\n exported[CONSTRUCTOR_NAME] = Constructor;\n $({ global: true, forced: Constructor != NativeConstructor }, exported);\n\n setToStringTag(Constructor, CONSTRUCTOR_NAME);\n\n if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);\n\n return Constructor;\n};\n","var isObject = require('../internals/is-object');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\n\n// makes subclassing work correct for wrapped built-ins\nmodule.exports = function ($this, dummy, Wrapper) {\n var NewTarget, NewTargetPrototype;\n if (\n // it can work only with native `setPrototypeOf`\n setPrototypeOf &&\n // we haven't completely correct pre-ES6 way for getting `new.target`, so use this\n typeof (NewTarget = dummy.constructor) == 'function' &&\n NewTarget !== Wrapper &&\n isObject(NewTargetPrototype = NewTarget.prototype) &&\n NewTargetPrototype !== Wrapper.prototype\n ) setPrototypeOf($this, NewTargetPrototype);\n return $this;\n};\n","'use strict';\n// https://tc39.github.io/proposal-setmap-offrom/\nvar aFunction = require('../internals/a-function');\nvar bind = require('../internals/function-bind-context');\nvar iterate = require('../internals/iterate');\n\nmodule.exports = function from(source /* , mapFn, thisArg */) {\n var length = arguments.length;\n var mapFn = length > 1 ? arguments[1] : undefined;\n var mapping, A, n, boundFunction;\n aFunction(this);\n mapping = mapFn !== undefined;\n if (mapping) aFunction(mapFn);\n if (source == undefined) return new this();\n A = [];\n if (mapping) {\n n = 0;\n boundFunction = bind(mapFn, length > 2 ? arguments[2] : undefined, 2);\n iterate(source, function (nextItem) {\n A.push(boundFunction(nextItem, n++));\n });\n } else {\n iterate(source, A.push, A);\n }\n return new this(A);\n};\n","var fails = require('../internals/fails');\n\nmodule.exports = !fails(function () {\n return Object.isExtensible(Object.preventExtensions({}));\n});\n","var hiddenKeys = require('../internals/hidden-keys');\nvar isObject = require('../internals/is-object');\nvar has = require('../internals/has');\nvar defineProperty = require('../internals/object-define-property').f;\nvar uid = require('../internals/uid');\nvar FREEZING = require('../internals/freezing');\n\nvar METADATA = uid('meta');\nvar id = 0;\n\nvar isExtensible = Object.isExtensible || function () {\n return true;\n};\n\nvar setMetadata = function (it) {\n defineProperty(it, METADATA, { value: {\n objectID: 'O' + ++id, // object ID\n weakData: {} // weak collections IDs\n } });\n};\n\nvar fastKey = function (it, create) {\n // return a primitive with prefix\n if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;\n if (!has(it, METADATA)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return 'F';\n // not necessary to add metadata\n if (!create) return 'E';\n // add missing metadata\n setMetadata(it);\n // return object ID\n } return it[METADATA].objectID;\n};\n\nvar getWeakData = function (it, create) {\n if (!has(it, METADATA)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return true;\n // not necessary to add metadata\n if (!create) return false;\n // add missing metadata\n setMetadata(it);\n // return the store of weak collections IDs\n } return it[METADATA].weakData;\n};\n\n// add metadata on freeze-family methods calling\nvar onFreeze = function (it) {\n if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it);\n return it;\n};\n\nvar meta = module.exports = {\n REQUIRED: false,\n fastKey: fastKey,\n getWeakData: getWeakData,\n onFreeze: onFreeze\n};\n\nhiddenKeys[METADATA] = true;\n","'use strict';\nvar defineProperty = require('../internals/object-define-property').f;\nvar create = require('../internals/object-create');\nvar redefineAll = require('../internals/redefine-all');\nvar bind = require('../internals/function-bind-context');\nvar anInstance = require('../internals/an-instance');\nvar iterate = require('../internals/iterate');\nvar defineIterator = require('../internals/define-iterator');\nvar setSpecies = require('../internals/set-species');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar fastKey = require('../internals/internal-metadata').fastKey;\nvar InternalStateModule = require('../internals/internal-state');\n\nvar setInternalState = InternalStateModule.set;\nvar internalStateGetterFor = InternalStateModule.getterFor;\n\nmodule.exports = {\n getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {\n var C = wrapper(function (that, iterable) {\n anInstance(that, C, CONSTRUCTOR_NAME);\n setInternalState(that, {\n type: CONSTRUCTOR_NAME,\n index: create(null),\n first: undefined,\n last: undefined,\n size: 0\n });\n if (!DESCRIPTORS) that.size = 0;\n if (iterable != undefined) iterate(iterable, that[ADDER], that, IS_MAP);\n });\n\n var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);\n\n var define = function (that, key, value) {\n var state = getInternalState(that);\n var entry = getEntry(that, key);\n var previous, index;\n // change existing entry\n if (entry) {\n entry.value = value;\n // create new entry\n } else {\n state.last = entry = {\n index: index = fastKey(key, true),\n key: key,\n value: value,\n previous: previous = state.last,\n next: undefined,\n removed: false\n };\n if (!state.first) state.first = entry;\n if (previous) previous.next = entry;\n if (DESCRIPTORS) state.size++;\n else that.size++;\n // add to index\n if (index !== 'F') state.index[index] = entry;\n } return that;\n };\n\n var getEntry = function (that, key) {\n var state = getInternalState(that);\n // fast case\n var index = fastKey(key);\n var entry;\n if (index !== 'F') return state.index[index];\n // frozen object case\n for (entry = state.first; entry; entry = entry.next) {\n if (entry.key == key) return entry;\n }\n };\n\n redefineAll(C.prototype, {\n // 23.1.3.1 Map.prototype.clear()\n // 23.2.3.2 Set.prototype.clear()\n clear: function clear() {\n var that = this;\n var state = getInternalState(that);\n var data = state.index;\n var entry = state.first;\n while (entry) {\n entry.removed = true;\n if (entry.previous) entry.previous = entry.previous.next = undefined;\n delete data[entry.index];\n entry = entry.next;\n }\n state.first = state.last = undefined;\n if (DESCRIPTORS) state.size = 0;\n else that.size = 0;\n },\n // 23.1.3.3 Map.prototype.delete(key)\n // 23.2.3.4 Set.prototype.delete(value)\n 'delete': function (key) {\n var that = this;\n var state = getInternalState(that);\n var entry = getEntry(that, key);\n if (entry) {\n var next = entry.next;\n var prev = entry.previous;\n delete state.index[entry.index];\n entry.removed = true;\n if (prev) prev.next = next;\n if (next) next.previous = prev;\n if (state.first == entry) state.first = next;\n if (state.last == entry) state.last = prev;\n if (DESCRIPTORS) state.size--;\n else that.size--;\n } return !!entry;\n },\n // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)\n // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)\n forEach: function forEach(callbackfn /* , that = undefined */) {\n var state = getInternalState(this);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n var entry;\n while (entry = entry ? entry.next : state.first) {\n boundFunction(entry.value, entry.key, this);\n // revert to the last existing entry\n while (entry && entry.removed) entry = entry.previous;\n }\n },\n // 23.1.3.7 Map.prototype.has(key)\n // 23.2.3.7 Set.prototype.has(value)\n has: function has(key) {\n return !!getEntry(this, key);\n }\n });\n\n redefineAll(C.prototype, IS_MAP ? {\n // 23.1.3.6 Map.prototype.get(key)\n get: function get(key) {\n var entry = getEntry(this, key);\n return entry && entry.value;\n },\n // 23.1.3.9 Map.prototype.set(key, value)\n set: function set(key, value) {\n return define(this, key === 0 ? 0 : key, value);\n }\n } : {\n // 23.2.3.1 Set.prototype.add(value)\n add: function add(value) {\n return define(this, value = value === 0 ? 0 : value, value);\n }\n });\n if (DESCRIPTORS) defineProperty(C.prototype, 'size', {\n get: function () {\n return getInternalState(this).size;\n }\n });\n return C;\n },\n setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) {\n var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator';\n var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME);\n var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME);\n // add .keys, .values, .entries, [@@iterator]\n // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11\n defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) {\n setInternalState(this, {\n type: ITERATOR_NAME,\n target: iterated,\n state: getInternalCollectionState(iterated),\n kind: kind,\n last: undefined\n });\n }, function () {\n var state = getInternalIteratorState(this);\n var kind = state.kind;\n var entry = state.last;\n // revert to the last existing entry\n while (entry && entry.removed) entry = entry.previous;\n // get next entry\n if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) {\n // or finish the iteration\n state.target = undefined;\n return { value: undefined, done: true };\n }\n // return step by kind\n if (kind == 'keys') return { value: entry.key, done: false };\n if (kind == 'values') return { value: entry.value, done: false };\n return { value: [entry.key, entry.value], done: false };\n }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);\n\n // add [@@species], 23.1.2.2, 23.2.2.2\n setSpecies(CONSTRUCTOR_NAME);\n }\n};\n","'use strict';\nvar collection = require('../internals/collection');\nvar collectionStrong = require('../internals/collection-strong');\n\n// `Map` constructor\n// https://tc39.github.io/ecma262/#sec-map-objects\nmodule.exports = collection('Map', function (init) {\n return function Map() { return init(this, arguments.length ? arguments[0] : undefined); };\n}, collectionStrong);\n","require('../../modules/es.map');\nrequire('../../modules/es.object.to-string');\nrequire('../../modules/es.string.iterator');\nrequire('../../modules/web.dom-collections.iterator');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Map;\n","var $ = require('../internals/export');\nvar from = require('../internals/collection-from');\n\n// `Map.from` method\n// https://tc39.github.io/proposal-setmap-offrom/#sec-map.from\n$({ target: 'Map', stat: true }, {\n from: from\n});\n","'use strict';\n// https://tc39.github.io/proposal-setmap-offrom/\nmodule.exports = function of() {\n var length = arguments.length;\n var A = new Array(length);\n while (length--) A[length] = arguments[length];\n return new this(A);\n};\n","var $ = require('../internals/export');\nvar of = require('../internals/collection-of');\n\n// `Map.of` method\n// https://tc39.github.io/proposal-setmap-offrom/#sec-map.of\n$({ target: 'Map', stat: true }, {\n of: of\n});\n","'use strict';\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\n\n// https://github.com/tc39/collection-methods\nmodule.exports = function (/* ...elements */) {\n var collection = anObject(this);\n var remover = aFunction(collection['delete']);\n var allDeleted = true;\n var wasDeleted;\n for (var k = 0, len = arguments.length; k < len; k++) {\n wasDeleted = remover.call(collection, arguments[k]);\n allDeleted = allDeleted && wasDeleted;\n }\n return !!allDeleted;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar collectionDeleteAll = require('../internals/collection-delete-all');\n\n// `Map.prototype.deleteAll` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n deleteAll: function deleteAll(/* ...elements */) {\n return collectionDeleteAll.apply(this, arguments);\n }\n});\n","var IS_PURE = require('../internals/is-pure');\nvar getIterator = require('../internals/get-iterator');\n\nmodule.exports = IS_PURE ? getIterator : function (it) {\n // eslint-disable-next-line no-undef\n return Map.prototype.entries.call(it);\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar bind = require('../internals/function-bind-context');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.every` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n every: function every(callbackfn /* , thisArg */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n return !iterate(iterator, function (key, value) {\n if (!boundFunction(value, key, map)) return iterate.stop();\n }, undefined, true, true).stopped;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar bind = require('../internals/function-bind-context');\nvar speciesConstructor = require('../internals/species-constructor');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.filter` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n filter: function filter(callbackfn /* , thisArg */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n var newMap = new (speciesConstructor(map, getBuiltIn('Map')))();\n var setter = aFunction(newMap.set);\n iterate(iterator, function (key, value) {\n if (boundFunction(value, key, map)) setter.call(newMap, key, value);\n }, undefined, true, true);\n return newMap;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar bind = require('../internals/function-bind-context');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.find` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n find: function find(callbackfn /* , thisArg */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n return iterate(iterator, function (key, value) {\n if (boundFunction(value, key, map)) return iterate.stop(value);\n }, undefined, true, true).result;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar bind = require('../internals/function-bind-context');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.findKey` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n findKey: function findKey(callbackfn /* , thisArg */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n return iterate(iterator, function (key, value) {\n if (boundFunction(value, key, map)) return iterate.stop(key);\n }, undefined, true, true).result;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar iterate = require('../internals/iterate');\nvar aFunction = require('../internals/a-function');\n\n// `Map.groupBy` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', stat: true }, {\n groupBy: function groupBy(iterable, keyDerivative) {\n var newMap = new this();\n aFunction(keyDerivative);\n var has = aFunction(newMap.has);\n var get = aFunction(newMap.get);\n var set = aFunction(newMap.set);\n iterate(iterable, function (element) {\n var derivedKey = keyDerivative(element);\n if (!has.call(newMap, derivedKey)) set.call(newMap, derivedKey, [element]);\n else get.call(newMap, derivedKey).push(element);\n });\n return newMap;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar sameValueZero = require('../internals/same-value-zero');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.includes` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n includes: function includes(searchElement) {\n return iterate(getMapIterator(anObject(this)), function (key, value) {\n if (sameValueZero(value, searchElement)) return iterate.stop();\n }, undefined, true, true).stopped;\n }\n});\n","// `SameValueZero` abstract operation\n// https://tc39.github.io/ecma262/#sec-samevaluezero\nmodule.exports = function (x, y) {\n // eslint-disable-next-line no-self-compare\n return x === y || x != x && y != y;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar iterate = require('../internals/iterate');\nvar aFunction = require('../internals/a-function');\n\n// `Map.keyBy` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', stat: true }, {\n keyBy: function keyBy(iterable, keyDerivative) {\n var newMap = new this();\n aFunction(keyDerivative);\n var setter = aFunction(newMap.set);\n iterate(iterable, function (element) {\n setter.call(newMap, keyDerivative(element), element);\n });\n return newMap;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.includes` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n keyOf: function keyOf(searchElement) {\n return iterate(getMapIterator(anObject(this)), function (key, value) {\n if (value === searchElement) return iterate.stop(key);\n }, undefined, true, true).result;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar bind = require('../internals/function-bind-context');\nvar speciesConstructor = require('../internals/species-constructor');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.mapKeys` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n mapKeys: function mapKeys(callbackfn /* , thisArg */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n var newMap = new (speciesConstructor(map, getBuiltIn('Map')))();\n var setter = aFunction(newMap.set);\n iterate(iterator, function (key, value) {\n setter.call(newMap, boundFunction(value, key, map), value);\n }, undefined, true, true);\n return newMap;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar bind = require('../internals/function-bind-context');\nvar speciesConstructor = require('../internals/species-constructor');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.mapValues` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n mapValues: function mapValues(callbackfn /* , thisArg */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n var newMap = new (speciesConstructor(map, getBuiltIn('Map')))();\n var setter = aFunction(newMap.set);\n iterate(iterator, function (key, value) {\n setter.call(newMap, key, boundFunction(value, key, map));\n }, undefined, true, true);\n return newMap;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.merge` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n // eslint-disable-next-line no-unused-vars\n merge: function merge(iterable /* ...iterbles */) {\n var map = anObject(this);\n var setter = aFunction(map.set);\n var i = 0;\n while (i < arguments.length) {\n iterate(arguments[i++], setter, map, true);\n }\n return map;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Map.prototype.reduce` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n reduce: function reduce(callbackfn /* , initialValue */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var noInitial = arguments.length < 2;\n var accumulator = noInitial ? undefined : arguments[1];\n aFunction(callbackfn);\n iterate(iterator, function (key, value) {\n if (noInitial) {\n noInitial = false;\n accumulator = value;\n } else {\n accumulator = callbackfn(accumulator, value, key, map);\n }\n }, undefined, true, true);\n if (noInitial) throw TypeError('Reduce of empty map with no initial value');\n return accumulator;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar bind = require('../internals/function-bind-context');\nvar getMapIterator = require('../internals/get-map-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.some` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n some: function some(callbackfn /* , thisArg */) {\n var map = anObject(this);\n var iterator = getMapIterator(map);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n return iterate(iterator, function (key, value) {\n if (boundFunction(value, key, map)) return iterate.stop();\n }, undefined, true, true).stopped;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\n\n// `Set.prototype.update` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n update: function update(key, callback /* , thunk */) {\n var map = anObject(this);\n var length = arguments.length;\n aFunction(callback);\n var isPresentInMap = map.has(key);\n if (!isPresentInMap && length < 3) {\n throw TypeError('Updating absent value');\n }\n var value = isPresentInMap ? map.get(key) : aFunction(length > 2 ? arguments[2] : undefined)(key, map);\n map.set(key, callback(value, key, map));\n return map;\n }\n});\n","'use strict';\nvar anObject = require('../internals/an-object');\n\n// `Map.prototype.upsert` method\n// https://github.com/thumbsupep/proposal-upsert\nmodule.exports = function upsert(key, updateFn /* , insertFn */) {\n var map = anObject(this);\n var insertFn = arguments.length > 2 ? arguments[2] : undefined;\n var value;\n if (typeof updateFn != 'function' && typeof insertFn != 'function') {\n throw TypeError('At least one callback required');\n }\n if (map.has(key)) {\n value = map.get(key);\n if (typeof updateFn == 'function') {\n value = updateFn(value);\n map.set(key, value);\n }\n } else if (typeof insertFn == 'function') {\n value = insertFn();\n map.set(key, value);\n } return value;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar $upsert = require('../internals/map-upsert');\n\n// `Map.prototype.upsert` method\n// https://github.com/thumbsupep/proposal-upsert\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n upsert: $upsert\n});\n","'use strict';\n// TODO: remove from `core-js@4`\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar $upsert = require('../internals/map-upsert');\n\n// `Map.prototype.updateOrInsert` method (replaced by `Map.prototype.upsert`)\n// https://github.com/thumbsupep/proposal-upsert\n$({ target: 'Map', proto: true, real: true, forced: IS_PURE }, {\n updateOrInsert: $upsert\n});\n","'use strict';\nvar collection = require('../internals/collection');\nvar collectionStrong = require('../internals/collection-strong');\n\n// `Set` constructor\n// https://tc39.github.io/ecma262/#sec-set-objects\nmodule.exports = collection('Set', function (init) {\n return function Set() { return init(this, arguments.length ? arguments[0] : undefined); };\n}, collectionStrong);\n","require('../../modules/es.set');\nrequire('../../modules/es.object.to-string');\nrequire('../../modules/es.string.iterator');\nrequire('../../modules/web.dom-collections.iterator');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Set;\n","var $ = require('../internals/export');\nvar from = require('../internals/collection-from');\n\n// `Set.from` method\n// https://tc39.github.io/proposal-setmap-offrom/#sec-set.from\n$({ target: 'Set', stat: true }, {\n from: from\n});\n","var $ = require('../internals/export');\nvar of = require('../internals/collection-of');\n\n// `Set.of` method\n// https://tc39.github.io/proposal-setmap-offrom/#sec-set.of\n$({ target: 'Set', stat: true }, {\n of: of\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar collectionAddAll = require('../internals/collection-add-all');\n\n// `Set.prototype.addAll` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n addAll: function addAll(/* ...elements */) {\n return collectionAddAll.apply(this, arguments);\n }\n});\n","'use strict';\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\n\n// https://github.com/tc39/collection-methods\nmodule.exports = function (/* ...elements */) {\n var set = anObject(this);\n var adder = aFunction(set.add);\n for (var k = 0, len = arguments.length; k < len; k++) {\n adder.call(set, arguments[k]);\n }\n return set;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar collectionDeleteAll = require('../internals/collection-delete-all');\n\n// `Set.prototype.deleteAll` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n deleteAll: function deleteAll(/* ...elements */) {\n return collectionDeleteAll.apply(this, arguments);\n }\n});\n","var IS_PURE = require('../internals/is-pure');\nvar getIterator = require('../internals/get-iterator');\n\nmodule.exports = IS_PURE ? getIterator : function (it) {\n // eslint-disable-next-line no-undef\n return Set.prototype.values.call(it);\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar bind = require('../internals/function-bind-context');\nvar getSetIterator = require('../internals/get-set-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.every` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n every: function every(callbackfn /* , thisArg */) {\n var set = anObject(this);\n var iterator = getSetIterator(set);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n return !iterate(iterator, function (value) {\n if (!boundFunction(value, value, set)) return iterate.stop();\n }, undefined, false, true).stopped;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar speciesConstructor = require('../internals/species-constructor');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.difference` method\n// https://github.com/tc39/proposal-set-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n difference: function difference(iterable) {\n var set = anObject(this);\n var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(set);\n var remover = aFunction(newSet['delete']);\n iterate(iterable, function (value) {\n remover.call(newSet, value);\n });\n return newSet;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar bind = require('../internals/function-bind-context');\nvar speciesConstructor = require('../internals/species-constructor');\nvar getSetIterator = require('../internals/get-set-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.filter` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n filter: function filter(callbackfn /* , thisArg */) {\n var set = anObject(this);\n var iterator = getSetIterator(set);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n var newSet = new (speciesConstructor(set, getBuiltIn('Set')))();\n var adder = aFunction(newSet.add);\n iterate(iterator, function (value) {\n if (boundFunction(value, value, set)) adder.call(newSet, value);\n }, undefined, false, true);\n return newSet;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar bind = require('../internals/function-bind-context');\nvar getSetIterator = require('../internals/get-set-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.find` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n find: function find(callbackfn /* , thisArg */) {\n var set = anObject(this);\n var iterator = getSetIterator(set);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n return iterate(iterator, function (value) {\n if (boundFunction(value, value, set)) return iterate.stop(value);\n }, undefined, false, true).result;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar speciesConstructor = require('../internals/species-constructor');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.intersection` method\n// https://github.com/tc39/proposal-set-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n intersection: function intersection(iterable) {\n var set = anObject(this);\n var newSet = new (speciesConstructor(set, getBuiltIn('Set')))();\n var hasCheck = aFunction(set.has);\n var adder = aFunction(newSet.add);\n iterate(iterable, function (value) {\n if (hasCheck.call(set, value)) adder.call(newSet, value);\n });\n return newSet;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.isDisjointFrom` method\n// https://tc39.github.io/proposal-set-methods/#Set.prototype.isDisjointFrom\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n isDisjointFrom: function isDisjointFrom(iterable) {\n var set = anObject(this);\n var hasCheck = aFunction(set.has);\n return !iterate(iterable, function (value) {\n if (hasCheck.call(set, value) === true) return iterate.stop();\n }).stopped;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar getIterator = require('../internals/get-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.isSubsetOf` method\n// https://tc39.github.io/proposal-set-methods/#Set.prototype.isSubsetOf\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n isSubsetOf: function isSubsetOf(iterable) {\n var iterator = getIterator(this);\n var otherSet = anObject(iterable);\n var hasCheck = otherSet.has;\n if (typeof hasCheck != 'function') {\n otherSet = new (getBuiltIn('Set'))(iterable);\n hasCheck = aFunction(otherSet.has);\n }\n return !iterate(iterator, function (value) {\n if (hasCheck.call(otherSet, value) === false) return iterate.stop();\n }, undefined, false, true).stopped;\n }\n});\n","var anObject = require('../internals/an-object');\nvar getIteratorMethod = require('../internals/get-iterator-method');\n\nmodule.exports = function (it) {\n var iteratorMethod = getIteratorMethod(it);\n if (typeof iteratorMethod != 'function') {\n throw TypeError(String(it) + ' is not iterable');\n } return anObject(iteratorMethod.call(it));\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.isSupersetOf` method\n// https://tc39.github.io/proposal-set-methods/#Set.prototype.isSupersetOf\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n isSupersetOf: function isSupersetOf(iterable) {\n var set = anObject(this);\n var hasCheck = aFunction(set.has);\n return !iterate(iterable, function (value) {\n if (hasCheck.call(set, value) === false) return iterate.stop();\n }).stopped;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar getSetIterator = require('../internals/get-set-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.join` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n join: function join(separator) {\n var set = anObject(this);\n var iterator = getSetIterator(set);\n var sep = separator === undefined ? ',' : String(separator);\n var result = [];\n iterate(iterator, result.push, result, false, true);\n return result.join(sep);\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar bind = require('../internals/function-bind-context');\nvar speciesConstructor = require('../internals/species-constructor');\nvar getSetIterator = require('../internals/get-set-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.map` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n map: function map(callbackfn /* , thisArg */) {\n var set = anObject(this);\n var iterator = getSetIterator(set);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n var newSet = new (speciesConstructor(set, getBuiltIn('Set')))();\n var adder = aFunction(newSet.add);\n iterate(iterator, function (value) {\n adder.call(newSet, boundFunction(value, value, set));\n }, undefined, false, true);\n return newSet;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar getSetIterator = require('../internals/get-set-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.reduce` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n reduce: function reduce(callbackfn /* , initialValue */) {\n var set = anObject(this);\n var iterator = getSetIterator(set);\n var noInitial = arguments.length < 2;\n var accumulator = noInitial ? undefined : arguments[1];\n aFunction(callbackfn);\n iterate(iterator, function (value) {\n if (noInitial) {\n noInitial = false;\n accumulator = value;\n } else {\n accumulator = callbackfn(accumulator, value, value, set);\n }\n }, undefined, false, true);\n if (noInitial) throw TypeError('Reduce of empty set with no initial value');\n return accumulator;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar anObject = require('../internals/an-object');\nvar bind = require('../internals/function-bind-context');\nvar getSetIterator = require('../internals/get-set-iterator');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.some` method\n// https://github.com/tc39/proposal-collection-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n some: function some(callbackfn /* , thisArg */) {\n var set = anObject(this);\n var iterator = getSetIterator(set);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n return iterate(iterator, function (value) {\n if (boundFunction(value, value, set)) return iterate.stop();\n }, undefined, false, true).stopped;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar speciesConstructor = require('../internals/species-constructor');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.symmetricDifference` method\n// https://github.com/tc39/proposal-set-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n symmetricDifference: function symmetricDifference(iterable) {\n var set = anObject(this);\n var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(set);\n var remover = aFunction(newSet['delete']);\n var adder = aFunction(newSet.add);\n iterate(iterable, function (value) {\n remover.call(newSet, value) || adder.call(newSet, value);\n });\n return newSet;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar getBuiltIn = require('../internals/get-built-in');\nvar anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar speciesConstructor = require('../internals/species-constructor');\nvar iterate = require('../internals/iterate');\n\n// `Set.prototype.union` method\n// https://github.com/tc39/proposal-set-methods\n$({ target: 'Set', proto: true, real: true, forced: IS_PURE }, {\n union: function union(iterable) {\n var set = anObject(this);\n var newSet = new (speciesConstructor(set, getBuiltIn('Set')))(set);\n iterate(iterable, aFunction(newSet.add), newSet);\n return newSet;\n }\n});\n","var isObject = require('../internals/is-object');\n\nvar floor = Math.floor;\n\n// `Number.isInteger` method implementation\n// https://tc39.github.io/ecma262/#sec-number.isinteger\nmodule.exports = function isInteger(it) {\n return !isObject(it) && isFinite(it) && floor(it) === it;\n};\n","var $ = require('../internals/export');\nvar isInteger = require('../internals/is-integer');\n\n// `Number.isInteger` method\n// https://tc39.github.io/ecma262/#sec-number.isinteger\n$({ target: 'Number', stat: true }, {\n isInteger: isInteger\n});\n","require('../../modules/es.number.is-integer');\nvar path = require('../../internals/path');\n\nmodule.exports = path.Number.isInteger;\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\nconst stringToByteArray = function(str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\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 (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\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 } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\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 bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function(bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\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 */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let 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 input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, 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 input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const 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 const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const 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 (let 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 * URL-safe base64 encoding\n */\nexport const base64Encode = function(str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\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 str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function(str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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: '${JSCORE_VERSION}'\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 */\nexport const assert = function(assertion: unknown, message: string): void {\n if (!assertion) {\n throw assertionError(message);\n }\n};\n\n/**\n * Returns an Error object suitable for throwing.\n */\nexport const assertionError = function(message: string): Error {\n return new Error(\n 'Firebase Database (' +\n CONSTANTS.SDK_VERSION +\n ') INTERNAL ASSERT FAILED: ' +\n message\n );\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * Do a deep-copy of basic JavaScript Objects or Arrays.\n */\nexport function deepCopy<T>(value: T): T {\n return deepExtend(undefined, value) as T;\n}\n\n/**\n * Copy properties from source to target (recursively allows extension\n * of Objects and Arrays). Scalar values in the target are over-written.\n * If target is undefined, an object of the appropriate type will be created\n * (and returned).\n *\n * We recursively copy all child properties of plain Objects in the source- so\n * that namespace- like dictionaries are merged.\n *\n * Note that the target can be a function, in which case the properties in\n * the source Object are copied onto it as static properties of the Function.\n */\nexport function deepExtend(target: unknown, source: unknown): unknown {\n if (!(source instanceof Object)) {\n return source;\n }\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 const dateValue = source as Date;\n return new Date(dateValue.getTime());\n\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\n default:\n // Not a plain Object - treat it as a scalar.\n return source;\n }\n\n for (const prop in source) {\n if (!source.hasOwnProperty(prop)) {\n continue;\n }\n (target as { [key: string]: unknown })[prop] = deepExtend(\n (target as { [key: string]: unknown })[prop],\n (source as { [key: string]: unknown })[prop]\n );\n }\n\n return target;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 class Deferred<R> {\n promise: Promise<R>;\n reject: (value?: unknown) => void = () => {};\n resolve: (value?: unknown) => void = () => {};\n constructor() {\n this.promise = new Promise((resolve, reject) => {\n this.resolve = resolve as (value?: unknown) => void;\n this.reject = reject as (value?: unknown) => void;\n });\n }\n\n /**\n * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around\n * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback\n * and returns a node-style callback which will resolve or reject the Deferred's promise.\n */\n wrapCallback(\n callback?: (error?: unknown, value?: unknown) => void\n ): (error: unknown, value?: unknown) => void {\n return (error, value?) => {\n if (error) {\n this.reject(error);\n } else {\n this.resolve(value);\n }\n if (typeof callback === 'function') {\n // Attaching noop handler just in case developer wasn't expecting\n // promises\n this.promise.catch(() => {});\n\n // Some of our callbacks don't expect a value and our own tests\n // assert that the parameter length is 1\n if (callback.length === 1) {\n callback(error);\n } else {\n callback(error, value);\n }\n }\n };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 user agent string\n */\nexport function getUA(): string {\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\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment\n */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if (e.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: StringLike | undefined;\n}\n\nexport interface FirebaseError extends Error, ErrorData {\n // Unique code for error - format is service/error-code-string.\n readonly code: string;\n\n // Developer-friendly error message.\n readonly message: string;\n\n // Always 'FirebaseError'.\n readonly name: typeof ERROR_NAME;\n\n // Where available - stack backtrace in a string.\n readonly stack?: string;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n readonly name = ERROR_NAME;\n\n constructor(readonly code: string, message: string) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage);\n\n // Keys with an underscore at the end of their name are not included in\n // error.data for some reason.\n // TODO: Replace with Object.entries when lib is updated to es2017.\n for (const key of Object.keys(customData)) {\n if (key.slice(-1) !== '_') {\n if (key in error) {\n console.warn(\n `Overwriting FirebaseError base field \"${key}\" can cause unexpected behavior.`\n );\n }\n error[key] = customData[key];\n }\n }\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? value.toString() : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 function jsonEval(str: string): unknown {\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 function stringify(data: unknown): string {\n return JSON.stringify(data);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 './crypt';\nimport { jsonEval } from './json';\n\ninterface Claims {\n [key: string]: {};\n}\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\n}\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 */\nexport const decode = function(token: string): DecodedToken {\n let header = {},\n claims: Claims = {},\n data = {},\n signature = '';\n\n try {\n const parts = token.split('.');\n header = jsonEval(base64Decode(parts[0]) || '') as object;\n claims = jsonEval(base64Decode(parts[1]) || '') as Claims;\n signature = parts[2];\n data = claims['d'] || {};\n delete claims['d'];\n } catch (e) {}\n\n return {\n header,\n claims,\n data,\n signature\n };\n};\n\ninterface DecodedToken {\n header: object;\n claims: Claims;\n data: object;\n signature: string;\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 */\nexport const isValidTimestamp = function(token: string): boolean {\n const claims: Claims = decode(token).claims;\n const now: number = Math.floor(new Date().getTime() / 1000);\n let validSince: number = 0,\n validUntil: number = 0;\n\n if (typeof claims === 'object') {\n if (claims.hasOwnProperty('nbf')) {\n validSince = claims['nbf'] as number;\n } else if (claims.hasOwnProperty('iat')) {\n validSince = claims['iat'] as number;\n }\n\n if (claims.hasOwnProperty('exp')) {\n validUntil = claims['exp'] as number;\n } else {\n // token will expire after 24h by default\n validUntil = validSince + 86400;\n }\n }\n\n return (\n !!now &&\n !!validSince &&\n !!validUntil &&\n now >= validSince &&\n 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 */\nexport const issuedAtTime = function(token: string): number | null {\n const claims: Claims = decode(token).claims;\n if (typeof claims === 'object' && claims.hasOwnProperty('iat')) {\n return claims['iat'] as number;\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.\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 */\nexport const isValidFormat = function(token: string): boolean {\n const decoded = decode(token),\n claims = decoded.claims;\n\n return !!claims && typeof claims === 'object' && claims.hasOwnProperty('iat');\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 */\nexport const isAdmin = function(token: string): boolean {\n const claims: Claims = decode(token).claims;\n return typeof claims === 'object' && claims['admin'] === true;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 function contains<T extends object>(obj: T, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function safeGet<T extends object, K extends keyof T>(\n obj: T,\n key: K\n): T[K] | undefined {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return obj[key];\n } else {\n return undefined;\n }\n}\n\nexport function isEmpty(obj: object): obj is {} {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function map<K extends string, V, U>(\n obj: { [key in K]: V },\n fn: (value: V, key: K, obj: { [key in K]: V }) => U,\n contextObj?: unknown\n): { [key in K]: U } {\n const res: Partial<{ [key in K]: U }> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n res[key] = fn.call(contextObj, obj[key], key, obj);\n }\n }\n return res as { [key in K]: U };\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 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 * @final\n * @struct\n */\nexport class Sha1 {\n /**\n * Holds the previous values of accumulated variables a-e in the compress_\n * function.\n * @private\n */\n private chain_: number[] = [];\n\n /**\n * A buffer holding the partially computed hash result.\n * @private\n */\n private buf_: number[] = [];\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 * @private\n */\n private W_: number[] = [];\n\n /**\n * Contains data needed to pad messages less than 64 bytes.\n * @private\n */\n private pad_: number[] = [];\n\n /**\n * @private {number}\n */\n private inbuf_: number = 0;\n\n /**\n * @private {number}\n */\n private total_: number = 0;\n\n blockSize: number;\n\n constructor() {\n this.blockSize = 512 / 8;\n\n this.pad_[0] = 128;\n for (let i = 1; i < this.blockSize; ++i) {\n this.pad_[i] = 0;\n }\n\n this.reset();\n }\n\n reset(): void {\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 buf Block to compress.\n * @param offset Offset of the block in the buffer.\n * @private\n */\n compress_(buf: number[] | Uint8Array | string, offset?: number): void {\n if (!offset) {\n offset = 0;\n }\n\n const W = this.W_;\n\n // get 16 big endian words\n if (typeof buf === 'string') {\n for (let 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(offset) << 24) |\n (buf.charCodeAt(offset + 1) << 16) |\n (buf.charCodeAt(offset + 2) << 8) |\n buf.charCodeAt(offset + 3);\n offset += 4;\n }\n } else {\n for (let i = 0; i < 16; i++) {\n W[i] =\n (buf[offset] << 24) |\n (buf[offset + 1] << 16) |\n (buf[offset + 2] << 8) |\n buf[offset + 3];\n offset += 4;\n }\n }\n\n // expand to 80 words\n for (let i = 16; i < 80; i++) {\n const t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = ((t << 1) | (t >>> 31)) & 0xffffffff;\n }\n\n let a = this.chain_[0];\n let b = this.chain_[1];\n let c = this.chain_[2];\n let d = this.chain_[3];\n let e = this.chain_[4];\n let f, k;\n\n // TODO(user): Try to unroll this loop to speed up the computation.\n for (let 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 const 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?: number[] | Uint8Array | string, length?: number): void {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (length === undefined) {\n length = bytes.length;\n }\n\n const lengthMinusBlock = length - this.blockSize;\n let n = 0;\n // Using local instead of member variables gives ~5% speedup on Firefox 16.\n const buf = this.buf_;\n let inbuf = this.inbuf_;\n\n // The outer while loop should execute at most twice.\n while (n < 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 < 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 < 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_ += length;\n }\n\n /** @override */\n digest(): number[] {\n const digest: number[] = [];\n let 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 (let 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 let n = 0;\n for (let i = 0; i < 5; i++) {\n for (let 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\nexport interface Observer<T> {\n // Called once for each value in a stream of values.\n next: NextFn<T>;\n\n // A stream terminates by a single call to EITHER error() or complete().\n error: ErrorFn;\n\n // No events will be sent to next() once complete() is called.\n complete: CompleteFn;\n}\n\nexport type PartialObserver<T> = Partial<Observer<T>>;\n\n// TODO: Support also Unsubscribe.unsubscribe?\nexport type Unsubscribe = () => void;\n\n/**\n * The Subscribe interface has two forms - passing the inline function\n * callbacks, or a object interface with callback properties.\n */\nexport interface Subscribe<T> {\n (next?: NextFn<T>, error?: ErrorFn, complete?: CompleteFn): Unsubscribe;\n (observer: PartialObserver<T>): Unsubscribe;\n}\n\nexport interface Observable<T> {\n // Subscribe method\n subscribe: Subscribe<T>;\n}\n\nexport type Executor<T> = (observer: Observer<T>) => void;\n\n/**\n * Helper to make a Subscribe function (just like Promise helps make a\n * Thenable).\n *\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\nexport function createSubscribe<T>(\n executor: Executor<T>,\n onNoObservers?: Executor<T>\n): Subscribe<T> {\n const proxy = new ObserverProxy<T>(executor, onNoObservers);\n return proxy.subscribe.bind(proxy);\n}\n\n/**\n * Implement fan-out for any number of Observers attached via a subscribe\n * function.\n */\nclass ObserverProxy<T> implements Observer<T> {\n private observers: Array<Observer<T>> | undefined = [];\n private unsubscribes: Unsubscribe[] = [];\n private onNoObservers: Executor<T> | undefined;\n private observerCount = 0;\n // Micro-task scheduling by calling task.then().\n private task = Promise.resolve();\n private finalized = false;\n private finalError?: Error;\n\n /**\n * @param executor Function which can make calls to a single Observer\n * as a proxy.\n * @param onNoObservers Callback when count of Observers goes to zero.\n */\n constructor(executor: Executor<T>, onNoObservers?: Executor<T>) {\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\n .then(() => {\n executor(this);\n })\n .catch(e => {\n this.error(e);\n });\n }\n\n next(value: T): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.next(value);\n });\n }\n\n error(error: Error): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.error(error);\n });\n this.close(error);\n }\n\n complete(): void {\n this.forEachObserver((observer: Observer<T>) => {\n observer.complete();\n });\n this.close();\n }\n\n /**\n * Subscribe function that can be used to add an Observer to the fan-out list.\n *\n * - We require that no event is sent to a subscriber sychronously to their\n * call to subscribe().\n */\n subscribe(\n nextOrObserver?: PartialObserver<T> | Function,\n error?: ErrorFn,\n complete?: CompleteFn\n ): Unsubscribe {\n let observer: Observer<T>;\n\n if (\n nextOrObserver === undefined &&\n error === undefined &&\n complete === undefined\n ) {\n throw new Error('Missing Observer.');\n }\n\n // Assemble an Observer object when passed as callback functions.\n if (\n implementsAnyMethods(nextOrObserver as { [key: string]: unknown }, [\n 'next',\n 'error',\n 'complete'\n ])\n ) {\n observer = nextOrObserver as Observer<T>;\n } else {\n observer = {\n next: nextOrObserver as NextFn<T>,\n error,\n complete\n } as Observer<T>;\n }\n\n if (observer.next === undefined) {\n observer.next = noop as NextFn<T>;\n }\n if (observer.error === undefined) {\n observer.error = noop as ErrorFn;\n }\n if (observer.complete === undefined) {\n observer.complete = noop as CompleteFn;\n }\n\n const unsub = this.unsubscribeOne.bind(this, this.observers!.length);\n\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 // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\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\n this.observers!.push(observer as Observer<T>);\n\n return unsub;\n }\n\n // Unsubscribe is synchronous - we guarantee that no events are sent to\n // any unsubscribed Observer.\n private unsubscribeOne(i: number): void {\n if (this.observers === undefined || this.observers[i] === undefined) {\n return;\n }\n\n delete this.observers[i];\n\n this.observerCount -= 1;\n if (this.observerCount === 0 && this.onNoObservers !== undefined) {\n this.onNoObservers(this);\n }\n }\n\n private forEachObserver(fn: (observer: Observer<T>) => void): void {\n if (this.finalized) {\n // Already closed by previous event....just eat the additional values.\n return;\n }\n\n // Since sendOne calls asynchronously - there is no chance that\n // this.observers will become undefined.\n for (let i = 0; i < this.observers!.length; i++) {\n this.sendOne(i, fn);\n }\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 private sendOne(i: number, fn: (observer: Observer<T>) => void): void {\n // Execute the callback asynchronously\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\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\n private close(err?: Error): void {\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 // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.task.then(() => {\n this.observers = undefined;\n this.onNoObservers = undefined;\n });\n }\n}\n\n/** Turn synchronous function into one called asynchronously. */\nexport function async(fn: Function, onError?: ErrorFn): Function {\n return (...args: unknown[]) => {\n Promise.resolve(true)\n .then(() => {\n fn(...args);\n })\n .catch((error: Error) => {\n if (onError) {\n onError(error);\n }\n });\n };\n}\n\n/**\n * Return true if the object passed in implements any of the named methods.\n */\nfunction implementsAnyMethods(\n obj: { [key: string]: unknown },\n methods: string[]\n): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n for (const method of methods) {\n if (method in obj && typeof obj[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n\nfunction noop(): void {\n // do nothing\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fnName The function name\n * @param minCount The minimum number of arguments to allow for the function call\n * @param maxCount The maximum number of argument to allow for the function call\n * @param argCount The actual number of arguments provided.\n */\nexport const validateArgCount = function(\n fnName: string,\n minCount: number,\n maxCount: number,\n argCount: number\n): void {\n let 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 const 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 fnName The function name\n * @param argumentNumber The index of the argument\n * @param optional Whether or not the argument is optional\n * @return The prefix to add to the error thrown for validation.\n */\nexport function errorPrefix(\n fnName: string,\n argumentNumber: number,\n optional: boolean\n): string {\n let 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 let error = fnName + ' failed: ';\n\n error += argName + ' argument ';\n return error;\n}\n\n/**\n * @param fnName\n * @param argumentNumber\n * @param namespace\n * @param optional\n */\nexport function validateNamespace(\n fnName: string,\n argumentNumber: number,\n namespace: string,\n optional: boolean\n): void {\n if (optional && !namespace) {\n return;\n }\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 function validateCallback(\n fnName: string,\n argumentNumber: number,\n callback: Function,\n optional: boolean\n): void {\n if (optional && !callback) {\n return;\n }\n if (typeof callback !== 'function') {\n throw new Error(\n errorPrefix(fnName, argumentNumber, optional) +\n 'must be a valid function.'\n );\n }\n}\n\nexport function validateContextObject(\n fnName: string,\n argumentNumber: number,\n context: unknown,\n optional: boolean\n): void {\n if (optional && !context) {\n return;\n }\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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: string): number[] {\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n\n // Is this the lead surrogate in a surrogate pair?\n if (c >= 0xd800 && c <= 0xdbff) {\n const high = c - 0xd800; // the high 10 bits.\n i++;\n assert(i < str.length, 'Surrogate pair missing trail surrogate.');\n const 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: string): number {\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n const 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 * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 DEFAULT_ENTRY_NAME = '[DEFAULT]';\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Deferred } from '@firebase/util';\nimport { ComponentContainer } from './component_container';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { InstantiationMode, Name, NameServiceMapping } from './types';\nimport { Component } from './component';\n\n/**\n * Provider for instance for service name T, e.g. 'auth', 'auth-internal'\n * NameServiceMapping[T] is an alias for the type of the instance\n */\nexport class Provider<T extends Name> {\n private component: Component<T> | null = null;\n private readonly instances: Map<string, NameServiceMapping[T]> = new Map();\n private readonly instancesDeferred: Map<\n string,\n Deferred<NameServiceMapping[T]>\n > = new Map();\n\n constructor(\n private readonly name: T,\n private readonly container: ComponentContainer\n ) {}\n\n /**\n * @param identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n */\n get(identifier: string = DEFAULT_ENTRY_NAME): Promise<NameServiceMapping[T]> {\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n\n if (!this.instancesDeferred.has(normalizedIdentifier)) {\n const deferred = new Deferred<NameServiceMapping[T]>();\n this.instancesDeferred.set(normalizedIdentifier, deferred);\n // If the service instance is available, resolve the promise with it immediately\n try {\n const instance = this.getOrInitializeService(normalizedIdentifier);\n if (instance) {\n deferred.resolve(instance);\n }\n } catch (e) {\n // when the instance factory throws an exception during get(), it should not cause\n // a fatal error. We just return the unresolved promise in this case.\n }\n }\n\n return this.instancesDeferred.get(normalizedIdentifier)!.promise;\n }\n\n /**\n *\n * @param options.identifier A provider can provide mulitple instances of a service\n * if this.component.multipleInstances is true.\n * @param options.optional If optional is false or not provided, the method throws an error when\n * the service is not immediately available.\n * If optional is true, the method returns null if the service is not immediately available.\n */\n getImmediate(options: {\n identifier?: string;\n optional: true;\n }): NameServiceMapping[T] | null;\n getImmediate(options?: {\n identifier?: string;\n optional?: false;\n }): NameServiceMapping[T];\n getImmediate(options?: {\n identifier?: string;\n optional?: boolean;\n }): NameServiceMapping[T] | null {\n const { identifier, optional } = {\n identifier: DEFAULT_ENTRY_NAME,\n optional: false,\n ...options\n };\n // if multipleInstances is not supported, use the default name\n const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);\n try {\n const instance = this.getOrInitializeService(normalizedIdentifier);\n\n if (!instance) {\n if (optional) {\n return null;\n }\n throw Error(`Service ${this.name} is not available`);\n }\n return instance;\n } catch (e) {\n if (optional) {\n return null;\n } else {\n throw e;\n }\n }\n }\n\n getComponent(): Component<T> | null {\n return this.component;\n }\n\n setComponent(component: Component<T>): void {\n if (component.name !== this.name) {\n throw Error(\n `Mismatching Component ${component.name} for Provider ${this.name}.`\n );\n }\n\n if (this.component) {\n throw Error(`Component for ${this.name} has already been provided`);\n }\n\n this.component = component;\n // if the service is eager, initialize the default instance\n if (isComponentEager(component)) {\n try {\n this.getOrInitializeService(DEFAULT_ENTRY_NAME);\n } catch (e) {\n // when the instance factory for an eager Component throws an exception during the eager\n // initialization, it should not cause a fatal error.\n // TODO: Investigate if we need to make it configurable, because some component may want to cause\n // a fatal error in this case?\n }\n }\n\n // Create service instances for the pending promises and resolve them\n // NOTE: if this.multipleInstances is false, only the default instance will be created\n // and all promises with resolve with it regardless of the identifier.\n for (const [\n instanceIdentifier,\n instanceDeferred\n ] of this.instancesDeferred.entries()) {\n const normalizedIdentifier = this.normalizeInstanceIdentifier(\n instanceIdentifier\n );\n\n try {\n // `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.\n const instance = this.getOrInitializeService(normalizedIdentifier)!;\n instanceDeferred.resolve(instance);\n } catch (e) {\n // when the instance factory throws an exception, it should not cause\n // a fatal error. We just leave the promise unresolved.\n }\n }\n }\n\n clearInstance(identifier: string = DEFAULT_ENTRY_NAME): void {\n this.instancesDeferred.delete(identifier);\n this.instances.delete(identifier);\n }\n\n // app.delete() will call this method on every provider to delete the services\n // TODO: should we mark the provider as deleted?\n async delete(): Promise<void> {\n const services = Array.from(this.instances.values());\n\n await Promise.all(\n services\n .filter(service => 'INTERNAL' in service)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n .map(service => (service as any).INTERNAL!.delete())\n );\n }\n\n isComponentSet(): boolean {\n return this.component != null;\n }\n\n private getOrInitializeService(\n identifier: string\n ): NameServiceMapping[T] | null {\n let instance = this.instances.get(identifier);\n if (!instance && this.component) {\n instance = this.component.instanceFactory(\n this.container,\n normalizeIdentifierForFactory(identifier)\n ) as NameServiceMapping[T];\n this.instances.set(identifier, instance);\n }\n\n return instance || null;\n }\n\n private normalizeInstanceIdentifier(identifier: string): string {\n if (this.component) {\n return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME;\n } else {\n return identifier; // assume multiple instances are supported before the component is provided.\n }\n }\n}\n\n// undefined should be passed to the service factory for the default instance\nfunction normalizeIdentifierForFactory(identifier: string): string | undefined {\n return identifier === DEFAULT_ENTRY_NAME ? undefined : identifier;\n}\n\nfunction isComponentEager(component: Component<Name>): boolean {\n return component.instantiationMode === InstantiationMode.EAGER;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Provider } from './provider';\nimport { Component } from './component';\nimport { Name } from './types';\n\n/**\n * ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`\n */\nexport class ComponentContainer {\n private readonly providers = new Map<string, Provider<Name>>();\n\n constructor(private readonly name: string) {}\n\n /**\n *\n * @param component Component being added\n * @param overwrite When a component with the same name has already been registered,\n * if overwrite is true: overwrite the existing component with the new component and create a new\n * provider with the new component. It can be useful in tests where you want to use different mocks\n * for different tests.\n * if overwrite is false: throw an exception\n */\n addComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n throw new Error(\n `Component ${component.name} has already been registered with ${this.name}`\n );\n }\n\n provider.setComponent(component);\n }\n\n addOrOverwriteComponent<T extends Name>(component: Component<T>): void {\n const provider = this.getProvider(component.name);\n if (provider.isComponentSet()) {\n // delete the existing provider from the container, so we can register the new component\n this.providers.delete(component.name);\n }\n\n this.addComponent(component);\n }\n\n /**\n * getProvider provides a type safe interface where it can only be called with a field name\n * present in NameServiceMapping interface.\n *\n * Firebase SDKs providing services should extend NameServiceMapping interface to register\n * themselves.\n */\n getProvider<T extends Name>(name: T): Provider<T> {\n if (this.providers.has(name)) {\n return this.providers.get(name) as Provider<T>;\n }\n\n // create a Provider for a service that hasn't registered with Firebase\n const provider = new Provider<T>(name, this);\n this.providers.set(name, provider);\n\n return provider as Provider<T>;\n }\n\n getProviders(): Array<Provider<Name>> {\n return Array.from(this.providers.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n};\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError('Invalid value assigned to `logLevel`');\n }\n this._logLevel = val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n const newLevel = typeof level === 'string' ? levelStringToEnum[level] : level;\n instances.forEach(inst => {\n inst.logLevel = newLevel;\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum AppError {\n NO_APP = 'no-app',\n BAD_APP_NAME = 'bad-app-name',\n DUPLICATE_APP = 'duplicate-app',\n APP_DELETED = 'app-deleted',\n INVALID_APP_ARGUMENT = 'invalid-app-argument',\n INVALID_LOG_ARGUMENT = 'invalid-log-argument'\n}\n\nconst ERRORS: ErrorMap<AppError> = {\n [AppError.NO_APP]:\n \"No Firebase App '{$appName}' has been created - \" +\n 'call Firebase App.initializeApp()',\n [AppError.BAD_APP_NAME]: \"Illegal App name: '{$appName}\",\n [AppError.DUPLICATE_APP]: \"Firebase App named '{$appName}' already exists\",\n [AppError.APP_DELETED]: \"Firebase App named '{$appName}' already deleted\",\n [AppError.INVALID_APP_ARGUMENT]:\n 'firebase.{$appName}() takes either no argument or a ' +\n 'Firebase App instance.',\n [AppError.INVALID_LOG_ARGUMENT]: 'First argument to `onLog` must be null or a function.'\n};\n\ntype ErrorParams = { [key in AppError]: { appName: string } };\n\nexport const ERROR_FACTORY = new ErrorFactory<AppError, ErrorParams>(\n 'app',\n 'Firebase',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 DEFAULT_ENTRY_NAME = '[DEFAULT]';\nimport { name as appName } from '../package.json';\nimport { name as analyticsName } from '../../analytics/package.json';\nimport { name as authName } from '../../auth/package.json';\nimport { name as databaseName } from '../../database/package.json';\nimport { name as functionsName } from '../../functions/package.json';\nimport { name as installationsName } from '../../installations/package.json';\nimport { name as messagingName } from '../../messaging/package.json';\nimport { name as performanceName } from '../../performance/package.json';\nimport { name as remoteConfigName } from '../../remote-config/package.json';\nimport { name as storageName } from '../../storage/package.json';\nimport { name as firestoreName } from '../../firestore/package.json';\nimport { name as packageName } from '../../../package.json';\n\nexport const PLATFORM_LOG_STRING = {\n [appName]: 'fire-core',\n [analyticsName]: 'fire-analytics',\n [authName]: 'fire-auth',\n [databaseName]: 'fire-rtdb',\n [functionsName]: 'fire-fn',\n [installationsName]: 'fire-iid',\n [messagingName]: 'fire-fcm',\n [performanceName]: 'fire-perf',\n [remoteConfigName]: 'fire-rc',\n [storageName]: 'fire-gcs',\n [firestoreName]: 'fire-fst',\n 'fire-js': 'fire-js', // Platform identifier for JS SDK.\n [packageName]: 'fire-js-all'\n} as const;\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/app');\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 FirebaseApp,\n FirebaseOptions,\n FirebaseAppConfig\n} from '@firebase/app-types';\nimport {\n _FirebaseApp,\n _FirebaseNamespace,\n FirebaseService\n} from '@firebase/app-types/private';\nimport { deepCopy } from '@firebase/util';\nimport {\n ComponentContainer,\n Component,\n ComponentType,\n Name\n} from '@firebase/component';\nimport { AppError, ERROR_FACTORY } from './errors';\nimport { DEFAULT_ENTRY_NAME } from './constants';\nimport { logger } from './logger';\n\n/**\n * Global context object for a collection of services using\n * a shared authentication state.\n */\nexport class FirebaseAppImpl implements FirebaseApp {\n private readonly options_: FirebaseOptions;\n private readonly name_: string;\n private isDeleted_ = false;\n private automaticDataCollectionEnabled_: boolean;\n private container: ComponentContainer;\n\n constructor(\n options: FirebaseOptions,\n config: FirebaseAppConfig,\n private readonly firebase_: _FirebaseNamespace\n ) {\n this.name_ = config.name!;\n this.automaticDataCollectionEnabled_ =\n config.automaticDataCollectionEnabled || false;\n this.options_ = deepCopy<FirebaseOptions>(options);\n this.container = new ComponentContainer(config.name!);\n\n // add itself to container\n this._addComponent(new Component('app', () => this, ComponentType.PUBLIC));\n // populate ComponentContainer with existing components\n for (const component of this.firebase_.INTERNAL.components.values()) {\n this._addComponent(component);\n }\n }\n\n get automaticDataCollectionEnabled(): boolean {\n this.checkDestroyed_();\n return this.automaticDataCollectionEnabled_;\n }\n\n set automaticDataCollectionEnabled(val) {\n this.checkDestroyed_();\n this.automaticDataCollectionEnabled_ = val;\n }\n\n get name(): string {\n this.checkDestroyed_();\n return this.name_;\n }\n\n get options(): FirebaseOptions {\n this.checkDestroyed_();\n return this.options_;\n }\n\n delete(): Promise<void> {\n return new Promise(resolve => {\n this.checkDestroyed_();\n resolve();\n })\n .then(() => {\n this.firebase_.INTERNAL.removeApp(this.name_);\n\n return Promise.all(\n this.container.getProviders().map(provider => provider.delete())\n );\n })\n .then((): void => {\n this.isDeleted_ = true;\n });\n }\n\n /**\n * Return a service instance associated with this app (creating it\n * on demand), identified by the passed instanceIdentifier.\n *\n * NOTE: Currently storage and functions are the only ones that are leveraging this\n * functionality. They invoke it by calling:\n *\n * ```javascript\n * firebase.app().storage('STORAGE BUCKET ID')\n * ```\n *\n * The service name is passed to this already\n * @internal\n */\n _getService(\n name: string,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n ): FirebaseService {\n this.checkDestroyed_();\n\n // getImmediate will always succeed because _getService is only called for registered components.\n return (this.container.getProvider(name as Name).getImmediate({\n identifier: instanceIdentifier\n }) as unknown) as FirebaseService;\n }\n /**\n * Remove a service instance from the cache, so we will create a new instance for this service\n * when people try to get this service again.\n *\n * NOTE: currently only firestore is using this functionality to support firestore shutdown.\n *\n * @param name The service name\n * @param instanceIdentifier instance identifier in case multiple instances are allowed\n * @internal\n */\n _removeServiceInstance(\n name: string,\n instanceIdentifier: string = DEFAULT_ENTRY_NAME\n ): void {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.container.getProvider(name as any).clearInstance(instanceIdentifier);\n }\n\n /**\n * @param component the component being added to this app's container\n */\n _addComponent(component: Component): void {\n try {\n this.container.addComponent(component);\n } catch (e) {\n logger.debug(\n `Component ${component.name} failed to register with FirebaseApp ${this.name}`,\n e\n );\n }\n }\n\n _addOrOverwriteComponent(component: Component): void {\n this.container.addOrOverwriteComponent(component);\n }\n\n /**\n * This function will throw an Error if the App has already been deleted -\n * use before performing API actions on the App.\n */\n private checkDestroyed_(): void {\n if (this.isDeleted_) {\n throw ERROR_FACTORY.create(AppError.APP_DELETED, { appName: this.name_ });\n }\n }\n}\n\n// Prevent dead-code elimination of these methods w/o invalid property\n// copying.\n(FirebaseAppImpl.prototype.name && FirebaseAppImpl.prototype.options) ||\n FirebaseAppImpl.prototype.delete ||\n console.log('dc');\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 FirebaseApp,\n FirebaseOptions,\n FirebaseNamespace,\n FirebaseAppConfig\n} from '@firebase/app-types';\nimport {\n _FirebaseApp,\n _FirebaseNamespace,\n FirebaseService,\n FirebaseServiceNamespace\n} from '@firebase/app-types/private';\nimport { deepExtend, contains } from '@firebase/util';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { ERROR_FACTORY, AppError } from './errors';\nimport { FirebaseAppLiteImpl } from './lite/firebaseAppLite';\nimport { DEFAULT_ENTRY_NAME, PLATFORM_LOG_STRING } from './constants';\nimport { version } from '../../firebase/package.json';\nimport { logger } from './logger';\nimport {\n setUserLogHandler,\n setLogLevel,\n LogCallback,\n LogOptions\n} from '@firebase/logger';\nimport { Component, ComponentType, Name } from '@firebase/component';\n\n/**\n * Because auth can't share code with other components, we attach the utility functions\n * in an internal namespace to share code.\n * This function return a firebase namespace object without\n * any utility functions, so it can be shared between the regular firebaseNamespace and\n * the lite version.\n */\nexport function createFirebaseNamespaceCore(\n firebaseAppImpl: typeof FirebaseAppImpl | typeof FirebaseAppLiteImpl\n): FirebaseNamespace {\n const apps: { [name: string]: FirebaseApp } = {};\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const components = new Map<string, Component<any>>();\n\n // A namespace is a plain JavaScript Object.\n const namespace: FirebaseNamespace = {\n // Hack to prevent Babel from modifying the object returned\n // as the firebase namespace.\n // @ts-ignore\n __esModule: true,\n initializeApp,\n // @ts-ignore\n app,\n registerVersion,\n setLogLevel,\n onLog,\n // @ts-ignore\n apps: null,\n SDK_VERSION: version,\n INTERNAL: {\n registerComponent,\n removeApp,\n components,\n useAsService\n }\n };\n\n // Inject a circular default export to allow Babel users who were previously\n // using:\n //\n // import firebase from 'firebase';\n // which becomes: var firebase = require('firebase').default;\n //\n // instead of\n //\n // import * as firebase from 'firebase';\n // which becomes: var firebase = require('firebase');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)['default'] = namespace;\n\n // firebase.apps is a read-only getter.\n Object.defineProperty(namespace, 'apps', {\n get: getApps\n });\n\n /**\n * Called by App.delete() - but before any services associated with the App\n * are deleted.\n */\n function removeApp(name: string): void {\n delete apps[name];\n }\n\n /**\n * Get the App object for a given name (or DEFAULT).\n */\n function app(name?: string): FirebaseApp {\n name = name || DEFAULT_ENTRY_NAME;\n if (!contains(apps, name)) {\n throw ERROR_FACTORY.create(AppError.NO_APP, { appName: name });\n }\n return apps[name];\n }\n\n // @ts-ignore\n app['App'] = firebaseAppImpl;\n /**\n * Create a new App instance (name must be unique).\n */\n function initializeApp(\n options: FirebaseOptions,\n config?: FirebaseAppConfig\n ): FirebaseApp;\n function initializeApp(options: FirebaseOptions, name?: string): FirebaseApp;\n function initializeApp(\n options: FirebaseOptions,\n rawConfig = {}\n ): FirebaseApp {\n if (typeof rawConfig !== 'object' || rawConfig === null) {\n const name = rawConfig;\n rawConfig = { name };\n }\n\n const config = rawConfig as FirebaseAppConfig;\n\n if (config.name === undefined) {\n config.name = DEFAULT_ENTRY_NAME;\n }\n\n const { name } = config;\n\n if (typeof name !== 'string' || !name) {\n throw ERROR_FACTORY.create(AppError.BAD_APP_NAME, {\n appName: String(name)\n });\n }\n\n if (contains(apps, name)) {\n throw ERROR_FACTORY.create(AppError.DUPLICATE_APP, { appName: name });\n }\n\n const app = new firebaseAppImpl(\n options,\n config,\n namespace as _FirebaseNamespace\n );\n\n apps[name] = app;\n\n return app;\n }\n\n /*\n * Return an array of all the non-deleted FirebaseApps.\n */\n function getApps(): FirebaseApp[] {\n // Make a copy so caller cannot mutate the apps list.\n return Object.keys(apps).map(name => apps[name]);\n }\n\n function registerComponent(\n component: Component\n ): FirebaseServiceNamespace<FirebaseService> | null {\n const componentName = component.name;\n if (components.has(componentName)) {\n logger.debug(\n `There were multiple attempts to register component ${componentName}.`\n );\n\n return component.type === ComponentType.PUBLIC\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)[componentName]\n : null;\n }\n\n components.set(componentName, component);\n\n // create service namespace for public components\n if (component.type === ComponentType.PUBLIC) {\n // The Service namespace is an accessor function ...\n const serviceNamespace = (\n appArg: FirebaseApp = app()\n ): FirebaseService => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (typeof (appArg as any)[componentName] !== 'function') {\n // Invalid argument.\n // This happens in the following case: firebase.storage('gs:/')\n throw ERROR_FACTORY.create(AppError.INVALID_APP_ARGUMENT, {\n appName: componentName\n });\n }\n\n // Forward service instance lookup to the FirebaseApp.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (appArg as any)[componentName]();\n };\n\n // ... and a container for service-level properties.\n if (component.serviceProps !== undefined) {\n deepExtend(serviceNamespace, component.serviceProps);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)[componentName] = serviceNamespace;\n\n // Patch the FirebaseAppImpl prototype\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (firebaseAppImpl.prototype as any)[componentName] =\n // TODO: The eslint disable can be removed and the 'ignoreRestArgs'\n // option added to the no-explicit-any rule when ESlint releases it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function(...args: any) {\n const serviceFxn = this._getService.bind(this, componentName);\n return serviceFxn.apply(\n this,\n component.multipleInstances ? args : []\n );\n };\n }\n\n // add the component to existing app instances\n for (const appName of Object.keys(apps)) {\n (apps[appName] as _FirebaseApp)._addComponent(component);\n }\n\n return component.type === ComponentType.PUBLIC\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (namespace as any)[componentName]\n : null;\n }\n\n function registerVersion(\n libraryKeyOrName: string,\n version: string,\n variant?: string\n ): void {\n // TODO: We can use this check to whitelist strings when/if we set up\n // a good whitelist system.\n let library = PLATFORM_LOG_STRING[libraryKeyOrName] ?? libraryKeyOrName;\n if (variant) {\n library += `-${variant}`;\n }\n const libraryMismatch = library.match(/\\s|\\//);\n const versionMismatch = version.match(/\\s|\\//);\n if (libraryMismatch || versionMismatch) {\n const warning = [\n `Unable to register library \"${library}\" with version \"${version}\":`\n ];\n if (libraryMismatch) {\n warning.push(\n `library name \"${library}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n if (libraryMismatch && versionMismatch) {\n warning.push('and');\n }\n if (versionMismatch) {\n warning.push(\n `version name \"${version}\" contains illegal characters (whitespace or \"/\")`\n );\n }\n logger.warn(warning.join(' '));\n return;\n }\n registerComponent(\n new Component(\n `${library}-version` as Name,\n () => ({ library, version }),\n ComponentType.VERSION\n )\n );\n }\n\n function onLog(logCallback: LogCallback | null, options?: LogOptions): void {\n if (logCallback !== null && typeof logCallback !== 'function') {\n throw ERROR_FACTORY.create(AppError.INVALID_LOG_ARGUMENT, {\n appName: name\n });\n }\n setUserLogHandler(logCallback, options);\n }\n\n // Map the requested service to a registered service name\n // (used to map auth to serverAuth service when needed).\n function useAsService(app: FirebaseApp, name: string): string | null {\n if (name === 'serverAuth') {\n return null;\n }\n\n const useService = name;\n\n return useService;\n }\n\n return namespace;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseApp, _FirebaseNamespace } from '@firebase/app-types/private';\nimport { createSubscribe, deepExtend, ErrorFactory } from '@firebase/util';\nimport { FirebaseAppImpl } from './firebaseApp';\nimport { createFirebaseNamespaceCore } from './firebaseNamespaceCore';\n\n/**\n * Return a firebase namespace object.\n *\n * In production, this will be called exactly once and the result\n * assigned to the 'firebase' global. It may be called multiple times\n * in unit tests.\n */\nexport function createFirebaseNamespace(): FirebaseNamespace {\n const namespace = createFirebaseNamespaceCore(FirebaseAppImpl);\n (namespace as _FirebaseNamespace).INTERNAL = {\n ...(namespace as _FirebaseNamespace).INTERNAL,\n createFirebaseNamespace,\n extendNamespace,\n createSubscribe,\n ErrorFactory,\n deepExtend\n };\n\n /**\n * Patch the top-level firebase namespace with additional properties.\n *\n * firebase.INTERNAL.extendNamespace()\n */\n function extendNamespace(props: { [prop: string]: unknown }): void {\n deepExtend(namespace, props);\n }\n\n return namespace;\n}\n\nexport const firebase = createFirebaseNamespace();\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 ComponentContainer,\n ComponentType,\n Provider,\n Name\n} from '@firebase/component';\n\nexport class PlatformLoggerService {\n constructor(private readonly container: ComponentContainer) {}\n // In initial implementation, this will be called by installations on\n // auth token refresh, and installations will send this string.\n getPlatformInfoString(): string {\n const providers = this.container.getProviders();\n // Loop through providers and get library/version pairs from any that are\n // version components.\n return providers\n .map(provider => {\n if (isVersionServiceProvider(provider)) {\n const service = provider.getImmediate();\n return `${service.library}/${service.version}`;\n } else {\n return null;\n }\n })\n .filter(logString => logString)\n .join(' ');\n }\n}\n/**\n *\n * @param provider check if this provider provides a VersionService\n *\n * NOTE: Using Provider<'app-version'> is a hack to indicate that the provider\n * provides VersionService. The provider is not necessarily a 'app-version'\n * provider.\n */\nfunction isVersionServiceProvider(\n provider: Provider<Name>\n): provider is Provider<'app-version'> {\n const component = provider.getComponent();\n return component?.type === ComponentType.VERSION;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FirebaseNamespace } from '@firebase/app-types';\nimport { firebase as firebaseNamespace } from './src/firebaseNamespace';\nimport { isNode, isBrowser } from '@firebase/util';\nimport { logger } from './src/logger';\nimport { registerCoreComponents } from './src/registerCoreComponents';\n\n// Firebase Lite detection\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nif (isBrowser() && (self as any).firebase !== undefined) {\n logger.warn(`\n Warning: Firebase is already defined in the global scope. Please make sure\n Firebase library is only loaded once.\n `);\n\n // eslint-disable-next-line\n const sdkVersion = ((self as any).firebase as FirebaseNamespace).SDK_VERSION;\n if (sdkVersion && sdkVersion.indexOf('LITE') >= 0) {\n logger.warn(`\n Warning: You are trying to load Firebase while using Firebase Performance standalone script.\n You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.\n `);\n }\n}\n\nconst initializeApp = firebaseNamespace.initializeApp;\n\n// TODO: This disable can be removed and the 'ignoreRestArgs' option added to\n// the no-explicit-any rule when ESlint releases it.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfirebaseNamespace.initializeApp = function(...args: any) {\n // Environment check before initializing app\n // Do the check in initializeApp, so people have a chance to disable it by setting logLevel\n // in @firebase/logger\n if (isNode()) {\n logger.warn(`\n Warning: This is a browser-targeted Firebase bundle but it appears it is being\n run in a Node environment. If running in a Node environment, make sure you\n are using the bundle specified by the \"main\" field in package.json.\n \n If you are using Webpack, you can specify \"main\" as the first item in\n \"resolve.mainFields\":\n https://webpack.js.org/configuration/resolve/#resolvemainfields\n \n If using Rollup, use the rollup-plugin-node-resolve plugin and specify \"main\"\n as the first item in \"mainFields\", e.g. ['main', 'module'].\n https://github.com/rollup/rollup-plugin-node-resolve\n `);\n }\n return initializeApp.apply(undefined, args);\n};\n\nexport const firebase = firebaseNamespace;\n\nregisterCoreComponents(firebase);\n\n// eslint-disable-next-line import/no-default-export\nexport default firebase;\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport { PlatformLoggerService } from './platformLoggerService';\nimport { name, version } from '../package.json';\n\nexport function registerCoreComponents(\n firebase: FirebaseNamespace,\n variant?: string\n): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'platform-logger',\n container => new PlatformLoggerService(container),\n ComponentType.PRIVATE\n )\n );\n // Register `app` package.\n firebase.registerVersion(name, version, variant);\n // Register platform SDK identifier (no version).\n firebase.registerVersion('fire-js', '');\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\nimport { name, version } from '../package.json';\n\nfirebase.registerVersion(name, version, 'app');\n\nexport default firebase;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Bootstrap for the Google JS Library (Closure).\n *\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\n * to include their own deps file(s) from different locations.\n *\n * Avoid including base.js more than once. This is strictly discouraged and not\n * supported. goog.require(...) won't work properly in that case.\n *\n * @provideGoog\n */\n\n\n/**\n * @define {boolean} Overridden to true by the compiler.\n */\nvar COMPILED = false;\n\n\n/**\n * Base namespace for the Closure library. Checks to see goog is already\n * defined in the current scope before assigning to prevent clobbering if\n * base.js is loaded more than once.\n *\n * @const\n */\nvar goog = goog || {};\n\n/**\n * Reference to the global object.\n * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-object\n *\n * More info on this implementation here:\n * https://docs.google.com/document/d/1NAeW4Wk7I7FV0Y2tcUFvQdGMc89k2vdgSXInw8_nvCI/edit\n *\n * @const\n * @suppress {undefinedVars} self won't be referenced unless `this` is falsy.\n * @type {!Global}\n */\ngoog.global =\n // Check `this` first for backwards compatibility.\n // Valid unless running as an ES module or in a function wrapper called\n // without setting `this` properly.\n // Note that base.js can't usefully be imported as an ES module, but it may\n // be compiled into bundles that are loadable as ES modules.\n this ||\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/self\n // For in-page browser environments and workers.\n self;\n\n\n/**\n * A hook for overriding the define values in uncompiled mode.\n *\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\n * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\n * `goog.define` will use the value instead of the default value. This\n * allows flags to be overwritten without compilation (this is normally\n * accomplished with the compiler's \"define\" flag).\n *\n * Example:\n * <pre>\n * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\n\n\n/**\n * A hook for overriding the define values in uncompiled or compiled mode,\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\n *\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\n * string literals or the compiler will emit an error.\n *\n * While any @define value may be set, only those set with goog.define will be\n * effective for uncompiled code.\n *\n * Example:\n * <pre>\n * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_DEFINES;\n\n\n/**\n * Builds an object structure for the provided namespace path, ensuring that\n * names that already exist are not overwritten. For example:\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\n * Used by goog.provide and goog.exportSymbol.\n * @param {string} name name of the object that this file defines.\n * @param {*=} opt_object the object to expose at the end of the path.\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\n * is `goog.global`.\n * @private\n */\ngoog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {\n var parts = name.split('.');\n var cur = opt_objectToExportTo || goog.global;\n\n // Internet Explorer exhibits strange behavior when throwing errors from\n // methods externed in this manner. See the testExportSymbolExceptions in\n // base_test.html for an example.\n if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\n cur.execScript('var ' + parts[0]);\n }\n\n for (var part; parts.length && (part = parts.shift());) {\n if (!parts.length && opt_object !== undefined) {\n // last part and we have an object; use it\n cur[part] = opt_object;\n } else if (cur[part] && cur[part] !== Object.prototype[part]) {\n cur = cur[part];\n } else {\n cur = cur[part] = {};\n }\n }\n};\n\n\n/**\n * Defines a named value. In uncompiled mode, the value is retrieved from\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\n * has the property specified, and otherwise used the defined defaultValue.\n * When compiled the default can be overridden using the compiler options or the\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\n * can be used safely in modules. Note that the value type MUST be either\n * boolean, number, or string.\n *\n * @param {string} name The distinguished name to provide.\n * @param {T} defaultValue\n * @return {T} The defined value.\n * @template T\n */\ngoog.define = function(name, defaultValue) {\n var value = defaultValue;\n if (!COMPILED) {\n var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\n var defines = goog.global.CLOSURE_DEFINES;\n if (uncompiledDefines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\n value = uncompiledDefines[name];\n } else if (\n defines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (defines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(defines, name)) {\n value = defines[name];\n }\n }\n return value;\n};\n\n\n/**\n * @define {number} Integer year indicating the set of browser features that are\n * guaranteed to be present. This is defined to include exactly features that\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\n * specified year. For example,\n * ```js\n * if (goog.FEATURESET_YEAR >= 2019) {\n * // use APIs known to be available on all major stable browsers Jan 1, 2019\n * } else {\n * // polyfill for older browsers\n * }\n * ```\n * This is intended to be the primary define for removing\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\n * and should inform the default value for most other defines:\n * ```js\n * const ASSUME_NATIVE_PROMISE =\n * goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\n * ```\n *\n * The default assumption is that IE9 is the lowest supported browser, which was\n * first available Jan 1, 2012.\n *\n * TODO(user): Reference more thorough documentation when it's available.\n */\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\n\n\n/**\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\n * that should not be included in a production. It can be easily stripped\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\n * JSCompiler. For example, most toString() methods should be declared inside an\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\n * purposes and it is difficult for the JSCompiler to statically determine\n * whether they are used.\n */\ngoog.DEBUG = goog.define('goog.DEBUG', true);\n\n\n/**\n * @define {string} LOCALE defines the locale being used for compilation. It is\n * used to select locale specific data to be compiled in js binary. BUILD rule\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\n * option.\n *\n * Take into account that the locale code format is important. You should use\n * the canonical Unicode format with hyphen as a delimiter. Language must be\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\n *\n * See more info about locale codes here:\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\n *\n * For language codes you should use values defined by ISO 693-1. See it here\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\n * be used instead of the new code (he).\n *\n */\ngoog.LOCALE = goog.define('goog.LOCALE', 'en'); // default to en\n\n\n/**\n * @define {boolean} Whether this code is running on trusted sites.\n *\n * On untrusted sites, several native functions can be defined or overridden by\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\n * to false forces closure to use its own implementations when possible.\n *\n * If your JavaScript can be loaded by a third party site and you are wary about\n * relying on non-standard implementations, specify\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\n */\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\n\n\n/**\n * @define {boolean} Whether a project is expected to be running in strict mode.\n *\n * This define can be used to trigger alternate implementations compatible with\n * running in EcmaScript Strict mode or warn about unavailable functionality.\n * @see https://goo.gl/PudQ4y\n *\n */\ngoog.STRICT_MODE_COMPATIBLE = goog.define('goog.STRICT_MODE_COMPATIBLE', false);\n\n\n/**\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\n * be disallowed in the compilation unit.\n */\ngoog.DISALLOW_TEST_ONLY_CODE =\n goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\n\n\n/**\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\n * loading scripts via goog.require. @see appendScriptSrcNode_.\n */\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\n goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\n\n\n/**\n * Defines a namespace in Closure.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * The presence of one or more goog.provide() calls in a file indicates\n * that the file defines the given objects/namespaces.\n * Provided symbols must not be null or undefined.\n *\n * In addition, goog.provide() creates the object stubs for a namespace\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\n * goog.foo.bar if it does not already exist).\n *\n * Build tools also scan for provide/require/module statements\n * to discern dependencies, build dependency files (see deps.js), etc.\n *\n * @see goog.require\n * @see goog.module\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n */\ngoog.provide = function(name) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.provide cannot be used within a module.');\n }\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n }\n\n goog.constructNamespace_(name);\n};\n\n\n/**\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * @param {Object=} opt_obj The object to embed in the namespace.\n * @private\n */\ngoog.constructNamespace_ = function(name, opt_obj) {\n if (!COMPILED) {\n delete goog.implicitNamespaces_[name];\n\n var namespace = name;\n while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\n if (goog.getObjectByName(namespace)) {\n break;\n }\n goog.implicitNamespaces_[namespace] = true;\n }\n }\n\n goog.exportPath_(name, opt_obj);\n};\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\n * Defaults to global context.\n * @return {string} CSP nonce or empty string if no nonce is present.\n */\ngoog.getScriptNonce = function(opt_window) {\n if (opt_window && opt_window != goog.global) {\n return goog.getScriptNonce_(opt_window.document);\n }\n if (goog.cspNonce_ === null) {\n goog.cspNonce_ = goog.getScriptNonce_(goog.global.document);\n }\n return goog.cspNonce_;\n};\n\n\n/**\n * According to the CSP3 spec a nonce must be a valid base64 string.\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\n * @private @const\n */\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\n\n\n/**\n * @private {?string}\n */\ngoog.cspNonce_ = null;\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {!Document} doc\n * @return {string} CSP nonce or empty string if no nonce is present.\n * @private\n */\ngoog.getScriptNonce_ = function(doc) {\n var script = doc.querySelector && doc.querySelector('script[nonce]');\n if (script) {\n // Try to get the nonce from the IDL property first, because browsers that\n // implement additional nonce protection features (currently only Chrome) to\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\n // See https://github.com/whatwg/html/issues/2369\n var nonce = script['nonce'] || script.getAttribute('nonce');\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\n return nonce;\n }\n }\n return '';\n};\n\n\n/**\n * Module identifier validation regexp.\n * Note: This is a conservative check, it is very possible to be more lenient,\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\n * restrictions are intended to leave the door open for using goog.require\n * with relative file paths rather than module identifiers.\n * @private\n */\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\n\n\n/**\n * Defines a module in Closure.\n *\n * Marks that this file must be loaded as a module and claims the namespace.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * goog.module() has three requirements:\n * - goog.module may not be used in the same file as goog.provide.\n * - goog.module must be the first statement in the file.\n * - only one goog.module is allowed per file.\n *\n * When a goog.module annotated file is loaded, it is enclosed in\n * a strict function closure. This means that:\n * - any variables declared in a goog.module file are private to the file\n * (not global), though the compiler is expected to inline the module.\n * - The code must obey all the rules of \"strict\" JavaScript.\n * - the file will be marked as \"use strict\"\n *\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\n * itself. If declared symbols are desired, use\n * goog.module.declareLegacyNamespace().\n *\n *\n * See the public goog.module proposal: http://goo.gl/Va1hin\n *\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\", is expected but not required.\n * @return {void}\n */\ngoog.module = function(name) {\n if (typeof name !== 'string' || !name ||\n name.search(goog.VALID_MODULE_RE_) == -1) {\n throw new Error('Invalid module identifier');\n }\n if (!goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\n 'module. For more info see: ' +\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\n }\n if (goog.moduleLoaderState_.moduleName) {\n throw new Error('goog.module may only be called once per module.');\n }\n\n // Store the module name for the loader.\n goog.moduleLoaderState_.moduleName = name;\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n delete goog.implicitNamespaces_[name];\n }\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n *\n * Note: This is not an alternative to goog.require, it does not\n * indicate a hard dependency, instead it is used to indicate\n * an optional dependency or to access the exports of a module\n * that has already been loaded.\n * @suppress {missingProvide}\n */\ngoog.module.get = function(name) {\n return goog.module.getInternal_(name);\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n * @private\n */\ngoog.module.getInternal_ = function(name) {\n if (!COMPILED) {\n if (name in goog.loadedModules_) {\n return goog.loadedModules_[name].exports;\n } else if (!goog.implicitNamespaces_[name]) {\n var ns = goog.getObjectByName(name);\n return ns != null ? ns : null;\n }\n }\n return null;\n};\n\n\n/**\n * Types of modules the debug loader can load.\n * @enum {string}\n */\ngoog.ModuleType = {\n ES6: 'es6',\n GOOG: 'goog'\n};\n\n\n/**\n * @private {?{\n * moduleName: (string|undefined),\n * declareLegacyNamespace:boolean,\n * type: ?goog.ModuleType\n * }}\n */\ngoog.moduleLoaderState_ = null;\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module or an es6 module is currently being\n * initialized.\n */\ngoog.isInModuleLoader_ = function() {\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\n};\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module is currently being initialized.\n */\ngoog.isInGoogModuleLoader_ = function() {\n return !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\n};\n\n\n/**\n * @private\n * @return {boolean} Whether an es6 module is currently being initialized.\n */\ngoog.isInEs6ModuleLoader_ = function() {\n var inLoader = !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\n\n if (inLoader) {\n return true;\n }\n\n var jscomp = goog.global['$jscomp'];\n\n if (jscomp) {\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\n // that has some of the runtime, but not all of it. This can happen if\n // optimizations are turned on so the unused runtime is removed but renaming\n // and Closure pass are off (so $jscomp is still named $jscomp and the\n // goog.provide/require calls still exist).\n if (typeof jscomp.getCurrentModulePath != 'function') {\n return false;\n }\n\n // Bundled ES6 module.\n return !!jscomp.getCurrentModulePath();\n }\n\n return false;\n};\n\n\n/**\n * Provide the module's exports as a globally accessible object under the\n * module's declared name. This is intended to ease migration to goog.module\n * for files that have existing usages.\n * @suppress {missingProvide}\n */\ngoog.module.declareLegacyNamespace = function() {\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'goog.module.declareLegacyNamespace must be called from ' +\n 'within a goog.module');\n }\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.module must be called prior to ' +\n 'goog.module.declareLegacyNamespace.');\n }\n goog.moduleLoaderState_.declareLegacyNamespace = true;\n};\n\n\n/**\n * Associates an ES6 module with a Closure module ID so that is available via\n * goog.require. The associated ID acts like a goog.module ID - it does not\n * create any global names, it is merely available via goog.require /\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\n * goog.module.get will return the entire module as if it was import *'d. This\n * allows Closure files to reference ES6 modules for the sake of migration.\n *\n * @param {string} namespace\n * @suppress {missingProvide}\n */\ngoog.declareModuleId = function(namespace) {\n if (!COMPILED) {\n if (!goog.isInEs6ModuleLoader_()) {\n throw new Error(\n 'goog.declareModuleId may only be called from ' +\n 'within an ES6 module');\n }\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.declareModuleId may only be called once per module.');\n }\n if (namespace in goog.loadedModules_) {\n throw new Error(\n 'Module with namespace \"' + namespace + '\" already exists.');\n }\n }\n if (goog.moduleLoaderState_) {\n // Not bundled - debug loading.\n goog.moduleLoaderState_.moduleName = namespace;\n } else {\n // Bundled - not debug loading, no module loader state.\n var jscomp = goog.global['$jscomp'];\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\n throw new Error(\n 'Module with namespace \"' + namespace +\n '\" has been loaded incorrectly.');\n }\n var exports = jscomp.require(jscomp.getCurrentModulePath());\n goog.loadedModules_[namespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: namespace\n };\n }\n};\n\n\n/**\n * Marks that the current file should only be used for testing, and never for\n * live code in production.\n *\n * In the case of unit tests, the message may optionally be an exact namespace\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\n * provide (if not explicitly defined in the code).\n *\n * @param {string=} opt_message Optional message to add to the error that's\n * raised when used in production code.\n */\ngoog.setTestOnly = function(opt_message) {\n if (goog.DISALLOW_TEST_ONLY_CODE) {\n opt_message = opt_message || '';\n throw new Error(\n 'Importing test-only code into non-debug environment' +\n (opt_message ? ': ' + opt_message : '.'));\n }\n};\n\n\n/**\n * Forward declares a symbol. This is an indication to the compiler that the\n * symbol may be used in the source yet is not required and may not be provided\n * in compilation.\n *\n * The most common usage of forward declaration is code that takes a type as a\n * function parameter but does not need to require it. By forward declaring\n * instead of requiring, no hard dependency is made, and (if not required\n * elsewhere) the namespace may never be required and thus, not be pulled\n * into the JavaScript binary. If it is required elsewhere, it will be type\n * checked as normal.\n *\n * Before using goog.forwardDeclare, please read the documentation at\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\n * understand the options and tradeoffs when working with forward declarations.\n *\n * @param {string} name The namespace to forward declare in the form of\n * \"goog.package.part\".\n * @deprecated See go/noforwarddeclaration, Use `goog.requireType` instead.\n */\ngoog.forwardDeclare = function(name) {};\n\n\n/**\n * Forward declare type information. Used to assign types to goog.global\n * referenced object that would otherwise result in unknown type references\n * and thus block property disambiguation.\n */\ngoog.forwardDeclare('Document');\ngoog.forwardDeclare('HTMLScriptElement');\ngoog.forwardDeclare('XMLHttpRequest');\n\n\nif (!COMPILED) {\n /**\n * Check if the given name has been goog.provided. This will return false for\n * names that are available only as implicit namespaces.\n * @param {string} name name of the object to look for.\n * @return {boolean} Whether the name has been provided.\n * @private\n */\n goog.isProvided_ = function(name) {\n return (name in goog.loadedModules_) ||\n (!goog.implicitNamespaces_[name] && goog.getObjectByName(name) != null);\n };\n\n /**\n * Namespaces implicitly defined by goog.provide. For example,\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\n * 'goog.events' must be namespaces.\n *\n * @type {!Object<string, (boolean|undefined)>}\n * @private\n */\n goog.implicitNamespaces_ = {'goog.module': true};\n\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\n // here and because the existing module package has not been moved yet out of\n // the goog.module namespace. This satisifies both the debug loader and\n // ahead-of-time dependency management.\n}\n\n\n/**\n * Returns an object based on its fully qualified external name. The object\n * is not found if null or undefined. If you are using a compilation pass that\n * renames property names beware that using this function will not find renamed\n * properties.\n *\n * @param {string} name The fully qualified name.\n * @param {Object=} opt_obj The object within which to look; default is\n * |goog.global|.\n * @return {?} The value (object or primitive) or, if not found, null.\n */\ngoog.getObjectByName = function(name, opt_obj) {\n var parts = name.split('.');\n var cur = opt_obj || goog.global;\n for (var i = 0; i < parts.length; i++) {\n cur = cur[parts[i]];\n if (cur == null) {\n return null;\n }\n }\n return cur;\n};\n\n\n/**\n * Globalizes a whole namespace, such as goog or goog.lang.\n *\n * @param {!Object} obj The namespace to globalize.\n * @param {Object=} opt_global The object to add the properties to.\n * @deprecated Properties may be explicitly exported to the global scope, but\n * this should no longer be done in bulk.\n */\ngoog.globalize = function(obj, opt_global) {\n var global = opt_global || goog.global;\n for (var x in obj) {\n global[x] = obj[x];\n }\n};\n\n\n/**\n * Adds a dependency from a file to the files it requires.\n * @param {string} relPath The path to the js file.\n * @param {!Array<string>} provides An array of strings with\n * the names of the objects this file provides.\n * @param {!Array<string>} requires An array of strings with\n * the names of the objects this file requires.\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\n * how the file must be loaded. The boolean 'true' is equivalent\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\n */\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\n }\n};\n\n\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\n// to do \"debug-mode\" development. The dependency system can sometimes be\n// confusing, as can the debug DOM loader's asynchronous nature.\n//\n// With the DOM loader, a call to goog.require() is not blocking -- the script\n// will not load until some point after the current script. If a namespace is\n// needed at runtime, it needs to be defined in a previous script, or loaded via\n// require() with its registered dependencies.\n//\n// User-defined namespaces may need their own deps file. For a reference on\n// creating a deps file, see:\n// Externally: https://developers.google.com/closure/library/docs/depswriter\n//\n// Because of legacy clients, the DOM loader can't be easily removed from\n// base.js. Work was done to make it disableable or replaceable for\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\n// for example). See bootstrap/ for more information.\n\n\n/**\n * @define {boolean} Whether to enable the debug loader.\n *\n * If enabled, a call to goog.require() will attempt to load the namespace by\n * appending a script tag to the DOM (if the namespace has been registered).\n *\n * If disabled, goog.require() will simply assert that the namespace has been\n * provided (and depend on the fact that some outside tool correctly ordered\n * the script).\n */\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', true);\n\n\n/**\n * @param {string} msg\n * @private\n */\ngoog.logToConsole_ = function(msg) {\n if (goog.global.console) {\n goog.global.console['error'](msg);\n }\n};\n\n\n/**\n * Implements a system for the dynamic resolution of dependencies that works in\n * parallel with the BUILD system.\n *\n * Note that all calls to goog.require will be stripped by the compiler.\n *\n * @see goog.provide\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?} If called within a goog.module or ES6 module file, the associated\n * namespace or module otherwise null.\n */\ngoog.require = function(namespace) {\n if (!COMPILED) {\n // Might need to lazy load on old IE.\n if (goog.ENABLE_DEBUG_LOADER) {\n goog.debugLoader_.requested(namespace);\n }\n\n // If the object already exists we do not need to do anything.\n if (goog.isProvided_(namespace)) {\n if (goog.isInModuleLoader_()) {\n return goog.module.getInternal_(namespace);\n }\n } else if (goog.ENABLE_DEBUG_LOADER) {\n var moduleLoaderState = goog.moduleLoaderState_;\n goog.moduleLoaderState_ = null;\n try {\n goog.debugLoader_.load_(namespace);\n } finally {\n goog.moduleLoaderState_ = moduleLoaderState;\n }\n }\n\n return null;\n }\n};\n\n\n/**\n * Requires a symbol for its type information. This is an indication to the\n * compiler that the symbol may appear in type annotations, yet it is not\n * referenced at runtime.\n *\n * When called within a goog.module or ES6 module file, the return value may be\n * assigned to or destructured into a variable, but it may not be otherwise used\n * in code outside of a type annotation.\n *\n * Note that all calls to goog.requireType will be stripped by the compiler.\n *\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?}\n */\ngoog.requireType = function(namespace) {\n // Return an empty object so that single-level destructuring of the return\n // value doesn't crash at runtime when using the debug loader. Multi-level\n // destructuring isn't supported.\n return {};\n};\n\n\n/**\n * Path for included scripts.\n * @type {string}\n */\ngoog.basePath = '';\n\n\n/**\n * A hook for overriding the base path.\n * @type {string|undefined}\n */\ngoog.global.CLOSURE_BASE_PATH;\n\n\n/**\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\n * deps files will attempt to be loaded.\n * @type {boolean|undefined}\n */\ngoog.global.CLOSURE_NO_DEPS;\n\n\n/**\n * A function to import a single script. This is meant to be overridden when\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\n * in the global scope so that it can be set before base.js is loaded, which\n * allows deps.js to be imported properly.\n *\n * The first parameter the script source, which is a relative URI. The second,\n * optional parameter is the script contents, in the event the script needed\n * transformation. It should return true if the script was imported, false\n * otherwise.\n * @type {(function(string, string=): boolean)|undefined}\n */\ngoog.global.CLOSURE_IMPORT_SCRIPT;\n\n\n/**\n * Null function used for default values of callbacks, etc.\n * @return {void} Nothing.\n */\ngoog.nullFunction = function() {};\n\n\n/**\n * When defining a class Foo with an abstract method bar(), you can do:\n * Foo.prototype.bar = goog.abstractMethod\n *\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\n * when bar() is invoked.\n *\n * @type {!Function}\n * @throws {Error} when invoked to indicate the method should be overridden.\n * @deprecated Use \"@abstract\" annotation instead of goog.abstractMethod in new\n * code. See\n * https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\n */\ngoog.abstractMethod = function() {\n throw new Error('unimplemented abstract method');\n};\n\n\n/**\n * Adds a `getInstance` static method that always returns the same\n * instance object.\n * @param {!Function} ctor The constructor for the class to add the static\n * method to.\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\n * but we don't have a better type to use here.\n */\ngoog.addSingletonGetter = function(ctor) {\n // instance_ is immediately set to prevent issues with sealed constructors\n // such as are encountered when a constructor is returned as the export object\n // of a goog.module in unoptimized code.\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\n /** @type {undefined|!Object} @suppress {underscore} */\n ctor.instance_ = undefined;\n ctor.getInstance = function() {\n if (ctor.instance_) {\n return ctor.instance_;\n }\n if (goog.DEBUG) {\n // NOTE: JSCompiler can't optimize away Array#push.\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\n }\n // Cast to avoid conformance violations that ctor.instance_ is unknown\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\n };\n};\n\n\n/**\n * All singleton classes that have been instantiated, for testing. Don't read\n * it directly, use the `goog.testing.singleton` module. The compiler\n * removes this variable if unused.\n * @type {!Array<!Function>}\n * @private\n */\ngoog.instantiatedSingletons_ = [];\n\n\n/**\n * @define {boolean} Whether to load goog.modules using `eval` when using\n * the debug loader. This provides a better debugging experience as the\n * source is unmodified and can be edited using Chrome Workspaces or similar.\n * However in some environments the use of `eval` is banned\n * so we provide an alternative.\n */\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\n\n\n/**\n * @define {boolean} Whether the exports of goog.modules should be sealed when\n * possible.\n */\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\n\n\n/**\n * The registry of initialized modules:\n * The module identifier or path to module exports map.\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\n */\ngoog.loadedModules_ = {};\n\n\n/**\n * True if the debug loader enabled and used.\n * @const {boolean}\n */\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\n\n\n/**\n * @define {string} How to decide whether to transpile. Valid values\n * are 'always', 'never', and 'detect'. The default ('detect') is to\n * use feature detection to determine which language levels need\n * transpilation.\n */\n// NOTE(sdh): we could expand this to accept a language level to bypass\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\n// would leave ES3 and ES5 files alone.\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\n\n/**\n * @define {boolean} If true assume that ES modules have already been\n * transpiled by the jscompiler (in the same way that transpile.js would\n * transpile them - to jscomp modules). Useful only for servers that wish to use\n * the debug loader and transpile server side. Thus this is only respected if\n * goog.TRANSPILE is \"never\".\n */\ngoog.ASSUME_ES_MODULES_TRANSPILED =\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\n\n\n/**\n * @define {string} If a file needs to be transpiled what the output language\n * should be. By default this is the highest language level this file detects\n * the current environment supports. Generally this flag should not be set, but\n * it could be useful to override. Example: If the current environment supports\n * ES6 then by default ES7+ files will be transpiled to ES6, unless this is\n * overridden.\n *\n * Valid values include: es3, es5, es6, es7, and es8. Anything not recognized\n * is treated as es3.\n *\n * Note that setting this value does not force transpilation. Just if\n * transpilation occurs this will be the output. So this is most useful when\n * goog.TRANSPILE is set to 'always' and then forcing the language level to be\n * something lower than what the environment detects.\n */\ngoog.TRANSPILE_TO_LANGUAGE = goog.define('goog.TRANSPILE_TO_LANGUAGE', '');\n\n\n/**\n * @define {string} Path to the transpiler. Executing the script at this\n * path (relative to base.js) should define a function $jscomp.transpile.\n */\ngoog.TRANSPILER = goog.define('goog.TRANSPILER', 'transpile.js');\n\n\n/**\n * @package {?boolean}\n * Visible for testing.\n */\ngoog.hasBadLetScoping = null;\n\n\n/**\n * @return {boolean}\n * @package Visible for testing.\n */\ngoog.useSafari10Workaround = function() {\n if (goog.hasBadLetScoping == null) {\n var hasBadLetScoping;\n try {\n hasBadLetScoping = !eval(\n '\"use strict\";' +\n 'let x = 1; function f() { return typeof x; };' +\n 'f() == \"number\";');\n } catch (e) {\n // Assume that ES6 syntax isn't supported.\n hasBadLetScoping = false;\n }\n goog.hasBadLetScoping = hasBadLetScoping;\n }\n return goog.hasBadLetScoping;\n};\n\n\n/**\n * @param {string} moduleDef\n * @return {string}\n * @package Visible for testing.\n */\ngoog.workaroundSafari10EvalBug = function(moduleDef) {\n return '(function(){' + moduleDef +\n '\\n' + // Terminate any trailing single line comment.\n ';' + // Terminate any trailing expression.\n '})();\\n';\n};\n\n\n/**\n * @param {function(?):?|string} moduleDef The module definition.\n */\ngoog.loadModule = function(moduleDef) {\n // NOTE: we allow function definitions to be either in the from\n // of a string to eval (which keeps the original source intact) or\n // in a eval forbidden environment (CSP) we allow a function definition\n // which in its body must call `goog.module`, and return the exports\n // of the module.\n var previousState = goog.moduleLoaderState_;\n try {\n goog.moduleLoaderState_ = {\n moduleName: '',\n declareLegacyNamespace: false,\n type: goog.ModuleType.GOOG\n };\n var exports;\n if (goog.isFunction(moduleDef)) {\n exports = moduleDef.call(undefined, {});\n } else if (typeof moduleDef === 'string') {\n if (goog.useSafari10Workaround()) {\n moduleDef = goog.workaroundSafari10EvalBug(moduleDef);\n }\n\n exports = goog.loadModuleFromSource_.call(undefined, moduleDef);\n } else {\n throw new Error('Invalid module definition');\n }\n\n var moduleName = goog.moduleLoaderState_.moduleName;\n if (typeof moduleName === 'string' && moduleName) {\n // Don't seal legacy namespaces as they may be used as a parent of\n // another namespace\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\n goog.constructNamespace_(moduleName, exports);\n } else if (\n goog.SEAL_MODULE_EXPORTS && Object.seal &&\n typeof exports == 'object' && exports != null) {\n Object.seal(exports);\n }\n\n var data = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: goog.moduleLoaderState_.moduleName\n };\n goog.loadedModules_[moduleName] = data;\n } else {\n throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\n }\n } finally {\n goog.moduleLoaderState_ = previousState;\n }\n};\n\n\n/**\n * @private @const\n */\ngoog.loadModuleFromSource_ = /** @type {function(string):?} */ (function() {\n // NOTE: we avoid declaring parameters or local variables here to avoid\n // masking globals or leaking values into the module definition.\n 'use strict';\n var exports = {};\n eval(arguments[0]);\n return exports;\n});\n\n\n/**\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\n * path components.\n * @param {string} path\n * @return {string}\n * @private\n */\ngoog.normalizePath_ = function(path) {\n var components = path.split('/');\n var i = 0;\n while (i < components.length) {\n if (components[i] == '.') {\n components.splice(i, 1);\n } else if (\n i && components[i] == '..' && components[i - 1] &&\n components[i - 1] != '..') {\n components.splice(--i, 2);\n } else {\n i++;\n }\n }\n return components.join('/');\n};\n\n\n/**\n * Provides a hook for loading a file when using Closure's goog.require() API\n * with goog.modules. In particular this hook is provided to support Node.js.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\n\n\n/**\n * Loads file by synchronous XHR. Should not be used in production environments.\n * @param {string} src Source URL.\n * @return {?string} File contents, or null if load failed.\n * @private\n */\ngoog.loadFileSync_ = function(src) {\n if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\n return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\n } else {\n try {\n /** @type {XMLHttpRequest} */\n var xhr = new goog.global['XMLHttpRequest']();\n xhr.open('get', src, false);\n xhr.send();\n // NOTE: Successful http: requests have a status of 200, but successful\n // file: requests may have a status of zero. Any other status, or a\n // thrown exception (particularly in case of file: requests) indicates\n // some sort of error, which we treat as a missing or unavailable file.\n return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\n } catch (err) {\n // No need to rethrow or log, since errors should show up on their own.\n return null;\n }\n }\n};\n\n\n/**\n * Lazily retrieves the transpiler and applies it to the source.\n * @param {string} code JS code.\n * @param {string} path Path to the code.\n * @param {string} target Language level output.\n * @return {string} The transpiled code.\n * @private\n */\ngoog.transpile_ = function(code, path, target) {\n var jscomp = goog.global['$jscomp'];\n if (!jscomp) {\n goog.global['$jscomp'] = jscomp = {};\n }\n var transpile = jscomp.transpile;\n if (!transpile) {\n var transpilerPath = goog.basePath + goog.TRANSPILER;\n var transpilerCode = goog.loadFileSync_(transpilerPath);\n if (transpilerCode) {\n // This must be executed synchronously, since by the time we know we\n // need it, we're about to load and write the ES6 code synchronously,\n // so a normal script-tag load will be too slow. Wrapped in a function\n // so that code is eval'd in the global scope.\n (function() {\n (0, eval)(transpilerCode + '\\n//# sourceURL=' + transpilerPath);\n }).call(goog.global);\n // Even though the transpiler is optional, if $gwtExport is found, it's\n // a sign the transpiler was loaded and the $jscomp.transpile *should*\n // be there.\n if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] &&\n !goog.global['$gwtExport']['$jscomp']['transpile']) {\n throw new Error(\n 'The transpiler did not properly export the \"transpile\" ' +\n 'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport']));\n }\n // transpile.js only exports a single $jscomp function, transpile. We\n // grab just that and add it to the existing definition of $jscomp which\n // contains the polyfills.\n goog.global['$jscomp'].transpile =\n goog.global['$gwtExport']['$jscomp']['transpile'];\n jscomp = goog.global['$jscomp'];\n transpile = jscomp.transpile;\n }\n }\n if (!transpile) {\n // The transpiler is an optional component. If it's not available then\n // replace it with a pass-through function that simply logs.\n var suffix = ' requires transpilation but no transpiler was found.';\n transpile = jscomp.transpile = function(code, path) {\n // TODO(sdh): figure out some way to get this error to show up\n // in test results, noting that the failure may occur in many\n // different ways, including in loadModule() before the test\n // runner even comes up.\n goog.logToConsole_(path + suffix);\n return code;\n };\n }\n // Note: any transpilation errors/warnings will be logged to the console.\n return transpile(code, path, target);\n};\n\n//==============================================================================\n// Language Enhancements\n//==============================================================================\n\n\n/**\n * This is a \"fixed\" version of the typeof operator. It differs from the typeof\n * operator in such a way that null returns 'null' and arrays return 'array'.\n * @param {?} value The value to get the type of.\n * @return {string} The name of the type.\n */\ngoog.typeOf = function(value) {\n var s = typeof value;\n if (s == 'object') {\n if (value) {\n // Check these first, so we can avoid calling Object.prototype.toString if\n // possible.\n //\n // IE improperly marshals typeof across execution contexts, but a\n // cross-context object will still return false for \"instanceof Object\".\n if (value instanceof Array) {\n return 'array';\n } else if (value instanceof Object) {\n return s;\n }\n\n // HACK: In order to use an Object prototype method on the arbitrary\n // value, the compiler requires the value be cast to type Object,\n // even though the ECMA spec explicitly allows it.\n var className = Object.prototype.toString.call(\n /** @type {!Object} */ (value));\n // In Firefox 3.6, attempting to access iframe window objects' length\n // property throws an NS_ERROR_FAILURE, so we need to special-case it\n // here.\n if (className == '[object Window]') {\n return 'object';\n }\n\n // We cannot always use constructor == Array or instanceof Array because\n // different frames have different Array objects. In IE6, if the iframe\n // where the array was created is destroyed, the array loses its\n // prototype. Then dereferencing val.splice here throws an exception, so\n // we can't use goog.isFunction. Calling typeof directly returns 'unknown'\n // so that will work. In this case, this function will return false and\n // most array functions will still work because the array is still\n // array-like (supports length and []) even though it has lost its\n // prototype.\n // Mark Miller noticed that Object.prototype.toString\n // allows access to the unforgeable [[Class]] property.\n // 15.2.4.2 Object.prototype.toString ( )\n // When the toString method is called, the following steps are taken:\n // 1. Get the [[Class]] property of this object.\n // 2. Compute a string value by concatenating the three strings\n // \"[object \", Result(1), and \"]\".\n // 3. Return Result(2).\n // and this behavior survives the destruction of the execution context.\n if ((className == '[object Array]' ||\n // In IE all non value types are wrapped as objects across window\n // boundaries (not iframe though) so we have to do object detection\n // for this edge case.\n typeof value.length == 'number' &&\n typeof value.splice != 'undefined' &&\n typeof value.propertyIsEnumerable != 'undefined' &&\n !value.propertyIsEnumerable('splice')\n\n )) {\n return 'array';\n }\n // HACK: There is still an array case that fails.\n // function ArrayImpostor() {}\n // ArrayImpostor.prototype = [];\n // var impostor = new ArrayImpostor;\n // this can be fixed by getting rid of the fast path\n // (value instanceof Array) and solely relying on\n // (value && Object.prototype.toString.vall(value) === '[object Array]')\n // but that would require many more function calls and is not warranted\n // unless closure code is receiving objects from untrusted sources.\n\n // IE in cross-window calls does not correctly marshal the function type\n // (it appears just as an object) so we cannot use just typeof val ==\n // 'function'. However, if the object has a call property, it is a\n // function.\n if ((className == '[object Function]' ||\n typeof value.call != 'undefined' &&\n typeof value.propertyIsEnumerable != 'undefined' &&\n !value.propertyIsEnumerable('call'))) {\n return 'function';\n }\n\n } else {\n return 'null';\n }\n\n } else if (s == 'function' && typeof value.call == 'undefined') {\n // In Safari typeof nodeList returns 'function', and on Firefox typeof\n // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We\n // would like to return object for those and we can detect an invalid\n // function by making sure that the function object has a call method.\n return 'object';\n }\n return s;\n};\n\n\n/**\n * Returns true if the specified value is an array.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArray = function(val) {\n return goog.typeOf(val) == 'array';\n};\n\n\n/**\n * Returns true if the object looks like an array. To qualify as array like\n * the value needs to be either a NodeList or an object with a Number length\n * property. Note that for this function neither strings nor functions are\n * considered \"array-like\".\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArrayLike = function(val) {\n var type = goog.typeOf(val);\n // We do not use goog.isObject here in order to exclude function values.\n return type == 'array' || type == 'object' && typeof val.length == 'number';\n};\n\n\n/**\n * Returns true if the object looks like a Date. To qualify as Date-like the\n * value needs to be an object and have a getFullYear() function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a like a Date.\n */\ngoog.isDateLike = function(val) {\n return goog.isObject(val) && typeof val.getFullYear == 'function';\n};\n\n\n/**\n * Returns true if the specified value is a function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a function.\n */\ngoog.isFunction = function(val) {\n return goog.typeOf(val) == 'function';\n};\n\n\n/**\n * Returns true if the specified value is an object. This includes arrays and\n * functions.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an object.\n */\ngoog.isObject = function(val) {\n var type = typeof val;\n return type == 'object' && val != null || type == 'function';\n // return Object(val) === val also works, but is slower, especially if val is\n // not an object.\n};\n\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. The unique ID is\n * guaranteed to be unique across the current session amongst objects that are\n * passed into `getUid`. There is no guarantee that the ID is unique or\n * consistent across sessions. It is unsafe to generate unique ID for function\n * prototypes.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {number} The unique ID for the object.\n */\ngoog.getUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n return Object.prototype.hasOwnProperty.call(obj, goog.UID_PROPERTY_) &&\n obj[goog.UID_PROPERTY_] ||\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\n};\n\n\n/**\n * Whether the given object is already assigned a unique ID.\n *\n * This does not modify the object.\n *\n * @param {!Object} obj The object to check.\n * @return {boolean} Whether there is an assigned unique id for the object.\n */\ngoog.hasUid = function(obj) {\n return !!obj[goog.UID_PROPERTY_];\n};\n\n\n/**\n * Removes the unique ID from an object. This is useful if the object was\n * previously mutated using `goog.getUid` in which case the mutation is\n * undone.\n * @param {Object} obj The object to remove the unique ID field from.\n */\ngoog.removeUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n\n // In IE, DOM nodes are not instances of Object and throw an exception if we\n // try to delete. Instead we try to use removeAttribute.\n if (obj !== null && 'removeAttribute' in obj) {\n obj.removeAttribute(goog.UID_PROPERTY_);\n }\n\n try {\n delete obj[goog.UID_PROPERTY_];\n } catch (ex) {\n }\n};\n\n\n/**\n * Name for unique ID property. Initialized in a way to help avoid collisions\n * with other closure JavaScript on the same page.\n * @type {string}\n * @private\n */\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * Counter for UID.\n * @type {number}\n * @private\n */\ngoog.uidCounter_ = 0;\n\n\n/**\n * Adds a hash code field to an object. The hash code is unique for the\n * given object.\n * @param {Object} obj The object to get the hash code for.\n * @return {number} The hash code for the object.\n * @deprecated Use goog.getUid instead.\n */\ngoog.getHashCode = goog.getUid;\n\n\n/**\n * Removes the hash code field from an object.\n * @param {Object} obj The object to remove the field from.\n * @deprecated Use goog.removeUid instead.\n */\ngoog.removeHashCode = goog.removeUid;\n\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n *\n * WARNINGS:\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\n * refer to themselves will cause infinite recursion.\n *\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\n * UIDs created by <code>getUid</code> into cloned results.\n *\n * @param {*} obj The value to clone.\n * @return {*} A clone of the input value.\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\n */\ngoog.cloneObject = function(obj) {\n var type = goog.typeOf(obj);\n if (type == 'object' || type == 'array') {\n if (typeof obj.clone === 'function') {\n return obj.clone();\n }\n var clone = type == 'array' ? [] : {};\n for (var key in obj) {\n clone[key] = goog.cloneObject(obj[key]);\n }\n return clone;\n }\n\n return obj;\n};\n\n\n/**\n * A native implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindNative_ = function(fn, selfObj, var_args) {\n return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\n};\n\n\n/**\n * A pure-JS implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindJs_ = function(fn, selfObj, var_args) {\n if (!fn) {\n throw new Error();\n }\n\n if (arguments.length > 2) {\n var boundArgs = Array.prototype.slice.call(arguments, 2);\n return function() {\n // Prepend the bound arguments to the current arguments.\n var newArgs = Array.prototype.slice.call(arguments);\n Array.prototype.unshift.apply(newArgs, boundArgs);\n return fn.apply(selfObj, newArgs);\n };\n\n } else {\n return function() {\n return fn.apply(selfObj, arguments);\n };\n }\n};\n\n\n/**\n * Partially applies this function to a particular 'this object' and zero or\n * more arguments. The result is a new function with some arguments of the first\n * function pre-filled and the value of this 'pre-specified'.\n *\n * Remaining arguments specified at call-time are appended to the pre-specified\n * ones.\n *\n * Also see: {@link #partial}.\n *\n * Usage:\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\n * barMethBound('arg3', 'arg4');</pre>\n *\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @suppress {deprecated} See above.\n */\ngoog.bind = function(fn, selfObj, var_args) {\n // TODO(nicksantos): narrow the type signature.\n if (Function.prototype.bind &&\n // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\n // extension environment. This means that for Chrome extensions, they get\n // the implementation of Function.prototype.bind that calls goog.bind\n // instead of the native one. Even worse, we don't want to introduce a\n // circular dependency between goog.bind and Function.prototype.bind, so\n // we have to hack this to make sure it works correctly.\n Function.prototype.bind.toString().indexOf('native code') != -1) {\n goog.bind = goog.bindNative_;\n } else {\n goog.bind = goog.bindJs_;\n }\n return goog.bind.apply(null, arguments);\n};\n\n\n/**\n * Like goog.bind(), except that a 'this object' is not required. Useful when\n * the target function is already bound.\n *\n * Usage:\n * var g = goog.partial(f, arg1, arg2);\n * g(arg3, arg4);\n *\n * @param {Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.partial = function(fn, var_args) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function() {\n // Clone the array (with slice()) and append additional arguments\n // to the existing arguments.\n var newArgs = args.slice();\n newArgs.push.apply(newArgs, arguments);\n return fn.apply(/** @type {?} */ (this), newArgs);\n };\n};\n\n\n/**\n * Copies all the members of a source object to a target object. This method\n * does not work on all browsers for all objects that contain keys such as\n * toString or hasOwnProperty. Use goog.object.extend for this purpose.\n *\n * NOTE: Some have advocated for the use of goog.mixin to setup classes\n * with multiple inheritence (traits, mixins, etc). However, as it simply\n * uses \"for in\", this is not compatible with ES6 classes whose methods are\n * non-enumerable. Changing this, would break cases where non-enumerable\n * properties are not expected.\n *\n * @param {Object} target Target.\n * @param {Object} source Source.\n * @deprecated Prefer Object.assign\n */\ngoog.mixin = function(target, source) {\n for (var x in source) {\n target[x] = source[x];\n }\n\n // For IE7 or lower, the for-in-loop does not contain any properties that are\n // not enumerable on the prototype object (for example, isPrototypeOf from\n // Object.prototype) but also it will not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n};\n\n\n/**\n * @return {number} An integer value representing the number of milliseconds\n * between midnight, January 1, 1970 and the current time.\n * @deprecated Use Date.now\n */\ngoog.now = (goog.TRUSTED_SITE && Date.now) || (function() {\n // Unary plus operator converts its operand to a number which in\n // the case of\n // a date is done by calling getTime().\n return +new Date();\n });\n\n\n/**\n * Evals JavaScript in the global scope. In IE this uses execScript, other\n * browsers use goog.global.eval. If goog.global.eval does not evaluate in the\n * global scope (for example, in Safari), appends a script tag instead.\n * Throws an exception if neither execScript or eval is defined.\n * @param {string} script JavaScript string.\n */\ngoog.globalEval = function(script) {\n if (goog.global.execScript) {\n goog.global.execScript(script, 'JavaScript');\n } else if (goog.global.eval) {\n // Test to see if eval works\n if (goog.evalWorksForGlobals_ == null) {\n try {\n goog.global.eval('var _evalTest_ = 1;');\n } catch (ignore) {\n }\n if (typeof goog.global['_evalTest_'] != 'undefined') {\n try {\n delete goog.global['_evalTest_'];\n } catch (ignore) {\n // Microsoft edge fails the deletion above in strict mode.\n }\n goog.evalWorksForGlobals_ = true;\n } else {\n goog.evalWorksForGlobals_ = false;\n }\n }\n\n if (goog.evalWorksForGlobals_) {\n goog.global.eval(script);\n } else {\n /** @type {!Document} */\n var doc = goog.global.document;\n var scriptElt =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptElt.type = 'text/javascript';\n scriptElt.defer = false;\n // Note(user): can't use .innerHTML since \"t('<test>')\" will fail and\n // .text doesn't work in Safari 2. Therefore we append a text node.\n scriptElt.appendChild(doc.createTextNode(script));\n doc.head.appendChild(scriptElt);\n doc.head.removeChild(scriptElt);\n }\n } else {\n throw new Error('goog.globalEval not available');\n }\n};\n\n\n/**\n * Indicates whether or not we can call 'eval' directly to eval code in the\n * global scope. Set to a Boolean by the first call to goog.globalEval (which\n * empirically tests whether eval works for globals). @see goog.globalEval\n * @type {?boolean}\n * @private\n */\ngoog.evalWorksForGlobals_ = null;\n\n\n/**\n * Optional map of CSS class names to obfuscated names used with\n * goog.getCssName().\n * @private {!Object<string, string>|undefined}\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMapping_;\n\n\n/**\n * Optional obfuscation style for CSS class names. Should be set to either\n * 'BY_WHOLE' or 'BY_PART' if defined.\n * @type {string|undefined}\n * @private\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMappingStyle_;\n\n\n\n/**\n * A hook for modifying the default behavior goog.getCssName. The function\n * if present, will receive the standard output of the goog.getCssName as\n * its input.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\n\n\n/**\n * Handles strings that are intended to be used as CSS class names.\n *\n * This function works in tandem with @see goog.setCssNameMapping.\n *\n * Without any mapping set, the arguments are simple joined with a hyphen and\n * passed through unaltered.\n *\n * When there is a mapping, there are two possible styles in which these\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\n * style, the full css name is looked up in the map directly. If a rewrite is\n * not specified by the map, the compiler will output a warning.\n *\n * When the mapping is passed to the compiler, it will replace calls to\n * goog.getCssName with the strings from the mapping, e.g.\n * var x = goog.getCssName('foo');\n * var y = goog.getCssName(this.baseClass, 'active');\n * becomes:\n * var x = 'foo';\n * var y = this.baseClass + '-active';\n *\n * If one argument is passed it will be processed, if two are passed only the\n * modifier will be processed, as it is assumed the first argument was generated\n * as a result of calling goog.getCssName.\n *\n * @param {string} className The class name.\n * @param {string=} opt_modifier A modifier to be appended to the class name.\n * @return {string} The class name or the concatenation of the class name and\n * the modifier.\n */\ngoog.getCssName = function(className, opt_modifier) {\n // String() is used for compatibility with compiled soy where the passed\n // className can be non-string objects.\n if (String(className).charAt(0) == '.') {\n throw new Error(\n 'className passed in goog.getCssName must not start with \".\".' +\n ' You passed: ' + className);\n }\n\n var getMapping = function(cssName) {\n return goog.cssNameMapping_[cssName] || cssName;\n };\n\n var renameByParts = function(cssName) {\n // Remap all the parts individually.\n var parts = cssName.split('-');\n var mapped = [];\n for (var i = 0; i < parts.length; i++) {\n mapped.push(getMapping(parts[i]));\n }\n return mapped.join('-');\n };\n\n var rename;\n if (goog.cssNameMapping_) {\n rename =\n goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\n } else {\n rename = function(a) {\n return a;\n };\n }\n\n var result =\n opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\n\n // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\n // processing of the class name.\n if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\n return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\n }\n\n return result;\n};\n\n\n/**\n * Sets the map to check when returning a value from goog.getCssName(). Example:\n * <pre>\n * goog.setCssNameMapping({\n * \"goog\": \"a\",\n * \"disabled\": \"b\",\n * });\n *\n * var x = goog.getCssName('goog');\n * // The following evaluates to: \"a a-b\".\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\n * </pre>\n * When declared as a map of string literals to string literals, the JSCompiler\n * will replace all calls to goog.getCssName() using the supplied map if the\n * --process_closure_primitives flag is set.\n *\n * @param {!Object} mapping A map of strings to strings where keys are possible\n * arguments to goog.getCssName() and values are the corresponding values\n * that should be returned.\n * @param {string=} opt_style The style of css name mapping. There are two valid\n * options: 'BY_PART', and 'BY_WHOLE'.\n * @see goog.getCssName for a description.\n */\ngoog.setCssNameMapping = function(mapping, opt_style) {\n goog.cssNameMapping_ = mapping;\n goog.cssNameMappingStyle_ = opt_style;\n};\n\n\n/**\n * To use CSS renaming in compiled mode, one of the input files should have a\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\n * mode, JavaScript code should be loaded before this base.js file that declares\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\n * are made in uncompiled mode.\n *\n * A hook for overriding the CSS name mapping.\n * @type {!Object<string, string>|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\n\n\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\n // This does not call goog.setCssNameMapping() because the JSCompiler\n // requires that goog.setCssNameMapping() be called with an object literal.\n goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\n}\n\n\n/**\n * Gets a localized message.\n *\n * This function is a compiler primitive. If you give the compiler a localized\n * message bundle, it will replace the string at compile-time with a localized\n * version, and expand goog.getMsg call to a concatenated string.\n *\n * Messages must be initialized in the form:\n * <code>\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n * </code>\n *\n * This function produces a string which should be treated as plain text. Use\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n * produce SafeHtml.\n *\n * @param {string} str Translatable string, places holders in the form {$foo}.\n * @param {Object<string, string>=} opt_values Maps place holder name to value.\n * @param {{html: boolean}=} opt_options Options:\n * html: Escape '<' in str to '&lt;'. Used by Closure Templates where the\n * generated code size and performance is critical which is why {@link\n * goog.html.SafeHtmlFormatter} is not used. The value must be literal true\n * or false.\n * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values, opt_options) {\n if (opt_options && opt_options.html) {\n // Note that '&' is not replaced because the translation can contain HTML\n // entities.\n str = str.replace(/</g, '&lt;');\n }\n if (opt_values) {\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\n return (opt_values != null && key in opt_values) ? opt_values[key] :\n match;\n });\n }\n return str;\n};\n\n\n/**\n * Gets a localized message. If the message does not have a translation, gives a\n * fallback message.\n *\n * This is useful when introducing a new message that has not yet been\n * translated into all languages.\n *\n * This function is a compiler primitive. Must be used in the form:\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n * where MSG_A and MSG_B were initialized with goog.getMsg.\n *\n * @param {string} a The preferred message.\n * @param {string} b The fallback message.\n * @return {string} The best translated message.\n */\ngoog.getMsgWithFallback = function(a, b) {\n return a;\n};\n\n\n/**\n * Exposes an unobfuscated global namespace path for the given object.\n * Note that fields of the exported object *will* be obfuscated, unless they are\n * exported in turn via this function or goog.exportProperty.\n *\n * Also handy for making public items that are defined in anonymous closures.\n *\n * ex. goog.exportSymbol('public.path.Foo', Foo);\n *\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n * public.path.Foo.staticFunction();\n *\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n * Foo.prototype.myMethod);\n * new public.path.Foo().myMethod();\n *\n * @param {string} publicPath Unobfuscated name to export.\n * @param {*} object Object the name should point to.\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\n * is goog.global.\n */\ngoog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {\n goog.exportPath_(publicPath, object, opt_objectToExportTo);\n};\n\n\n/**\n * Exports a property unobfuscated into the object's namespace.\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\n * @param {Object} object Object whose static property is being exported.\n * @param {string} publicName Unobfuscated name to export.\n * @param {*} symbol Object the name should point to.\n */\ngoog.exportProperty = function(object, publicName, symbol) {\n object[publicName] = symbol;\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * Usage:\n * <pre>\n * function ParentClass(a, b) { }\n * ParentClass.prototype.foo = function(a) { };\n *\n * function ChildClass(a, b, c) {\n * ChildClass.base(this, 'constructor', a, b);\n * }\n * goog.inherits(ChildClass, ParentClass);\n *\n * var child = new ChildClass('a', 'b', 'see');\n * child.foo(); // This works.\n * </pre>\n *\n * @param {!Function} childCtor Child class.\n * @param {!Function} parentCtor Parent class.\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\n * Function.\n */\ngoog.inherits = function(childCtor, parentCtor) {\n /** @constructor */\n function tempCtor() {}\n tempCtor.prototype = parentCtor.prototype;\n childCtor.superClass_ = parentCtor.prototype;\n childCtor.prototype = new tempCtor();\n /** @override */\n childCtor.prototype.constructor = childCtor;\n\n /**\n * Calls superclass constructor/method.\n *\n * This function is only available if you use goog.inherits to\n * express inheritance relationships between classes.\n *\n * NOTE: This is a replacement for goog.base and for superClass_\n * property defined in childCtor.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {string} methodName The method name to call. Calling\n * superclass constructor can be done with the special string\n * 'constructor'.\n * @param {...*} var_args The arguments to pass to superclass\n * method/constructor.\n * @return {*} The return value of the superclass method/constructor.\n */\n childCtor.base = function(me, methodName, var_args) {\n // Copying using loop to avoid deop due to passing arguments object to\n // function. This is faster in many JS engines as of late 2014.\n var args = new Array(arguments.length - 2);\n for (var i = 2; i < arguments.length; i++) {\n args[i - 2] = arguments[i];\n }\n return parentCtor.prototype[methodName].apply(me, args);\n };\n};\n\n\n/**\n * Allow for aliasing within scope functions. This function exists for\n * uncompiled code - in compiled code the calls will be inlined and the aliases\n * applied. In uncompiled code the function is simply run since the aliases as\n * written are valid JavaScript.\n *\n *\n * @param {function()} fn Function to call. This function can contain aliases\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\n * (e.g. \"var Timer = goog.Timer\").\n * @deprecated Use goog.module instead.\n */\ngoog.scope = function(fn) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.scope is not supported within a module.');\n }\n fn.call(goog.global);\n};\n\n\n/*\n * To support uncompiled, strict mode bundles that use eval to divide source\n * like so:\n * eval('someSource;//# sourceUrl sourcefile.js');\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\n * be defined externally.\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\n * extern generation when that compiler option is enabled.\n */\nif (!COMPILED) {\n goog.global['COMPILED'] = COMPILED;\n}\n\n\n//==============================================================================\n// goog.defineClass implementation\n//==============================================================================\n\n\n/**\n * Creates a restricted form of a Closure \"class\":\n * - from the compiler's perspective, the instance returned from the\n * constructor is sealed (no new properties may be added). This enables\n * better checks.\n * - the compiler will rewrite this definition to a form that is optimal\n * for type checking and optimization (initially this will be a more\n * traditional form).\n *\n * @param {Function} superClass The superclass, Object or null.\n * @param {goog.defineClass.ClassDescriptor} def\n * An object literal describing\n * the class. It may have the following properties:\n * \"constructor\": the constructor function\n * \"statics\": an object literal containing methods to add to the constructor\n * as \"static\" methods or a function that will receive the constructor\n * function as its only parameter to which static properties can\n * be added.\n * all other properties are added to the prototype.\n * @return {!Function} The class constructor.\n * @deprecated Use ES6 class syntax instead.\n */\ngoog.defineClass = function(superClass, def) {\n // TODO(johnlenz): consider making the superClass an optional parameter.\n var constructor = def.constructor;\n var statics = def.statics;\n // Wrap the constructor prior to setting up the prototype and static methods.\n if (!constructor || constructor == Object.prototype.constructor) {\n constructor = function() {\n throw new Error(\n 'cannot instantiate an interface (no constructor defined).');\n };\n }\n\n var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\n if (superClass) {\n goog.inherits(cls, superClass);\n }\n\n // Remove all the properties that should not be copied to the prototype.\n delete def.constructor;\n delete def.statics;\n\n goog.defineClass.applyProperties_(cls.prototype, def);\n if (statics != null) {\n if (statics instanceof Function) {\n statics(cls);\n } else {\n goog.defineClass.applyProperties_(cls, statics);\n }\n }\n\n return cls;\n};\n\n\n/**\n * @typedef {{\n * constructor: (!Function|undefined),\n * statics: (Object|undefined|function(Function):void)\n * }}\n */\ngoog.defineClass.ClassDescriptor;\n\n\n/**\n * @define {boolean} Whether the instances returned by goog.defineClass should\n * be sealed when possible.\n *\n * When sealing is disabled the constructor function will not be wrapped by\n * goog.defineClass, making it incompatible with ES6 class methods.\n */\ngoog.defineClass.SEAL_CLASS_INSTANCES =\n goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\n\n\n/**\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\n * defined, this function will wrap the constructor in a function that seals the\n * results of the provided constructor function.\n *\n * @param {!Function} ctr The constructor whose results maybe be sealed.\n * @param {Function} superClass The superclass constructor.\n * @return {!Function} The replacement constructor.\n * @private\n */\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\n if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\n // Do now wrap the constructor when sealing is disabled. Angular code\n // depends on this for injection to work properly.\n return ctr;\n }\n\n // Compute whether the constructor is sealable at definition time, rather\n // than when the instance is being constructed.\n var superclassSealable = !goog.defineClass.isUnsealable_(superClass);\n\n /**\n * @this {Object}\n * @return {?}\n */\n var wrappedCtr = function() {\n // Don't seal an instance of a subclass when it calls the constructor of\n // its super class as there is most likely still setup to do.\n var instance = ctr.apply(this, arguments) || this;\n instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\n\n if (this.constructor === wrappedCtr && superclassSealable &&\n Object.seal instanceof Function) {\n Object.seal(instance);\n }\n return instance;\n };\n\n return wrappedCtr;\n};\n\n\n/**\n * @param {Function} ctr The constructor to test.\n * @return {boolean} Whether the constructor has been tagged as unsealable\n * using goog.tagUnsealableClass.\n * @private\n */\ngoog.defineClass.isUnsealable_ = function(ctr) {\n return ctr && ctr.prototype &&\n ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_];\n};\n\n\n// TODO(johnlenz): share these values with the goog.object\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n * @private\n * @const\n */\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\n 'toLocaleString', 'toString', 'valueOf'\n];\n\n\n// TODO(johnlenz): share this function with the goog.object\n/**\n * @param {!Object} target The object to add properties to.\n * @param {!Object} source The object to copy properties from.\n * @private\n */\ngoog.defineClass.applyProperties_ = function(target, source) {\n // TODO(johnlenz): update this to support ES5 getters/setters\n\n var key;\n for (key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\n key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n};\n\n\n/**\n * Sealing classes breaks the older idiom of assigning properties on the\n * prototype rather than in the constructor. As such, goog.defineClass\n * must not seal subclasses of these old-style classes until they are fixed.\n * Until then, this marks a class as \"broken\", instructing defineClass\n * not to seal subclasses.\n * @param {!Function} ctr The legacy constructor to tag as unsealable.\n */\ngoog.tagUnsealableClass = function(ctr) {\n if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {\n ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;\n }\n};\n\n\n/**\n * Name for unsealable tag property.\n * @const @private {string}\n */\ngoog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';\n\n\n// There's a bug in the compiler where without collapse properties the\n// Closure namespace defines do not guard code correctly. To help reduce code\n// size also check for !COMPILED even though it redundant until this is fixed.\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n\n /**\n * Tries to detect whether is in the context of an HTML document.\n * @return {boolean} True if it looks like HTML document.\n * @private\n */\n goog.inHtmlDocument_ = function() {\n /** @type {!Document} */\n var doc = goog.global.document;\n return doc != null && 'write' in doc; // XULDocument misses write.\n };\n\n\n /**\n * We'd like to check for if the document readyState is 'loading'; however\n * there are bugs on IE 10 and below where the readyState being anything other\n * than 'complete' is not reliable.\n * @return {boolean}\n * @private\n */\n goog.isDocumentLoading_ = function() {\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\n // detect those browsers.\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n return doc.attachEvent ? doc.readyState != 'complete' :\n doc.readyState == 'loading';\n };\n\n\n /**\n * Tries to detect the base path of base.js script that bootstraps Closure.\n * @private\n */\n goog.findBasePath_ = function() {\n if (goog.global.CLOSURE_BASE_PATH != undefined &&\n // Anti DOM-clobbering runtime check (b/37736576).\n typeof goog.global.CLOSURE_BASE_PATH === 'string') {\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\n return;\n } else if (!goog.inHtmlDocument_()) {\n return;\n }\n /** @type {!Document} */\n var doc = goog.global.document;\n // If we have a currentScript available, use it exclusively.\n var currentScript = doc.currentScript;\n if (currentScript) {\n var scripts = [currentScript];\n } else {\n var scripts = doc.getElementsByTagName('SCRIPT');\n }\n // Search backwards since the current script is in almost all cases the one\n // that has base.js.\n for (var i = scripts.length - 1; i >= 0; --i) {\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\n var src = script.src;\n var qmark = src.lastIndexOf('?');\n var l = qmark == -1 ? src.length : qmark;\n if (src.substr(l - 7, 7) == 'base.js') {\n goog.basePath = src.substr(0, l - 7);\n return;\n }\n }\n };\n\n goog.findBasePath_();\n\n /** @struct @constructor @final */\n goog.Transpiler = function() {\n /** @private {?Object<string, boolean>} */\n this.requiresTranspilation_ = null;\n /** @private {string} */\n this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;\n };\n /**\n * Returns a newly created map from language mode string to a boolean\n * indicating whether transpilation should be done for that mode as well as\n * the highest level language that this environment supports.\n *\n * Guaranteed invariant:\n * For any two modes, l1 and l2 where l2 is a newer mode than l1,\n * `map[l1] == true` implies that `map[l2] == true`.\n *\n * Note this method is extracted and used elsewhere, so it cannot rely on\n * anything external (it should easily be able to be transformed into a\n * standalone, top level function).\n *\n * @private\n * @return {{\n * target: string,\n * map: !Object<string, boolean>\n * }}\n */\n goog.Transpiler.prototype.createRequiresTranspilation_ = function() {\n var transpilationTarget = 'es3';\n var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false};\n var transpilationRequiredForAllLaterModes = false;\n\n /**\n * Adds an entry to requiresTranspliation for the given language mode.\n *\n * IMPORTANT: Calls must be made in order from oldest to newest language\n * mode.\n * @param {string} modeName\n * @param {function(): boolean} isSupported Returns true if the JS engine\n * supports the given mode.\n */\n function addNewerLanguageTranspilationCheck(modeName, isSupported) {\n if (transpilationRequiredForAllLaterModes) {\n requiresTranspilation[modeName] = true;\n } else if (isSupported()) {\n transpilationTarget = modeName;\n requiresTranspilation[modeName] = false;\n } else {\n requiresTranspilation[modeName] = true;\n transpilationRequiredForAllLaterModes = true;\n }\n }\n\n /**\n * Does the given code evaluate without syntax errors and return a truthy\n * result?\n */\n function /** boolean */ evalCheck(/** string */ code) {\n try {\n return !!eval(code);\n } catch (ignored) {\n return false;\n }\n }\n\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\n goog.global.navigator.userAgent :\n '';\n\n // Identify ES3-only browsers by their incorrect treatment of commas.\n addNewerLanguageTranspilationCheck('es5', function() {\n return evalCheck('[1,].length==1');\n });\n addNewerLanguageTranspilationCheck('es6', function() {\n // Edge has a non-deterministic (i.e., not reproducible) bug with ES6:\n // https://github.com/Microsoft/ChakraCore/issues/1496.\n var re = /Edge\\/(\\d+)(\\.\\d)*/i;\n var edgeUserAgent = userAgent.match(re);\n if (edgeUserAgent) {\n // The Reflect.construct test below is flaky on Edge. It can sometimes\n // pass or fail on 40 15.15063, so just exit early for Edge and treat\n // it as ES5. Until we're on a more up to date version just always use\n // ES5. See https://github.com/Microsoft/ChakraCore/issues/3217.\n return false;\n }\n // Test es6: [FF50 (?), Edge 14 (?), Chrome 50]\n // (a) default params (specifically shadowing locals),\n // (b) destructuring, (c) block-scoped functions,\n // (d) for-of (const), (e) new.target/Reflect.construct\n var es6fullTest =\n 'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' +\n 'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' +\n 'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' +\n 'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' +\n '==3}';\n\n return evalCheck('(()=>{\"use strict\";' + es6fullTest + '})()');\n });\n // ** and **= are the only new features in 'es7'\n addNewerLanguageTranspilationCheck('es7', function() {\n return evalCheck('2 ** 2 == 4');\n });\n // async functions are the only new features in 'es8'\n addNewerLanguageTranspilationCheck('es8', function() {\n return evalCheck('async () => 1, true');\n });\n addNewerLanguageTranspilationCheck('es9', function() {\n return evalCheck('({...rest} = {}), true');\n });\n addNewerLanguageTranspilationCheck('es_next', function() {\n return false; // assume it always need to transpile\n });\n return {target: transpilationTarget, map: requiresTranspilation};\n };\n\n\n /**\n * Determines whether the given language needs to be transpiled.\n * @param {string} lang\n * @param {string|undefined} module\n * @return {boolean}\n */\n goog.Transpiler.prototype.needsTranspile = function(lang, module) {\n if (goog.TRANSPILE == 'always') {\n return true;\n } else if (goog.TRANSPILE == 'never') {\n return false;\n } else if (!this.requiresTranspilation_) {\n var obj = this.createRequiresTranspilation_();\n this.requiresTranspilation_ = obj.map;\n this.transpilationTarget_ = this.transpilationTarget_ || obj.target;\n }\n if (lang in this.requiresTranspilation_) {\n if (this.requiresTranspilation_[lang]) {\n return true;\n } else if (\n goog.inHtmlDocument_() && module == 'es6' &&\n !('noModule' in goog.global.document.createElement('script'))) {\n return true;\n } else {\n return false;\n }\n } else {\n throw new Error('Unknown language mode: ' + lang);\n }\n };\n\n\n /**\n * Lazily retrieves the transpiler and applies it to the source.\n * @param {string} code JS code.\n * @param {string} path Path to the code.\n * @return {string} The transpiled code.\n */\n goog.Transpiler.prototype.transpile = function(code, path) {\n // TODO(johnplaisted): We should delete goog.transpile_ and just have this\n // function. But there's some compile error atm where goog.global is being\n // stripped incorrectly without this.\n return goog.transpile_(code, path, this.transpilationTarget_);\n };\n\n\n /** @private @final {!goog.Transpiler} */\n goog.transpiler_ = new goog.Transpiler();\n\n /**\n * Rewrites closing script tags in input to avoid ending an enclosing script\n * tag.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n goog.protectScriptTag_ = function(str) {\n return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\n };\n\n\n /**\n * A debug loader is responsible for downloading and executing javascript\n * files in an unbundled, uncompiled environment.\n *\n * This can be custimized via the setDependencyFactory method, or by\n * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\n *\n * @struct @constructor @final @private\n */\n goog.DebugLoader_ = function() {\n /** @private @const {!Object<string, !goog.Dependency>} */\n this.dependencies_ = {};\n /** @private @const {!Object<string, string>} */\n this.idToPath_ = {};\n /** @private @const {!Object<string, boolean>} */\n this.written_ = {};\n /** @private @const {!Array<!goog.Dependency>} */\n this.loadingDeps_ = [];\n /** @private {!Array<!goog.Dependency>} */\n this.depsToLoad_ = [];\n /** @private {boolean} */\n this.paused_ = false;\n /** @private {!goog.DependencyFactory} */\n this.factory_ = new goog.DependencyFactory(goog.transpiler_);\n /** @private @const {!Object<string, !Function>} */\n this.deferredCallbacks_ = {};\n /** @private @const {!Array<string>} */\n this.deferredQueue_ = [];\n };\n\n /**\n * @param {!Array<string>} namespaces\n * @param {function(): undefined} callback Function to call once all the\n * namespaces have loaded.\n */\n goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\n var cb = callback;\n function resolve() {\n if (cb) {\n goog.global.setTimeout(cb, 0);\n cb = null;\n }\n }\n\n if (!namespaces.length) {\n resolve();\n return;\n }\n\n var deps = [];\n for (var i = 0; i < namespaces.length; i++) {\n var path = this.getPathFromDeps_(namespaces[i]);\n if (!path) {\n throw new Error('Unregonized namespace: ' + namespaces[i]);\n }\n deps.push(this.dependencies_[path]);\n }\n\n var require = goog.require;\n var loaded = 0;\n for (var i = 0; i < namespaces.length; i++) {\n require(namespaces[i]);\n deps[i].onLoad(function() {\n if (++loaded == namespaces.length) {\n resolve();\n }\n });\n }\n };\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.DebugLoader_.prototype.loadClosureDeps = function() {\n // Circumvent addDependency, which would try to transpile deps.js if\n // transpile is set to always.\n var relPath = 'deps.js';\n this.depsToLoad_.push(this.factory_.createDependency(\n goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {},\n false));\n this.loadDeps_();\n };\n\n\n /**\n * Notifies the debug loader when a dependency has been requested.\n *\n * @param {string} absPathOrId Path of the dependency or goog id.\n * @param {boolean=} opt_force\n */\n goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\n var path = this.getPathFromDeps_(absPathOrId);\n if (path &&\n (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\n var callback = this.deferredCallbacks_[path];\n if (callback) {\n delete this.deferredCallbacks_[path];\n callback();\n }\n }\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\n this.factory_ = factory;\n };\n\n\n /**\n * Travserses the dependency graph and queues the given dependency, and all of\n * its transitive dependencies, for loading and then starts loading if not\n * paused.\n *\n * @param {string} namespace\n * @private\n */\n goog.DebugLoader_.prototype.load_ = function(namespace) {\n if (!this.getPathFromDeps_(namespace)) {\n var errorMessage = 'goog.require could not find: ' + namespace;\n\n goog.logToConsole_(errorMessage);\n throw Error(errorMessage);\n } else {\n var loader = this;\n\n var deps = [];\n\n /** @param {string} namespace */\n var visit = function(namespace) {\n var path = loader.getPathFromDeps_(namespace);\n\n if (!path) {\n throw new Error('Bad dependency path or symbol: ' + namespace);\n }\n\n if (loader.written_[path]) {\n return;\n }\n\n loader.written_[path] = true;\n\n var dep = loader.dependencies_[path];\n for (var i = 0; i < dep.requires.length; i++) {\n if (!goog.isProvided_(dep.requires[i])) {\n visit(dep.requires[i]);\n }\n }\n\n deps.push(dep);\n };\n\n visit(namespace);\n\n var wasLoading = !!this.depsToLoad_.length;\n this.depsToLoad_ = this.depsToLoad_.concat(deps);\n\n if (!this.paused_ && !wasLoading) {\n this.loadDeps_();\n }\n }\n };\n\n\n /**\n * Loads any queued dependencies until they are all loaded or paused.\n *\n * @private\n */\n goog.DebugLoader_.prototype.loadDeps_ = function() {\n var loader = this;\n var paused = this.paused_;\n\n while (this.depsToLoad_.length && !paused) {\n (function() {\n var loadCallDone = false;\n var dep = loader.depsToLoad_.shift();\n\n var loaded = false;\n loader.loading_(dep);\n\n var controller = {\n pause: function() {\n if (loadCallDone) {\n throw new Error('Cannot call pause after the call to load.');\n } else {\n paused = true;\n }\n },\n resume: function() {\n if (loadCallDone) {\n loader.resume_();\n } else {\n // Some dep called pause and then resume in the same load call.\n // Just keep running this same loop.\n paused = false;\n }\n },\n loaded: function() {\n if (loaded) {\n throw new Error('Double call to loaded.');\n }\n\n loaded = true;\n loader.loaded_(dep);\n },\n pending: function() {\n // Defensive copy.\n var pending = [];\n for (var i = 0; i < loader.loadingDeps_.length; i++) {\n pending.push(loader.loadingDeps_[i]);\n }\n return pending;\n },\n /**\n * @param {goog.ModuleType} type\n */\n setModuleState: function(type) {\n goog.moduleLoaderState_ = {\n type: type,\n moduleName: '',\n declareLegacyNamespace: false\n };\n },\n /** @type {function(string, string, string=)} */\n registerEs6ModuleExports: function(\n path, exports, opt_closureNamespace) {\n if (opt_closureNamespace) {\n goog.loadedModules_[opt_closureNamespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: opt_closureNamespace || ''\n };\n }\n },\n /** @type {function(string, ?)} */\n registerGoogModuleExports: function(moduleId, exports) {\n goog.loadedModules_[moduleId] = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: moduleId\n };\n },\n clearModuleState: function() {\n goog.moduleLoaderState_ = null;\n },\n defer: function(callback) {\n if (loadCallDone) {\n throw new Error(\n 'Cannot register with defer after the call to load.');\n }\n loader.defer_(dep, callback);\n },\n areDepsLoaded: function() {\n return loader.areDepsLoaded_(dep.requires);\n }\n };\n\n try {\n dep.load(controller);\n } finally {\n loadCallDone = true;\n }\n })();\n }\n\n if (paused) {\n this.pause_();\n }\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.pause_ = function() {\n this.paused_ = true;\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.resume_ = function() {\n if (this.paused_) {\n this.paused_ = false;\n this.loadDeps_();\n }\n };\n\n\n /**\n * Marks the given dependency as loading (load has been called but it has not\n * yet marked itself as finished). Useful for dependencies that want to know\n * what else is loading. Example: goog.modules cannot eval if there are\n * loading dependencies.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loading_ = function(dep) {\n this.loadingDeps_.push(dep);\n };\n\n\n /**\n * Marks the given dependency as having finished loading and being available\n * for require.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loaded_ = function(dep) {\n for (var i = 0; i < this.loadingDeps_.length; i++) {\n if (this.loadingDeps_[i] == dep) {\n this.loadingDeps_.splice(i, 1);\n break;\n }\n }\n\n for (var i = 0; i < this.deferredQueue_.length; i++) {\n if (this.deferredQueue_[i] == dep.path) {\n this.deferredQueue_.splice(i, 1);\n break;\n }\n }\n\n if (this.loadingDeps_.length == this.deferredQueue_.length &&\n !this.depsToLoad_.length) {\n // Something has asked to load these, but they may not be directly\n // required again later, so load them now that we know we're done loading\n // everything else. e.g. a goog module entry point.\n while (this.deferredQueue_.length) {\n this.requested(this.deferredQueue_.shift(), true);\n }\n }\n\n dep.loaded();\n };\n\n\n /**\n * @param {!Array<string>} pathsOrIds\n * @return {boolean}\n * @private\n */\n goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\n for (var i = 0; i < pathsOrIds.length; i++) {\n var path = this.getPathFromDeps_(pathsOrIds[i]);\n if (!path ||\n (!(path in this.deferredCallbacks_) &&\n !goog.isProvided_(pathsOrIds[i]))) {\n return false;\n }\n }\n\n return true;\n };\n\n\n /**\n * @param {string} absPathOrId\n * @return {?string}\n * @private\n */\n goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\n if (absPathOrId in this.idToPath_) {\n return this.idToPath_[absPathOrId];\n } else if (absPathOrId in this.dependencies_) {\n return absPathOrId;\n } else {\n return null;\n }\n };\n\n\n /**\n * @param {!goog.Dependency} dependency\n * @param {!Function} callback\n * @private\n */\n goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\n this.deferredCallbacks_[dependency.path] = callback;\n this.deferredQueue_.push(dependency.path);\n };\n\n\n /**\n * Interface for goog.Dependency implementations to have some control over\n * loading of dependencies.\n *\n * @record\n */\n goog.LoadController = function() {};\n\n\n /**\n * Tells the controller to halt loading of more dependencies.\n */\n goog.LoadController.prototype.pause = function() {};\n\n\n /**\n * Tells the controller to resume loading of more dependencies if paused.\n */\n goog.LoadController.prototype.resume = function() {};\n\n\n /**\n * Tells the controller that this dependency has finished loading.\n *\n * This causes this to be removed from pending() and any load callbacks to\n * fire.\n */\n goog.LoadController.prototype.loaded = function() {};\n\n\n /**\n * List of dependencies on which load has been called but which have not\n * called loaded on their controller. This includes the current dependency.\n *\n * @return {!Array<!goog.Dependency>}\n */\n goog.LoadController.prototype.pending = function() {};\n\n\n /**\n * Registers an object as an ES6 module's exports so that goog.modules may\n * require it by path.\n *\n * @param {string} path Full path of the module.\n * @param {?} exports\n * @param {string=} opt_closureNamespace Closure namespace to associate with\n * this module.\n */\n goog.LoadController.prototype.registerEs6ModuleExports = function(\n path, exports, opt_closureNamespace) {};\n\n\n /**\n * Sets the current module state.\n *\n * @param {goog.ModuleType} type Type of module.\n */\n goog.LoadController.prototype.setModuleState = function(type) {};\n\n\n /**\n * Clears the current module state.\n */\n goog.LoadController.prototype.clearModuleState = function() {};\n\n\n /**\n * Registers a callback to call once the dependency is actually requested\n * via goog.require + all of the immediate dependencies have been loaded or\n * all other files have been loaded. Allows for lazy loading until\n * require'd without pausing dependency loading, which is needed on old IE.\n *\n * @param {!Function} callback\n */\n goog.LoadController.prototype.defer = function(callback) {};\n\n\n /**\n * @return {boolean}\n */\n goog.LoadController.prototype.areDepsLoaded = function() {};\n\n\n /**\n * Basic super class for all dependencies Closure Library can load.\n *\n * This default implementation is designed to load untranspiled, non-module\n * scripts in a web broswer.\n *\n * For transpiled non-goog.module files {@see goog.TranspiledDependency}.\n * For goog.modules see {@see goog.GoogModuleDependency}.\n * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n */\n goog.Dependency = function(\n path, relativePath, provides, requires, loadFlags) {\n /** @const */\n this.path = path;\n /** @const */\n this.relativePath = relativePath;\n /** @const */\n this.provides = provides;\n /** @const */\n this.requires = requires;\n /** @const */\n this.loadFlags = loadFlags;\n /** @private {boolean} */\n this.loaded_ = false;\n /** @private {!Array<function()>} */\n this.loadCallbacks_ = [];\n };\n\n\n /**\n * @return {string} The pathname part of this dependency's path if it is a\n * URI.\n */\n goog.Dependency.prototype.getPathName = function() {\n var pathName = this.path;\n var protocolIndex = pathName.indexOf('://');\n if (protocolIndex >= 0) {\n pathName = pathName.substring(protocolIndex + 3);\n var slashIndex = pathName.indexOf('/');\n if (slashIndex >= 0) {\n pathName = pathName.substring(slashIndex + 1);\n }\n }\n return pathName;\n };\n\n\n /**\n * @param {function()} callback Callback to fire as soon as this has loaded.\n * @final\n */\n goog.Dependency.prototype.onLoad = function(callback) {\n if (this.loaded_) {\n callback();\n } else {\n this.loadCallbacks_.push(callback);\n }\n };\n\n\n /**\n * Marks this dependency as loaded and fires any callbacks registered with\n * onLoad.\n * @final\n */\n goog.Dependency.prototype.loaded = function() {\n this.loaded_ = true;\n var callbacks = this.loadCallbacks_;\n this.loadCallbacks_ = [];\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i]();\n }\n };\n\n\n /**\n * Whether or not document.written / appended script tags should be deferred.\n *\n * @private {boolean}\n */\n goog.Dependency.defer_ = false;\n\n\n /**\n * Map of script ready / state change callbacks. Old IE cannot handle putting\n * these properties on goog.global.\n *\n * @private @const {!Object<string, function(?):undefined>}\n */\n goog.Dependency.callbackMap_ = {};\n\n\n /**\n * @param {function(...?):?} callback\n * @return {string}\n * @private\n */\n goog.Dependency.registerCallback_ = function(callback) {\n var key = Math.random().toString(32);\n goog.Dependency.callbackMap_[key] = callback;\n return key;\n };\n\n\n /**\n * @param {string} key\n * @private\n */\n goog.Dependency.unregisterCallback_ = function(key) {\n delete goog.Dependency.callbackMap_[key];\n };\n\n\n /**\n * @param {string} key\n * @param {...?} var_args\n * @private\n * @suppress {unusedPrivateMembers}\n */\n goog.Dependency.callback_ = function(key, var_args) {\n if (key in goog.Dependency.callbackMap_) {\n var callback = goog.Dependency.callbackMap_[key];\n var args = [];\n for (var i = 1; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n callback.apply(undefined, args);\n } else {\n var errorMessage = 'Callback key ' + key +\n ' does not exist (was base.js loaded more than once?).';\n throw Error(errorMessage);\n }\n };\n\n\n /**\n * Starts loading this dependency. This dependency can pause loading if it\n * needs to and resume it later via the controller interface.\n *\n * When this is loaded it should call controller.loaded(). Note that this will\n * end up calling the loaded method of this dependency; there is no need to\n * call it explicitly.\n *\n * @param {!goog.LoadController} controller\n */\n goog.Dependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n if (this.relativePath == 'deps.js') {\n // Some old code is relying on base.js auto loading deps.js failing with\n // no error before later setting CLOSURE_IMPORT_SCRIPT.\n // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\n // CLOSURE_NO_DEPS set to true.\n goog.logToConsole_(\n 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\n 'or setting CLOSURE_NO_DEPS to true.');\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n // If the user tries to require a new symbol after document load,\n // something has gone terribly wrong. Doing a document.write would\n // wipe out the page. This does not apply to the CSP-compliant method\n // of writing script tags.\n if (doc.readyState == 'complete' &&\n !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\n // Certain test frameworks load base.js multiple times, which tries\n // to write deps.js each time. If that happens, just fail silently.\n // These frameworks wipe the page between each load of base.js, so this\n // is OK.\n var isDeps = /\\bdeps.js$/.test(this.path);\n if (isDeps) {\n controller.loaded();\n return;\n } else {\n throw Error('Cannot write \"' + this.path + '\" after document load');\n }\n }\n\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\n goog.isDocumentLoading_()) {\n var key = goog.Dependency.registerCallback_(function(script) {\n if (!goog.DebugLoader_.IS_OLD_IE_ || script.readyState == 'complete') {\n goog.Dependency.unregisterCallback_(key);\n controller.loaded();\n }\n });\n var nonceAttr = !goog.DebugLoader_.IS_OLD_IE_ && goog.getScriptNonce() ?\n ' nonce=\"' + goog.getScriptNonce() + '\"' :\n '';\n var event =\n goog.DebugLoader_.IS_OLD_IE_ ? 'onreadystatechange' : 'onload';\n var defer = goog.Dependency.defer_ ? 'defer' : '';\n var script = '<script src=\"' + this.path + '\" ' + event +\n '=\"goog.Dependency.callback_(\\'' + key +\n '\\', this)\" type=\"text/javascript\" ' + defer + nonceAttr + '><' +\n '/script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = goog.Dependency.defer_;\n scriptEl.async = false;\n scriptEl.type = 'text/javascript';\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce();\n if (nonce) {\n scriptEl.setAttribute('nonce', nonce);\n }\n\n if (goog.DebugLoader_.IS_OLD_IE_) {\n // Execution order is not guaranteed on old IE, halt loading and write\n // these scripts one at a time, after each loads.\n controller.pause();\n scriptEl.onreadystatechange = function() {\n if (scriptEl.readyState == 'loaded' ||\n scriptEl.readyState == 'complete') {\n controller.loaded();\n controller.resume();\n }\n };\n } else {\n scriptEl.onload = function() {\n scriptEl.onload = null;\n controller.loaded();\n };\n }\n\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\n this.path;\n doc.head.appendChild(scriptEl);\n }\n };\n\n\n /**\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides Should be an empty array.\n * TODO(johnplaisted) add support for adding closure namespaces to ES6\n * modules for interop purposes.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.Dependency}\n */\n goog.Es6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.Es6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\n\n\n /** @override */\n goog.Es6ModuleDependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n controller.pause();\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var dep = this;\n\n // TODO(johnplaisted): Does document.writing really speed up anything? Any\n // difference between this and just waiting for interactive mode and then\n // appending?\n function write(src, contents) {\n if (contents) {\n var script = '<script type=\"module\" crossorigin>' + contents + '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var script = '<script type=\"module\" crossorigin src=\"' + src + '\"></' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n }\n\n function append(src, contents) {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = true;\n scriptEl.async = false;\n scriptEl.type = 'module';\n scriptEl.setAttribute('crossorigin', true);\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce();\n if (nonce) {\n scriptEl.setAttribute('nonce', nonce);\n }\n\n if (contents) {\n scriptEl.textContent = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\n contents;\n } else {\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\n src;\n }\n\n doc.head.appendChild(scriptEl);\n }\n\n var create;\n\n if (goog.isDocumentLoading_()) {\n create = write;\n // We can ONLY call document.write if we are guaranteed that any\n // non-module script tags document.written after this are deferred.\n // Small optimization, in theory document.writing is faster.\n goog.Dependency.defer_ = true;\n } else {\n create = append;\n }\n\n // Write 4 separate tags here:\n // 1) Sets the module state at the correct time (just before execution).\n // 2) A src node for this, which just hopefully lets the browser load it a\n // little early (no need to parse #3).\n // 3) Import the module and register it.\n // 4) Clear the module state at the correct time. Guaranteed to run even\n // if there is an error in the module (#3 will not run if there is an\n // error in the module).\n var beforeKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(beforeKey);\n controller.setModuleState(goog.ModuleType.ES6);\n });\n create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\n\n // TODO(johnplaisted): Does this really speed up anything?\n create(this.path, undefined);\n\n var registerKey = goog.Dependency.registerCallback_(function(exports) {\n goog.Dependency.unregisterCallback_(registerKey);\n controller.registerEs6ModuleExports(\n dep.path, exports, goog.moduleLoaderState_.moduleName);\n });\n create(\n undefined,\n 'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\n registerKey + '\", m)');\n\n var afterKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(afterKey);\n controller.clearModuleState();\n controller.loaded();\n });\n create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\n };\n\n\n /**\n * Superclass of any dependency that needs to be loaded into memory,\n * transformed, and then eval'd (goog.modules and transpiled files).\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor @abstract\n * @extends {goog.Dependency}\n */\n goog.TransformedDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.TransformedDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private {?string} */\n this.contents_ = null;\n\n /**\n * Whether to lazily make the synchronous XHR (when goog.require'd) or make\n * the synchronous XHR when initially loading. On FireFox 61 there is a bug\n * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\n * it does then no other ES6 modules will load after).\n *\n * tl;dr we lazy load due to bugs on older browsers and eager load due to\n * bugs on newer ones.\n *\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\n *\n * @private @const {boolean}\n */\n this.lazyFetch_ = !goog.inHtmlDocument_() ||\n !('noModule' in goog.global.document.createElement('script'));\n };\n goog.inherits(goog.TransformedDependency, goog.Dependency);\n\n\n /** @override */\n goog.TransformedDependency.prototype.load = function(controller) {\n var dep = this;\n\n function fetch() {\n dep.contents_ = goog.loadFileSync_(dep.path);\n\n if (dep.contents_) {\n dep.contents_ = dep.transform(dep.contents_);\n if (dep.contents_) {\n dep.contents_ += '\\n//# sourceURL=' + dep.path;\n }\n }\n }\n\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n fetch();\n if (this.contents_ &&\n goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\n this.contents_ = null;\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n\n var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\n\n if (!this.lazyFetch_) {\n fetch();\n }\n\n function load() {\n if (dep.lazyFetch_) {\n fetch();\n }\n\n if (!dep.contents_) {\n // loadFileSync_ or transform are responsible. Assume they logged an\n // error.\n return;\n }\n\n if (isEs6) {\n controller.setModuleState(goog.ModuleType.ES6);\n }\n\n var namespace;\n\n try {\n var contents = dep.contents_;\n dep.contents_ = null;\n goog.globalEval(contents);\n if (isEs6) {\n namespace = goog.moduleLoaderState_.moduleName;\n }\n } finally {\n if (isEs6) {\n controller.clearModuleState();\n }\n }\n\n if (isEs6) {\n // Due to circular dependencies this may not be available for require\n // right now.\n goog.global['$jscomp']['require']['ensure'](\n [dep.getPathName()], function() {\n controller.registerEs6ModuleExports(\n dep.path,\n goog.global['$jscomp']['require'](dep.getPathName()),\n namespace);\n });\n }\n\n controller.loaded();\n }\n\n // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\n // events. If we fetched now and then document.write'd the contents the\n // document.write would be an eval and would execute too soon! Instead write\n // a script tag to fetch and eval synchronously at the correct time.\n function fetchInOwnScriptThenLoad() {\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var key = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(key);\n load();\n });\n\n var script = '<script type=\"text/javascript\">' +\n goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\n '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n\n // If one thing is pending it is this.\n var anythingElsePending = controller.pending().length > 1;\n\n // If anything else is loading we need to lazy load due to bugs in old IE.\n // Specifically script tags with src and script tags with contents could\n // execute out of order if document.write is used, so we cannot use\n // document.write. Do not pause here; it breaks old IE as well.\n var useOldIeWorkAround =\n anythingElsePending && goog.DebugLoader_.IS_OLD_IE_;\n\n // Additionally if we are meant to defer scripts but the page is still\n // loading (e.g. an ES6 module is loading) then also defer. Or if we are\n // meant to defer and anything else is pending then defer (those may be\n // scripts that did not need transformation and are just script tags with\n // defer set to true, and we need to evaluate after that deferred script).\n var needsAsyncLoading = goog.Dependency.defer_ &&\n (anythingElsePending || goog.isDocumentLoading_());\n\n if (useOldIeWorkAround || needsAsyncLoading) {\n // Note that we only defer when we have to rather than 100% of the time.\n // Always defering would work, but then in theory the order of\n // goog.require calls would then matter. We want to enforce that most of\n // the time the order of the require calls does not matter.\n controller.defer(function() {\n load();\n });\n return;\n }\n // TODO(johnplaisted): Externs are missing onreadystatechange for\n // HTMLDocument.\n /** @type {?} */\n var doc = goog.global.document;\n\n var isInternetExplorer =\n goog.inHtmlDocument_() && 'ActiveXObject' in goog.global;\n\n // Don't delay in any version of IE. There's bug around this that will\n // cause out of order script execution. This means that on older IE ES6\n // modules will load too early (while the document is still loading + the\n // dom is not available). The other option is to load too late (when the\n // document is complete and the onload even will never fire). This seems\n // to be the lesser of two evils as scripts already act like the former.\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\n !isInternetExplorer) {\n goog.Dependency.defer_ = true;\n // Transpiled ES6 modules still need to load like regular ES6 modules,\n // aka only after the document is interactive.\n controller.pause();\n var oldCallback = doc.onreadystatechange;\n doc.onreadystatechange = function() {\n if (doc.readyState == 'interactive') {\n doc.onreadystatechange = oldCallback;\n load();\n controller.resume();\n }\n if (goog.isFunction(oldCallback)) {\n oldCallback.apply(undefined, arguments);\n }\n };\n } else {\n // Always eval on old IE.\n if (goog.DebugLoader_.IS_OLD_IE_ || !goog.inHtmlDocument_() ||\n !goog.isDocumentLoading_()) {\n load();\n } else {\n fetchInOwnScriptThenLoad();\n }\n }\n };\n\n\n /**\n * @param {string} contents\n * @return {string}\n * @abstract\n */\n goog.TransformedDependency.prototype.transform = function(contents) {};\n\n\n /**\n * Any non-goog.module dependency which needs to be transpiled before eval.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.TranspiledDependency = function(\n path, relativePath, provides, requires, loadFlags, transpiler) {\n goog.TranspiledDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @protected @const*/\n this.transpiler = transpiler;\n };\n goog.inherits(goog.TranspiledDependency, goog.TransformedDependency);\n\n\n /** @override */\n goog.TranspiledDependency.prototype.transform = function(contents) {\n // Transpile with the pathname so that ES6 modules are domain agnostic.\n return this.transpiler.transpile(contents, this.getPathName());\n };\n\n\n /**\n * An ES6 module dependency that was transpiled to a jscomp module outside\n * of the debug loader, e.g. server side.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.PreTranspiledEs6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.PreTranspiledEs6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(\n goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\n\n\n /** @override */\n goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\n contents) {\n return contents;\n };\n\n\n /**\n * A goog.module, transpiled or not. Will always perform some minimal\n * transformation even when not transpiled to wrap in a goog.loadModule\n * statement.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @param {boolean} needsTranspile\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.GoogModuleDependency = function(\n path, relativePath, provides, requires, loadFlags, needsTranspile,\n transpiler) {\n goog.GoogModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private @const */\n this.needsTranspile_ = needsTranspile;\n /** @private @const */\n this.transpiler_ = transpiler;\n };\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\n\n\n /** @override */\n goog.GoogModuleDependency.prototype.transform = function(contents) {\n if (this.needsTranspile_) {\n contents = this.transpiler_.transpile(contents, this.getPathName());\n }\n\n if (!goog.LOAD_MODULE_USING_EVAL || goog.global.JSON === undefined) {\n return '' +\n 'goog.loadModule(function(exports) {' +\n '\"use strict\";' + contents +\n '\\n' + // terminate any trailing single line comment.\n ';return exports' +\n '});' +\n '\\n//# sourceURL=' + this.path + '\\n';\n } else {\n return '' +\n 'goog.loadModule(' +\n goog.global.JSON.stringify(\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\n ');';\n }\n };\n\n\n /**\n * Whether the browser is IE9 or earlier, which needs special handling\n * for deferred modules.\n * @const @private {boolean}\n */\n goog.DebugLoader_.IS_OLD_IE_ = !!(\n !goog.global.atob && goog.global.document && goog.global.document['all']);\n\n\n /**\n * @param {string} relPath\n * @param {!Array<string>|undefined} provides\n * @param {!Array<string>} requires\n * @param {boolean|!Object<string>=} opt_loadFlags\n * @see goog.addDependency\n */\n goog.DebugLoader_.prototype.addDependency = function(\n relPath, provides, requires, opt_loadFlags) {\n provides = provides || [];\n relPath = relPath.replace(/\\\\/g, '/');\n var path = goog.normalizePath_(goog.basePath + relPath);\n if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\n opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\n }\n var dep = this.factory_.createDependency(\n path, relPath, provides, requires, opt_loadFlags,\n goog.transpiler_.needsTranspile(\n opt_loadFlags['lang'] || 'es3', opt_loadFlags['module']));\n this.dependencies_[path] = dep;\n for (var i = 0; i < provides.length; i++) {\n this.idToPath_[provides[i]] = path;\n }\n this.idToPath_[relPath] = path;\n };\n\n\n /**\n * Creates goog.Dependency instances for the debug loader to load.\n *\n * Should be overridden to have the debug loader use custom subclasses of\n * goog.Dependency.\n *\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n */\n goog.DependencyFactory = function(transpiler) {\n /** @protected @const */\n this.transpiler = transpiler;\n };\n\n\n /**\n * @param {string} path Absolute path of the file.\n * @param {string} relativePath Path relative to closure’s base.js.\n * @param {!Array<string>} provides Array of provided goog.provide/module ids.\n * @param {!Array<string>} requires Array of required goog.provide/module /\n * relative ES6 module paths.\n * @param {!Object<string, string>} loadFlags\n * @param {boolean} needsTranspile True if the file needs to be transpiled\n * per the goog.Transpiler.\n * @return {!goog.Dependency}\n */\n goog.DependencyFactory.prototype.createDependency = function(\n path, relativePath, provides, requires, loadFlags, needsTranspile) {\n\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\n return new goog.GoogModuleDependency(\n path, relativePath, provides, requires, loadFlags, needsTranspile,\n this.transpiler);\n } else if (needsTranspile) {\n return new goog.TranspiledDependency(\n path, relativePath, provides, requires, loadFlags, this.transpiler);\n } else {\n if (loadFlags['module'] == goog.ModuleType.ES6) {\n if (goog.TRANSPILE == 'never' && goog.ASSUME_ES_MODULES_TRANSPILED) {\n return new goog.PreTranspiledEs6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n return new goog.Es6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n }\n } else {\n return new goog.Dependency(\n path, relativePath, provides, requires, loadFlags);\n }\n }\n };\n\n\n /** @private @const */\n goog.debugLoader_ = new goog.DebugLoader_();\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.loadClosureDeps = function() {\n goog.debugLoader_.loadClosureDeps();\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * Note: if you wish to call this function and provide your own implemnetation\n * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\n * file and all of its goog.addDependency calls will use the default factory.\n * You can call goog.loadClosureDeps to load the Closure dependency file\n * later, after your factory is injected.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.setDependencyFactory = function(factory) {\n goog.debugLoader_.setDependencyFactory(factory);\n };\n\n\n if (!goog.global.CLOSURE_NO_DEPS) {\n goog.debugLoader_.loadClosureDeps();\n }\n\n\n /**\n * Bootstraps the given namespaces and calls the callback once they are\n * available either via goog.require. This is a replacement for using\n * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\n * in an HTML file would guarantee that the require'd namespace was available\n * in the next immediate script tag. With ES6 modules this no longer a\n * guarantee.\n *\n * @param {!Array<string>} namespaces\n * @param {function(): ?} callback Function to call once all the namespaces\n * have loaded. Always called asynchronously.\n */\n goog.bootstrap = function(namespaces, callback) {\n goog.debugLoader_.bootstrap(namespaces, callback);\n };\n}\n\n\n/**\n * @define {string} Trusted Types policy name. If non-empty then Closure will\n * use Trusted Types.\n */\ngoog.TRUSTED_TYPES_POLICY_NAME =\n goog.define('goog.TRUSTED_TYPES_POLICY_NAME', '');\n\n\n/**\n * Returns the parameter.\n * @param {string} s\n * @return {string}\n * @private\n */\ngoog.identity_ = function(s) {\n return s;\n};\n\n\n/**\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\n * The policy just blesses any string as a Trusted Type. It is not visibility\n * restricted because anyone can also call TrustedTypes.createPolicy directly.\n * However, the allowed names should be restricted by a HTTP header and the\n * reference to the created policy should be visibility restricted.\n * @param {string} name\n * @return {?TrustedTypePolicy}\n */\ngoog.createTrustedTypesPolicy = function(name) {\n var policy = null;\n // TODO(koto): Remove window.TrustedTypes variant when the newer API ships.\n var policyFactory = goog.global.trustedTypes || goog.global.TrustedTypes;\n if (!policyFactory || !policyFactory.createPolicy) {\n return policy;\n }\n // TrustedTypes.createPolicy throws if called with a name that is already\n // registered, even in report-only mode. Until the API changes, catch the\n // error not to break the applications functionally. In such case, the code\n // will fall back to using regular Safe Types.\n // TODO(koto): Remove catching once createPolicy API stops throwing.\n try {\n policy = policyFactory.createPolicy(name, {\n createHTML: goog.identity_,\n createScript: goog.identity_,\n createScriptURL: goog.identity_,\n createURL: goog.identity_\n });\n } catch (e) {\n goog.logToConsole_(e.message);\n }\n return policy;\n};\n\n\n/** @private @const {?TrustedTypePolicy} */\ngoog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\n null;\n",null,null,null,null,null,null,"/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 developer-visible errors for Firebase Auth APIs.\n */\n\n\ngoog.provide('fireauth.AuthError');\ngoog.provide('fireauth.authenum');\ngoog.provide('fireauth.authenum.Error');\n\n\n\n/**\n * Error that can be returned to the developer.\n * @param {!fireauth.authenum.Error} code The short error code.\n * @param {?string=} message The human-readable message.\n * @param {?Object=} serverResponse The raw server response.\n * @constructor\n * @extends {Error}\n */\nfireauth.AuthError = function(code, message, serverResponse) {\n this['code'] = fireauth.AuthError.ERROR_CODE_PREFIX + code;\n this.message = message || fireauth.AuthError.MESSAGES_[code] || '';\n this.serverResponse = serverResponse || null;\n};\ngoog.inherits(fireauth.AuthError, Error);\n\n\n/**\n * @return {!Object} The plain object form of the error.\n */\nfireauth.AuthError.prototype.toPlainObject = function() {\n var obj = {\n 'code': this['code'],\n 'message': this.message\n };\n if (this.serverResponse) {\n obj['serverResponse'] = this.serverResponse;\n }\n return obj;\n};\n\n\n/**\n * @return {!Object} The plain object form of the error. This is used by\n * JSON.toStringify() to return the stringified representation of the error;\n * @override\n */\nfireauth.AuthError.prototype.toJSON = function() {\n // Return the plain object representation in case JSON.stringify is called on\n // an auth error instance.\n return this.toPlainObject();\n};\n\n\n/**\n * @param {?Object|undefined} response The object response to convert to a\n * fireauth.AuthError.\n * @return {?fireauth.AuthError} The error representation of the response.\n */\nfireauth.AuthError.fromPlainObject = function(response) {\n var fullCode = response && response['code'];\n if (fullCode) {\n // Remove prefix from name.\n var code = fullCode.substring(\n fireauth.AuthError.ERROR_CODE_PREFIX.length);\n return new fireauth.AuthError(\n /** @type {!fireauth.authenum.Error} */ (code),\n response['message'],\n response['serverResponse']);\n }\n return null;\n};\n\n\n/**\n * Takes in an error and translates a specific error code to another one if\n * found in the current error.\n * @param {*} error The error thrown.\n * @param {!fireauth.authenum.Error} fromCode The error code to translate from.\n * @param {!fireauth.authenum.Error} toCode The error code to translate to.\n * @return {*} The mapped error message.\n */\nfireauth.AuthError.translateError = function(error, fromCode, toCode) {\n if (error &&\n error['code'] &&\n error['code'] == fireauth.AuthError.ERROR_CODE_PREFIX + fromCode) {\n // Translate the error to the new one.\n return new fireauth.AuthError(toCode);\n }\n // Return the same error if the fromCode is not found.\n return error;\n};\n\n\n/**\n * The error prefix for fireauth.Auth errors.\n * @protected {string}\n */\nfireauth.AuthError.ERROR_CODE_PREFIX = 'auth/';\n\n\n/**\n * Developer facing Firebase Auth error codes.\n * @enum {string}\n */\nfireauth.authenum.Error = {\n ADMIN_ONLY_OPERATION: 'admin-restricted-operation',\n ARGUMENT_ERROR: 'argument-error',\n APP_NOT_AUTHORIZED: 'app-not-authorized',\n APP_NOT_INSTALLED: 'app-not-installed',\n CAPTCHA_CHECK_FAILED: 'captcha-check-failed',\n CODE_EXPIRED: 'code-expired',\n CORDOVA_NOT_READY: 'cordova-not-ready',\n CORS_UNSUPPORTED: 'cors-unsupported',\n CREDENTIAL_ALREADY_IN_USE: 'credential-already-in-use',\n CREDENTIAL_MISMATCH: 'custom-token-mismatch',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'requires-recent-login',\n DYNAMIC_LINK_NOT_ACTIVATED: 'dynamic-link-not-activated',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'email-change-needs-verification',\n EMAIL_EXISTS: 'email-already-in-use',\n EXPIRED_OOB_CODE: 'expired-action-code',\n EXPIRED_POPUP_REQUEST: 'cancelled-popup-request',\n INTERNAL_ERROR: 'internal-error',\n INVALID_API_KEY: 'invalid-api-key',\n INVALID_APP_CREDENTIAL: 'invalid-app-credential',\n INVALID_APP_ID: 'invalid-app-id',\n INVALID_AUTH: 'invalid-user-token',\n INVALID_AUTH_EVENT: 'invalid-auth-event',\n INVALID_CERT_HASH: 'invalid-cert-hash',\n INVALID_CODE: 'invalid-verification-code',\n INVALID_CONTINUE_URI: 'invalid-continue-uri',\n INVALID_CORDOVA_CONFIGURATION: 'invalid-cordova-configuration',\n INVALID_CUSTOM_TOKEN: 'invalid-custom-token',\n INVALID_DYNAMIC_LINK_DOMAIN: 'invalid-dynamic-link-domain',\n INVALID_EMAIL: 'invalid-email',\n INVALID_IDP_RESPONSE: 'invalid-credential',\n INVALID_MESSAGE_PAYLOAD: 'invalid-message-payload',\n INVALID_MFA_PENDING_CREDENTIAL: 'invalid-multi-factor-session',\n INVALID_OAUTH_CLIENT_ID: 'invalid-oauth-client-id',\n INVALID_OAUTH_PROVIDER: 'invalid-oauth-provider',\n INVALID_OOB_CODE: 'invalid-action-code',\n INVALID_ORIGIN: 'unauthorized-domain',\n INVALID_PASSWORD: 'wrong-password',\n INVALID_PERSISTENCE: 'invalid-persistence-type',\n INVALID_PHONE_NUMBER: 'invalid-phone-number',\n INVALID_PROVIDER_ID: 'invalid-provider-id',\n INVALID_RECIPIENT_EMAIL: 'invalid-recipient-email',\n INVALID_SENDER: 'invalid-sender',\n INVALID_SESSION_INFO: 'invalid-verification-id',\n INVALID_TENANT_ID: 'invalid-tenant-id',\n MFA_ENROLLMENT_NOT_FOUND: 'multi-factor-info-not-found',\n MFA_REQUIRED: 'multi-factor-auth-required',\n MISSING_ANDROID_PACKAGE_NAME: 'missing-android-pkg-name',\n MISSING_APP_CREDENTIAL: 'missing-app-credential',\n MISSING_AUTH_DOMAIN: 'auth-domain-config-required',\n MISSING_CODE: 'missing-verification-code',\n MISSING_CONTINUE_URI: 'missing-continue-uri',\n MISSING_IFRAME_START: 'missing-iframe-start',\n MISSING_IOS_BUNDLE_ID: 'missing-ios-bundle-id',\n MISSING_MFA_ENROLLMENT_ID: 'missing-multi-factor-info',\n MISSING_MFA_PENDING_CREDENTIAL: 'missing-multi-factor-session',\n MISSING_OR_INVALID_NONCE: 'missing-or-invalid-nonce',\n MISSING_PHONE_NUMBER: 'missing-phone-number',\n MISSING_SESSION_INFO: 'missing-verification-id',\n MODULE_DESTROYED: 'app-deleted',\n NEED_CONFIRMATION: 'account-exists-with-different-credential',\n NETWORK_REQUEST_FAILED: 'network-request-failed',\n NULL_USER: 'null-user',\n NO_AUTH_EVENT: 'no-auth-event',\n NO_SUCH_PROVIDER: 'no-such-provider',\n OPERATION_NOT_ALLOWED: 'operation-not-allowed',\n OPERATION_NOT_SUPPORTED: 'operation-not-supported-in-this-environment',\n POPUP_BLOCKED: 'popup-blocked',\n POPUP_CLOSED_BY_USER: 'popup-closed-by-user',\n PROVIDER_ALREADY_LINKED: 'provider-already-linked',\n QUOTA_EXCEEDED: 'quota-exceeded',\n REDIRECT_CANCELLED_BY_USER: 'redirect-cancelled-by-user',\n REDIRECT_OPERATION_PENDING: 'redirect-operation-pending',\n REJECTED_CREDENTIAL: 'rejected-credential',\n SECOND_FACTOR_EXISTS: 'second-factor-already-in-use',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'maximum-second-factor-count-exceeded',\n TENANT_ID_MISMATCH: 'tenant-id-mismatch',\n TIMEOUT: 'timeout',\n TOKEN_EXPIRED: 'user-token-expired',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'too-many-requests',\n UNAUTHORIZED_DOMAIN: 'unauthorized-continue-uri',\n UNSUPPORTED_FIRST_FACTOR: 'unsupported-first-factor',\n UNSUPPORTED_PERSISTENCE: 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'unsupported-tenant-operation',\n UNVERIFIED_EMAIL: 'unverified-email',\n USER_CANCELLED: 'user-cancelled',\n USER_DELETED: 'user-not-found',\n USER_DISABLED: 'user-disabled',\n USER_MISMATCH: 'user-mismatch',\n USER_SIGNED_OUT: 'user-signed-out',\n WEAK_PASSWORD: 'weak-password',\n WEB_STORAGE_UNSUPPORTED: 'web-storage-unsupported'\n};\n\n\n/**\n * Map from developer error codes to human-readable error messages.\n * @private {!Object<string, string>}\n */\nfireauth.AuthError.MESSAGES_ = {};\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.ADMIN_ONLY_OPERATION] =\n 'This operation is restricted to administrators only.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.ARGUMENT_ERROR] = '';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.APP_NOT_AUTHORIZED] =\n 'This app, identified by the domain where it\\'s hosted, is not ' +\n 'authorized to use Firebase Authentication with the provided API key. ' +\n 'Review your key configuration in the Google API console.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.APP_NOT_INSTALLED] =\n 'The requested mobile application corresponding to the identifier (' +\n 'Android package name or iOS bundle ID) provided is not installed on ' +\n 'this device.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.CAPTCHA_CHECK_FAILED] =\n 'The reCAPTCHA response token provided is either invalid, expired, ' +\n 'already used or the domain associated with it does not match the list ' +\n 'of whitelisted domains.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.CODE_EXPIRED] =\n 'The SMS code has expired. Please re-send the verification code to try ' +\n 'again.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.CORDOVA_NOT_READY] =\n 'Cordova framework is not ready.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.CORS_UNSUPPORTED] =\n 'This browser is not supported.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.CREDENTIAL_ALREADY_IN_USE] =\n 'This credential is already associated with a different user account.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.CREDENTIAL_MISMATCH] =\n 'The custom token corresponds to a different audience.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.CREDENTIAL_TOO_OLD_LOGIN_AGAIN] =\n 'This operation is sensitive and requires recent authentication. Log in ' +\n 'again before retrying this request.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.DYNAMIC_LINK_NOT_ACTIVATED] = 'Please activate ' +\n 'Dynamic Links in the Firebase Console and agree to the terms and ' +\n 'conditions.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.EMAIL_CHANGE_NEEDS_VERIFICATION] =\n 'Multi-factor users must always have a verified email.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.EMAIL_EXISTS] =\n 'The email address is already in use by another account.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.EXPIRED_OOB_CODE] =\n 'The action code has expired. ';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.EXPIRED_POPUP_REQUEST] =\n 'This operation has been cancelled due to another conflicting popup ' +\n 'being opened.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INTERNAL_ERROR] =\n 'An internal error has occurred.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_APP_CREDENTIAL] =\n 'The phone verification request contains an invalid application verifier.' +\n ' The reCAPTCHA token response is either invalid or expired.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_APP_ID] =\n 'The mobile app identifier is not registed for the current project.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_AUTH] =\n 'This user\\'s credential isn\\'t valid for this project. This can happen ' +\n 'if the user\\'s token has been tampered with, or if the user isn\\'t for ' +\n 'the project associated with this API key.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_AUTH_EVENT] =\n 'An internal error has occurred.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_CODE] =\n 'The SMS verification code used to create the phone auth credential is ' +\n 'invalid. Please resend the verification code sms and be sure use the ' +\n 'verification code provided by the user.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_CONTINUE_URI] =\n 'The continue URL provided in the request is invalid.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.INVALID_CORDOVA_CONFIGURATION] = 'The following' +\n ' Cordova plugins must be installed to enable OAuth sign-in: ' +\n 'cordova-plugin-buildinfo, cordova-universal-links-plugin, ' +\n 'cordova-plugin-browsertab, cordova-plugin-inappbrowser and ' +\n 'cordova-plugin-customurlscheme.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_CUSTOM_TOKEN] =\n 'The custom token format is incorrect. Please check the documentation.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.INVALID_DYNAMIC_LINK_DOMAIN] = 'The provided ' +\n 'dynamic link domain is not configured or authorized for the current ' +\n 'project.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_EMAIL] =\n 'The email address is badly formatted.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_API_KEY] =\n 'Your API key is invalid, please check you have copied it correctly.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_CERT_HASH] =\n 'The SHA-1 certificate hash provided is invalid.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_IDP_RESPONSE] =\n 'The supplied auth credential is malformed or has expired.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_MESSAGE_PAYLOAD] =\n 'The email template corresponding to this action contains invalid charac' +\n 'ters in its message. Please fix by going to the Auth email templates se' +\n 'ction in the Firebase Console.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.INVALID_MFA_PENDING_CREDENTIAL] =\n 'The request does not contain a valid proof of first factor successful ' +\n 'sign-in.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_OAUTH_PROVIDER] =\n 'EmailAuthProvider is not supported for this operation. This operation ' +\n 'only supports OAuth providers.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_OAUTH_CLIENT_ID] =\n 'The OAuth client ID provided is either invalid or does not match the ' +\n 'specified API key.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_ORIGIN] =\n 'This domain is not authorized for OAuth operations for your Firebase ' +\n 'project. Edit the list of authorized domains from the Firebase console.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_OOB_CODE] =\n 'The action code is invalid. This can happen if the code is malformed, ' +\n 'expired, or has already been used.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_PASSWORD] =\n 'The password is invalid or the user does not have a password.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_PERSISTENCE] =\n 'The specified persistence type is invalid. It can only be local, ' +\n 'session or none.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_PHONE_NUMBER] =\n 'The format of the phone number provided is incorrect. Please enter the ' +\n 'phone number in a format that can be parsed into E.164 format. E.164 ' +\n 'phone numbers are written in the format [+][country code][subscriber ' +\n 'number including area code].';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_PROVIDER_ID] =\n 'The specified provider ID is invalid.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_RECIPIENT_EMAIL] =\n 'The email corresponding to this action failed to send as the provided ' +\n 'recipient email address is invalid.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_SENDER] =\n 'The email template corresponding to this action contains an invalid sen' +\n 'der email or name. Please fix by going to the Auth email templates sect' +\n 'ion in the Firebase Console.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_SESSION_INFO] =\n 'The verification ID used to create the phone auth credential is invalid.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.INVALID_TENANT_ID] =\n 'The Auth instance\\'s tenant ID is invalid.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.MFA_ENROLLMENT_NOT_FOUND] = 'The user does not ' +\n 'have a second factor matching the identifier provided.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MFA_REQUIRED] =\n 'Proof of ownership of a second factor is required to complete sign-in.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.MISSING_ANDROID_PACKAGE_NAME] = 'An Android ' +\n 'Package Name must be provided if the Android App is required to be ' +\n 'installed.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_AUTH_DOMAIN] =\n 'Be sure to include authDomain when calling firebase.initializeApp(), ' +\n 'by following the instructions in the Firebase console.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_APP_CREDENTIAL] =\n 'The phone verification request is missing an application verifier ' +\n 'assertion. A reCAPTCHA response token needs to be provided.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_CODE] =\n 'The phone auth credential was created with an empty SMS verification ' +\n 'code.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_CONTINUE_URI] =\n 'A continue URL must be provided in the request.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_IFRAME_START] =\n 'An internal error has occurred.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_IOS_BUNDLE_ID] =\n 'An iOS Bundle ID must be provided if an App Store ID is provided.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.MISSING_MFA_ENROLLMENT_ID] =\n 'No second factor identifier is provided.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.MISSING_MFA_PENDING_CREDENTIAL] =\n 'The request is missing proof of first factor successful sign-in.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_OR_INVALID_NONCE] =\n 'The request does not contain a valid nonce. This can occur if the ' +\n 'SHA-256 hash of the provided raw nonce does not match the hashed nonce ' +\n 'in the ID token payload.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_PHONE_NUMBER] =\n 'To send verification codes, provide a phone number for the recipient.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MISSING_SESSION_INFO] =\n 'The phone auth credential was created with an empty verification ID.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.MODULE_DESTROYED] =\n 'This instance of FirebaseApp has been deleted.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.NEED_CONFIRMATION] =\n 'An account already exists with the same email address but different ' +\n 'sign-in credentials. Sign in using a provider associated with this ' +\n 'email address.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.NETWORK_REQUEST_FAILED] =\n 'A network error (such as timeout, interrupted connection or ' +\n 'unreachable host) has occurred.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.NO_AUTH_EVENT] =\n 'An internal error has occurred.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.NO_SUCH_PROVIDER] =\n 'User was not linked to an account with the given provider.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.NULL_USER] =\n 'A null user object was provided as the argument for an operation which ' +\n 'requires a non-null user object.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.OPERATION_NOT_ALLOWED] =\n 'The given sign-in provider is disabled for this Firebase project. ' +\n 'Enable it in the Firebase console, under the sign-in method tab of the ' +\n 'Auth section.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.OPERATION_NOT_SUPPORTED] =\n 'This operation is not supported in the environment this application is ' +\n 'running on. \"location.protocol\" must be http, https or chrome-extension' +\n ' and web storage must be enabled.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.POPUP_BLOCKED] =\n 'Unable to establish a connection with the popup. It may have been ' +\n 'blocked by the browser.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.POPUP_CLOSED_BY_USER] =\n 'The popup has been closed by the user before finalizing the operation.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.PROVIDER_ALREADY_LINKED] =\n 'User can only be linked to one identity for the given provider.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.QUOTA_EXCEEDED] =\n 'The project\\'s quota for this operation has been exceeded.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.REDIRECT_CANCELLED_BY_USER] =\n 'The redirect operation has been cancelled by the user before finalizing.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.REDIRECT_OPERATION_PENDING] =\n 'A redirect sign-in operation is already pending.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.REJECTED_CREDENTIAL] =\n 'The request contains malformed or mismatching credentials.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.SECOND_FACTOR_EXISTS] =\n 'The second factor is already enrolled on this account.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.SECOND_FACTOR_LIMIT_EXCEEDED] =\n 'The maximum allowed number of second factors on a user has been exceeded.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.TENANT_ID_MISMATCH] =\n 'The provided tenant ID does not match the Auth instance\\'s tenant ID';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.TIMEOUT] =\n 'The operation has timed out.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.TOKEN_EXPIRED] =\n 'The user\\'s credential is no longer valid. The user must sign in again.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.TOO_MANY_ATTEMPTS_TRY_LATER] =\n 'We have blocked all requests from this device due to unusual activity. ' +\n 'Try again later.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.UNAUTHORIZED_DOMAIN] =\n 'The domain of the continue URL is not whitelisted. Please whitelist ' +\n 'the domain in the Firebase console.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.UNSUPPORTED_FIRST_FACTOR] = 'Enrolling a second ' +\n 'factor or signing in with a multi-factor account requires sign-in with ' +\n 'a supported first factor.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.UNSUPPORTED_PERSISTENCE] =\n 'The current environment does not support the specified persistence type.';\nfireauth.AuthError.MESSAGES_[\n fireauth.authenum.Error.UNSUPPORTED_TENANT_OPERATION] =\n 'This operation is not supported in a multi-tenant context.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.UNVERIFIED_EMAIL] =\n 'The operation requires a verified email.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.USER_CANCELLED] =\n 'The user did not grant your application the permissions it requested.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.USER_DELETED] =\n 'There is no user record corresponding to this identifier. The user may ' +\n 'have been deleted.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.USER_DISABLED] =\n 'The user account has been disabled by an administrator.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.USER_MISMATCH] =\n 'The supplied credentials do not correspond to the previously signed in ' +\n 'user.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.USER_SIGNED_OUT] = '';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.WEAK_PASSWORD] =\n 'The password must be 6 characters long or more.';\nfireauth.AuthError.MESSAGES_[fireauth.authenum.Error.WEB_STORAGE_UNSUPPORTED] =\n 'This browser is not supported or 3rd party cookies and data may be ' +\n 'disabled.';\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 all common constants and enums used by firebase-auth.\n */\n\ngoog.provide('fireauth.constants');\ngoog.provide('fireauth.constants.AuthEventType');\n\n\n/**\n * Enums for authentication operation types.\n * @enum {string}\n */\nfireauth.constants.OperationType = {\n LINK: 'link',\n REAUTHENTICATE: 'reauthenticate',\n SIGN_IN: 'signIn'\n};\n\n\n/**\n * Events dispatched firebase.auth.Auth.\n * @enum {string}\n */\nfireauth.constants.AuthEventType = {\n /** Dispatched when Firebase framework is changed. */\n FRAMEWORK_CHANGED: 'frameworkChanged',\n /** Dispatched when language code is changed. */\n LANGUAGE_CODE_CHANGED: 'languageCodeChanged'\n};\n\n\n/**\n * Enums for all second factor types.\n * @enum {string}\n */\nfireauth.constants.SecondFactorType = {\n PHONE: 'phone'\n};\n\n\n/**\n * The settings of an Auth endpoint. The fields are:\n * <ul>\n * <li>firebaseAuthEndpoint: defines the Firebase Auth backend endpoint for\n * specified endpoint type.</li>\n * <li>secureTokenEndpoint: defines the secure token backend endpoint for\n * specified endpoint type.</li>\n * <li>identityPlatformEndpoint: defines the Identity Platform backend endpoint\n * for specified endpoint type.</li>\n * <li>id: defines the endpoint identifier.</li>\n * </ul>\n * @typedef {{\n * firebaseAuthEndpoint: string,\n * secureTokenEndpoint: string,\n * identityPlatformEndpoint: string,\n * id: string\n * }}\n */\nfireauth.constants.EndpointSettings;\n\n\n/**\n * The different endpoints for Firebase Auth backend.\n * @enum {!fireauth.constants.EndpointSettings}\n */\nfireauth.constants.Endpoint = {\n // TODO: this is no longer needed now that client endpoint migration is\n // completed.\n BOQ: {\n firebaseAuthEndpoint: 'https://staging-identitytoolkit.sandbox.googleapi' +\n 's.com/identitytoolkit/v3/relyingparty/',\n secureTokenEndpoint: 'https://staging-securetoken.sandbox.googleapis.com' +\n '/v1/token',\n identityPlatformEndpoint:\n 'https://staging-identitytoolkit.sandbox.googleapis.com/v2/',\n id: 'b'\n },\n PRODUCTION: {\n firebaseAuthEndpoint: 'https://www.googleapis.com/identitytoolkit/v3/' +\n 'relyingparty/',\n secureTokenEndpoint: 'https://securetoken.googleapis.com/v1/token',\n identityPlatformEndpoint:\n 'https://identitytoolkit.googleapis.com/v2/',\n id: 'p'\n },\n STAGING: {\n firebaseAuthEndpoint: 'https://staging-www.sandbox.googleapis.com/' +\n 'identitytoolkit/v3/relyingparty/',\n secureTokenEndpoint: 'https://staging-securetoken.sandbox.googleapis.com' +\n '/v1/token',\n identityPlatformEndpoint:\n 'https://staging-identitytoolkit.sandbox.googleapis.com/v2/',\n id: 's'\n },\n TEST: {\n firebaseAuthEndpoint: 'https://www-googleapis-test.sandbox.google.com/' +\n 'identitytoolkit/v3/relyingparty/',\n secureTokenEndpoint: 'https://test-securetoken.sandbox.googleapis.com/v1' +\n '/token',\n identityPlatformEndpoint:\n 'https://test-identitytoolkit.sandbox.googleapis.com/v2/',\n id: 't'\n }\n};\n\n\n/**\n * Returns the endpoint specific RpcHandler configuration.\n * @param {?string=} opt_id The identifier of the endpoint type if available.\n * @return {?Object|undefined} The RpcHandler endpoint configuration object.\n */\nfireauth.constants.getEndpointConfig = function(opt_id) {\n for (var endpointKey in fireauth.constants.Endpoint) {\n if (fireauth.constants.Endpoint[endpointKey].id === opt_id) {\n var endpoint = fireauth.constants.Endpoint[endpointKey];\n return {\n 'firebaseEndpoint': endpoint.firebaseAuthEndpoint,\n 'secureTokenEndpoint': endpoint.secureTokenEndpoint,\n 'identityPlatformEndpoint': endpoint.identityPlatformEndpoint\n };\n }\n }\n return null;\n};\n\n\n/**\n * Returns the validated endpoint identifier. Undefined if the provided one is\n * invalid.\n * @param {?string=} opt_id The identifier of the endpoint type if available.\n * @return {string|undefined} The validated endpoint ID. If not valid,\n * undefined.\n */\nfireauth.constants.getEndpointId = function(opt_id) {\n if (opt_id && fireauth.constants.getEndpointConfig(opt_id)) {\n return opt_id;\n }\n return undefined;\n};\n\n\n/** @const {string|undefined} The current client endpoint. */\nfireauth.constants.clientEndpoint = fireauth.constants.getEndpointId('__EID__');\n\n\n/** @const {string} The required SAML provider ID prefix. */\nfireauth.constants.SAML_PREFIX = 'saml.';\n\n\n/** @const {string} The required OIDC provider ID prefix. */\nfireauth.constants.OIDC_PREFIX = 'oidc.';\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.Thenable');\n\n/** @suppress {extraRequire} used in complex type */\ngoog.requireType('goog.Promise'); // for the type reference.\n\n\n\n/**\n * Provides a more strict interface for Thenables in terms of\n * http://promisesaplus.com for interop with {@see goog.Promise}.\n *\n * @interface\n * @extends {IThenable<TYPE>}\n * @template TYPE\n */\ngoog.Thenable = function() {};\n\n\n/**\n * Adds callbacks that will operate on the result of the Thenable, returning a\n * new child Promise.\n *\n * If the Thenable is fulfilled, the `onFulfilled` callback will be\n * invoked with the fulfillment value as argument, and the child Promise will\n * be fulfilled with the return value of the callback. If the callback throws\n * an exception, the child Promise will be rejected with the thrown value\n * instead.\n *\n * If the Thenable is rejected, the `onRejected` callback will be invoked\n * with the rejection reason as argument, and the child Promise will be rejected\n * with the return value of the callback or thrown value.\n *\n * @param {?(function(this:THIS, TYPE): VALUE)=} opt_onFulfilled A\n * function that will be invoked with the fulfillment value if the Promise\n * is fulfilled.\n * @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will\n * be invoked with the rejection reason if the Promise is rejected.\n * @param {THIS=} opt_context An optional context object that will be the\n * execution context for the callbacks. By default, functions are executed\n * with the default this.\n *\n * @return {RESULT} A new Promise that will receive the result\n * of the fulfillment or rejection callback.\n * @template VALUE\n * @template THIS\n *\n * When a Promise (or thenable) is returned from the fulfilled callback,\n * the result is the payload of that promise, not the promise itself.\n *\n * @template RESULT := type('goog.Promise',\n * cond(isUnknown(VALUE), unknown(),\n * mapunion(VALUE, (V) =>\n * cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),\n * templateTypeOf(V, 0),\n * cond(sub(V, 'Thenable'),\n * unknown(),\n * V)))))\n * =:\n *\n */\ngoog.Thenable.prototype.then = function(\n opt_onFulfilled, opt_onRejected, opt_context) {};\n\n\n/**\n * An expando property to indicate that an object implements\n * `goog.Thenable`.\n *\n * {@see addImplementation}.\n *\n * @const\n */\ngoog.Thenable.IMPLEMENTED_BY_PROP = '$goog_Thenable';\n\n\n/**\n * Marks a given class (constructor) as an implementation of Thenable, so\n * that we can query that fact at runtime. The class must have already\n * implemented the interface.\n * Exports a 'then' method on the constructor prototype, so that the objects\n * also implement the extern {@see goog.Thenable} interface for interop with\n * other Promise implementations.\n * @param {function(new:goog.Thenable,...?)} ctor The class constructor. The\n * corresponding class must have already implemented the interface.\n */\ngoog.Thenable.addImplementation = function(ctor) {\n if (COMPILED) {\n ctor.prototype[goog.Thenable.IMPLEMENTED_BY_PROP] = true;\n } else {\n // Avoids dictionary access in uncompiled mode.\n ctor.prototype.$goog_Thenable = true;\n }\n};\n\n\n/**\n * @param {?} object\n * @return {boolean} Whether a given instance implements `goog.Thenable`.\n * The class/superclass of the instance must call `addImplementation`.\n */\ngoog.Thenable.isImplementedBy = function(object) {\n if (!object) {\n return false;\n }\n try {\n if (COMPILED) {\n return !!object[goog.Thenable.IMPLEMENTED_BY_PROP];\n }\n return !!object.$goog_Thenable;\n } catch (e) {\n // Property access seems to be forbidden.\n return false;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a base class for custom Error objects such that the\n * stack is correctly maintained.\n *\n * You should never need to throw goog.debug.Error(msg) directly, Error(msg) is\n * sufficient.\n */\n\ngoog.provide('goog.debug.Error');\n\n\n\n/**\n * Base class for custom error objects.\n * @param {*=} opt_msg The message associated with the error.\n * @constructor\n * @extends {Error}\n */\ngoog.debug.Error = function(opt_msg) {\n\n // Attempt to ensure there is a stack trace.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, goog.debug.Error);\n } else {\n const stack = new Error().stack;\n if (stack) {\n /** @override */\n this.stack = stack;\n }\n }\n\n if (opt_msg) {\n /** @override */\n this.message = String(opt_msg);\n }\n\n /**\n * Whether to report this error to the server. Setting this to false will\n * cause the error reporter to not report the error back to the server,\n * which can be useful if the client knows that the error has already been\n * logged on the server.\n * @type {boolean}\n */\n this.reportErrorToServer = true;\n};\ngoog.inherits(goog.debug.Error, Error);\n\n\n/** @override */\ngoog.debug.Error.prototype.name = 'CustomError';\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities to check the preconditions, postconditions and\n * invariants runtime.\n *\n * Methods in this package are given special treatment by the compiler\n * for type-inference. For example, <code>goog.asserts.assert(foo)</code>\n * will make the compiler treat <code>foo</code> as non-nullable. Similarly,\n * <code>goog.asserts.assertNumber(foo)</code> informs the compiler about the\n * type of <code>foo</code>. Where applicable, such assertions are preferable to\n * casts by jsdoc with <code>@type</code>.\n *\n * The compiler has an option to disable asserts. So code like:\n * <code>\n * var x = goog.asserts.assert(foo());\n * goog.asserts.assert(bar());\n * </code>\n * will be transformed into:\n * <code>\n * var x = foo();\n * </code>\n * The compiler will leave in foo() (because its return value is used),\n * but it will remove bar() because it assumes it does not have side-effects.\n *\n * Additionally, note the compiler will consider the type to be \"tightened\" for\n * all statements <em>after</em> the assertion. For example:\n * <code>\n * const /** ?Object &#ast;/ value = foo();\n * goog.asserts.assert(value);\n * // \"value\" is of type {!Object} at this point.\n * </code>\n */\n\ngoog.provide('goog.asserts');\ngoog.provide('goog.asserts.AssertionError');\n\ngoog.require('goog.debug.Error');\ngoog.require('goog.dom.NodeType');\n\n\n/**\n * @define {boolean} Whether to strip out asserts or to leave them in.\n */\ngoog.asserts.ENABLE_ASSERTS =\n goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG);\n\n\n\n/**\n * Error object for failed assertions.\n * @param {string} messagePattern The pattern that was used to form message.\n * @param {!Array<*>} messageArgs The items to substitute into the pattern.\n * @constructor\n * @extends {goog.debug.Error}\n * @final\n */\ngoog.asserts.AssertionError = function(messagePattern, messageArgs) {\n goog.debug.Error.call(this, goog.asserts.subs_(messagePattern, messageArgs));\n\n /**\n * The message pattern used to format the error message. Error handlers can\n * use this to uniquely identify the assertion.\n * @type {string}\n */\n this.messagePattern = messagePattern;\n};\ngoog.inherits(goog.asserts.AssertionError, goog.debug.Error);\n\n\n/** @override */\ngoog.asserts.AssertionError.prototype.name = 'AssertionError';\n\n\n/**\n * The default error handler.\n * @param {!goog.asserts.AssertionError} e The exception to be handled.\n */\ngoog.asserts.DEFAULT_ERROR_HANDLER = function(e) {\n throw e;\n};\n\n\n/**\n * The handler responsible for throwing or logging assertion errors.\n * @private {function(!goog.asserts.AssertionError)}\n */\ngoog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER;\n\n\n/**\n * Does simple python-style string substitution.\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\n * @param {string} pattern The string containing the pattern.\n * @param {!Array<*>} subs The items to substitute into the pattern.\n * @return {string} A copy of `str` in which each occurrence of\n * {@code %s} has been replaced an argument from `var_args`.\n * @private\n */\ngoog.asserts.subs_ = function(pattern, subs) {\n var splitParts = pattern.split('%s');\n var returnString = '';\n\n // Replace up to the last split part. We are inserting in the\n // positions between split parts.\n var subLast = splitParts.length - 1;\n for (var i = 0; i < subLast; i++) {\n // keep unsupplied as '%s'\n var sub = (i < subs.length) ? subs[i] : '%s';\n returnString += splitParts[i] + sub;\n }\n return returnString + splitParts[subLast];\n};\n\n\n/**\n * Throws an exception with the given message and \"Assertion failed\" prefixed\n * onto it.\n * @param {string} defaultMessage The message to use if givenMessage is empty.\n * @param {Array<*>} defaultArgs The substitution arguments for defaultMessage.\n * @param {string|undefined} givenMessage Message supplied by the caller.\n * @param {Array<*>} givenArgs The substitution arguments for givenMessage.\n * @throws {goog.asserts.AssertionError} When the value is not a number.\n * @private\n */\ngoog.asserts.doAssertFailure_ = function(\n defaultMessage, defaultArgs, givenMessage, givenArgs) {\n var message = 'Assertion failed';\n if (givenMessage) {\n message += ': ' + givenMessage;\n var args = givenArgs;\n } else if (defaultMessage) {\n message += ': ' + defaultMessage;\n args = defaultArgs;\n }\n // The '' + works around an Opera 10 bug in the unit tests. Without it,\n // a stack trace is added to var message above. With this, a stack trace is\n // not added until this line (it causes the extra garbage to be added after\n // the assertion message instead of in the middle of it).\n var e = new goog.asserts.AssertionError('' + message, args || []);\n goog.asserts.errorHandler_(e);\n};\n\n\n/**\n * Sets a custom error handler that can be used to customize the behavior of\n * assertion failures, for example by turning all assertion failures into log\n * messages.\n * @param {function(!goog.asserts.AssertionError)} errorHandler\n */\ngoog.asserts.setErrorHandler = function(errorHandler) {\n if (goog.asserts.ENABLE_ASSERTS) {\n goog.asserts.errorHandler_ = errorHandler;\n }\n};\n\n\n/**\n * Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is\n * true.\n * @template T\n * @param {T} condition The condition to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {T} The value of the condition.\n * @throws {goog.asserts.AssertionError} When the condition evaluates to false.\n * @closurePrimitive {asserts.truthy}\n */\ngoog.asserts.assert = function(condition, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && !condition) {\n goog.asserts.doAssertFailure_(\n '', null, opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return condition;\n};\n\n\n/**\n * Checks if `value` is `null` or `undefined` if goog.asserts.ENABLE_ASSERTS is\n * true.\n *\n * @param {T} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {R} `value` with its type narrowed to exclude `null` and `undefined`.\n *\n * @template T\n * @template R :=\n * mapunion(T, (V) =>\n * cond(eq(V, 'null'),\n * none(),\n * cond(eq(V, 'undefined'),\n * none(),\n * V)))\n * =:\n *\n * @throws {!goog.asserts.AssertionError} When `value` is `null` or `undefined`.\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertExists = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && value == null) {\n goog.asserts.doAssertFailure_(\n 'Expected to exist: %s.', [value], opt_message,\n Array.prototype.slice.call(arguments, 2));\n }\n return value;\n};\n\n\n/**\n * Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case\n * when we want to add a check in the unreachable area like switch-case\n * statement:\n *\n * <pre>\n * switch(type) {\n * case FOO: doSomething(); break;\n * case BAR: doSomethingElse(); break;\n * default: goog.asserts.fail('Unrecognized type: ' + type);\n * // We have only 2 types - \"default:\" section is unreachable code.\n * }\n * </pre>\n *\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @throws {goog.asserts.AssertionError} Failure.\n * @closurePrimitive {asserts.fail}\n */\ngoog.asserts.fail = function(opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS) {\n goog.asserts.errorHandler_(new goog.asserts.AssertionError(\n 'Failure' + (opt_message ? ': ' + opt_message : ''),\n Array.prototype.slice.call(arguments, 1)));\n }\n};\n\n\n/**\n * Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true.\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {number} The value, guaranteed to be a number when asserts enabled.\n * @throws {goog.asserts.AssertionError} When the value is not a number.\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertNumber = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && typeof value !== 'number') {\n goog.asserts.doAssertFailure_(\n 'Expected number but got %s: %s.', [goog.typeOf(value), value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {number} */ (value);\n};\n\n\n/**\n * Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true.\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {string} The value, guaranteed to be a string when asserts enabled.\n * @throws {goog.asserts.AssertionError} When the value is not a string.\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertString = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && typeof value !== 'string') {\n goog.asserts.doAssertFailure_(\n 'Expected string but got %s: %s.', [goog.typeOf(value), value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {string} */ (value);\n};\n\n\n/**\n * Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true.\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {!Function} The value, guaranteed to be a function when asserts\n * enabled.\n * @throws {goog.asserts.AssertionError} When the value is not a function.\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertFunction = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) {\n goog.asserts.doAssertFailure_(\n 'Expected function but got %s: %s.', [goog.typeOf(value), value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {!Function} */ (value);\n};\n\n\n/**\n * Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true.\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {!Object} The value, guaranteed to be a non-null object.\n * @throws {goog.asserts.AssertionError} When the value is not an object.\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertObject = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) {\n goog.asserts.doAssertFailure_(\n 'Expected object but got %s: %s.', [goog.typeOf(value), value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {!Object} */ (value);\n};\n\n\n/**\n * Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true.\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {!Array<?>} The value, guaranteed to be a non-null array.\n * @throws {goog.asserts.AssertionError} When the value is not an array.\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertArray = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && !Array.isArray(value)) {\n goog.asserts.doAssertFailure_(\n 'Expected array but got %s: %s.', [goog.typeOf(value), value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {!Array<?>} */ (value);\n};\n\n\n/**\n * Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true.\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {boolean} The value, guaranteed to be a boolean when asserts are\n * enabled.\n * @throws {goog.asserts.AssertionError} When the value is not a boolean.\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertBoolean = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && typeof value !== 'boolean') {\n goog.asserts.doAssertFailure_(\n 'Expected boolean but got %s: %s.', [goog.typeOf(value), value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {boolean} */ (value);\n};\n\n\n/**\n * Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true.\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @return {!Element} The value, likely to be a DOM Element when asserts are\n * enabled.\n * @throws {goog.asserts.AssertionError} When the value is not an Element.\n * @closurePrimitive {asserts.matchesReturn}\n * @deprecated Use goog.asserts.dom.assertIsElement instead.\n */\ngoog.asserts.assertElement = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS &&\n (!goog.isObject(value) ||\n /** @type {!Node} */ (value).nodeType != goog.dom.NodeType.ELEMENT)) {\n goog.asserts.doAssertFailure_(\n 'Expected Element but got %s: %s.', [goog.typeOf(value), value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {!Element} */ (value);\n};\n\n\n/**\n * Checks if the value is an instance of the user-defined type if\n * goog.asserts.ENABLE_ASSERTS is true.\n *\n * The compiler may tighten the type returned by this function.\n *\n * Do not use this to ensure a value is an HTMLElement or a subclass! Cross-\n * document DOM inherits from separate - though identical - browser classes, and\n * such a check will unexpectedly fail. Please use the methods in\n * goog.asserts.dom for these purposes.\n *\n * @param {?} value The value to check.\n * @param {function(new: T, ...)} type A user-defined constructor.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @throws {goog.asserts.AssertionError} When the value is not an instance of\n * type.\n * @return {T}\n * @template T\n * @closurePrimitive {asserts.matchesReturn}\n */\ngoog.asserts.assertInstanceof = function(value, type, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) {\n goog.asserts.doAssertFailure_(\n 'Expected instanceof %s but got %s.',\n [goog.asserts.getType_(type), goog.asserts.getType_(value)],\n opt_message, Array.prototype.slice.call(arguments, 3));\n }\n return value;\n};\n\n\n/**\n * Checks whether the value is a finite number, if goog.asserts.ENABLE_ASSERTS\n * is true.\n *\n * @param {*} value The value to check.\n * @param {string=} opt_message Error message in case of failure.\n * @param {...*} var_args The items to substitute into the failure message.\n * @throws {goog.asserts.AssertionError} When the value is not a number, or is\n * a non-finite number such as NaN, Infinity or -Infinity.\n * @return {number} The value initially passed in.\n */\ngoog.asserts.assertFinite = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS &&\n (typeof value != 'number' || !isFinite(value))) {\n goog.asserts.doAssertFailure_(\n 'Expected %s to be a finite number but it is not.', [value],\n opt_message, Array.prototype.slice.call(arguments, 2));\n }\n return /** @type {number} */ (value);\n};\n\n/**\n * Checks that no enumerable keys are present in Object.prototype. Such keys\n * would break most code that use {@code for (var ... in ...)} loops.\n */\ngoog.asserts.assertObjectPrototypeIsIntact = function() {\n for (var key in Object.prototype) {\n goog.asserts.fail(key + ' should not be enumerable in Object.prototype.');\n }\n};\n\n\n/**\n * Returns the type of a value. If a constructor is passed, and a suitable\n * string cannot be found, 'unknown type name' will be returned.\n * @param {*} value A constructor, object, or primitive.\n * @return {string} The best display name for the value, or 'unknown type name'.\n * @private\n */\ngoog.asserts.getType_ = function(value) {\n if (value instanceof Function) {\n return value.displayName || value.name || 'unknown type name';\n } else if (value instanceof Object) {\n return /** @type {string} */ (value.constructor.displayName) ||\n value.constructor.name || Object.prototype.toString.call(value);\n } else {\n return value === null ? 'null' : typeof value;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple freelist.\n *\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\n * objects in the list contain a \"next\" property that can be used to maintain\n * the pool.\n */\n\ngoog.provide('goog.async.FreeList');\n\n\n/**\n * @template ITEM\n */\ngoog.async.FreeList = class {\n /**\n * @param {function():ITEM} create\n * @param {function(ITEM):void} reset\n * @param {number} limit\n */\n constructor(create, reset, limit) {\n /** @private @const {number} */\n this.limit_ = limit;\n /** @private @const {function()} */\n this.create_ = create;\n /** @private @const {function(ITEM):void} */\n this.reset_ = reset;\n\n /** @private {number} */\n this.occupants_ = 0;\n /** @private {ITEM} */\n this.head_ = null;\n }\n\n /**\n * @return {ITEM}\n */\n get() {\n let item;\n if (this.occupants_ > 0) {\n this.occupants_--;\n item = this.head_;\n this.head_ = item.next;\n item.next = null;\n } else {\n item = this.create_();\n }\n return item;\n }\n\n /**\n * @param {ITEM} item An item available for possible future reuse.\n */\n put(item) {\n this.reset_(item);\n if (this.occupants_ < this.limit_) {\n this.occupants_++;\n item.next = this.head_;\n this.head_ = item;\n }\n }\n\n /**\n * Visible for testing.\n * @package\n * @return {number}\n */\n occupants() {\n return this.occupants_;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.async.WorkItem');\ngoog.provide('goog.async.WorkQueue');\n\ngoog.require('goog.asserts');\ngoog.require('goog.async.FreeList');\n\n\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\n// than goog.async.run.\n\n\n\n/**\n * A low GC workqueue. The key elements of this design:\n * - avoids the need for goog.bind or equivalent by carrying scope\n * - avoids the need for array reallocation by using a linked list\n * - minimizes work entry objects allocation by recycling objects\n * @constructor\n * @final\n * @struct\n */\ngoog.async.WorkQueue = function() {\n this.workHead_ = null;\n this.workTail_ = null;\n};\n\n\n/** @define {number} The maximum number of entries to keep for recycling. */\ngoog.async.WorkQueue.DEFAULT_MAX_UNUSED =\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\n\n\n/** @const @private {goog.async.FreeList<goog.async.WorkItem>} */\ngoog.async.WorkQueue.freelist_ = new goog.async.FreeList(\n function() { return new goog.async.WorkItem(); },\n function(item) { item.reset(); }, goog.async.WorkQueue.DEFAULT_MAX_UNUSED);\n\n\n/**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\ngoog.async.WorkQueue.prototype.add = function(fn, scope) {\n var item = this.getUnusedItem_();\n item.set(fn, scope);\n\n if (this.workTail_) {\n this.workTail_.next = item;\n this.workTail_ = item;\n } else {\n goog.asserts.assert(!this.workHead_);\n this.workHead_ = item;\n this.workTail_ = item;\n }\n};\n\n\n/**\n * @return {goog.async.WorkItem}\n */\ngoog.async.WorkQueue.prototype.remove = function() {\n var item = null;\n\n if (this.workHead_) {\n item = this.workHead_;\n this.workHead_ = this.workHead_.next;\n if (!this.workHead_) {\n this.workTail_ = null;\n }\n item.next = null;\n }\n return item;\n};\n\n\n/**\n * @param {goog.async.WorkItem} item\n */\ngoog.async.WorkQueue.prototype.returnUnused = function(item) {\n goog.async.WorkQueue.freelist_.put(item);\n};\n\n\n/**\n * @return {goog.async.WorkItem}\n * @private\n */\ngoog.async.WorkQueue.prototype.getUnusedItem_ = function() {\n return goog.async.WorkQueue.freelist_.get();\n};\n\n\n\n/**\n * @constructor\n * @final\n * @struct\n */\ngoog.async.WorkItem = function() {\n /** @type {?function()} */\n this.fn = null;\n /** @type {?Object|null|undefined} */\n this.scope = null;\n /** @type {?goog.async.WorkItem} */\n this.next = null;\n};\n\n\n/**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\ngoog.async.WorkItem.prototype.set = function(fn, scope) {\n this.fn = fn;\n this.scope = scope;\n this.next = null;\n};\n\n\n/** Reset the work item so they don't prevent GC before reuse */\ngoog.async.WorkItem.prototype.reset = function() {\n this.fn = null;\n this.scope = null;\n this.next = null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating arrays.\n */\n\n\ngoog.provide('goog.array');\n\ngoog.require('goog.asserts');\n\n\n/**\n * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should\n * rely on Array.prototype functions, if available.\n *\n * The Array.prototype functions can be defined by external libraries like\n * Prototype and setting this flag to false forces closure to use its own\n * goog.array implementation.\n *\n * If your javascript can be loaded by a third party site and you are wary about\n * relying on the prototype functions, specify\n * \"--define goog.NATIVE_ARRAY_PROTOTYPES=false\" to the JSCompiler.\n *\n * Setting goog.TRUSTED_SITE to false will automatically set\n * NATIVE_ARRAY_PROTOTYPES to false.\n */\ngoog.NATIVE_ARRAY_PROTOTYPES =\n goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);\n\n\n/**\n * @define {boolean} If true, JSCompiler will use the native implementation of\n * array functions where appropriate (e.g., `Array#filter`) and remove the\n * unused pure JS implementation.\n */\ngoog.array.ASSUME_NATIVE_FUNCTIONS = goog.define(\n 'goog.array.ASSUME_NATIVE_FUNCTIONS', goog.FEATURESET_YEAR > 2012);\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as goog.array.last.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\ngoog.array.peek = function(array) {\n return array[array.length - 1];\n};\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as goog.array.peek.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\ngoog.array.last = goog.array.peek;\n\n// NOTE(arv): Since most of the array functions are generic it allows you to\n// pass an array-like object. Strings have a length and are considered array-\n// like. However, the 'in' operator does not work on strings so we cannot just\n// use the array path even if the browser supports indexing into strings. We\n// therefore end up splitting the string.\n\n\n/**\n * Returns the index of the first element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}\n *\n * @param {IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at index 0.\n * @return {number} The index of the first matching array element.\n * @template T\n */\ngoog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\n function(arr, obj, opt_fromIndex) {\n goog.asserts.assert(arr.length != null);\n\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n var fromIndex = opt_fromIndex == null ?\n 0 :\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\n opt_fromIndex);\n\n if (typeof arr === 'string') {\n // Array.prototype.indexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.indexOf(obj, fromIndex);\n }\n\n for (var i = fromIndex; i < arr.length; i++) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\n\n\n/**\n * Returns the index of the last element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}\n *\n * @param {!IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {?number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at the end of the array.\n * @return {number} The index of the last matching array element.\n * @template T\n */\ngoog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\n function(arr, obj, opt_fromIndex) {\n goog.asserts.assert(arr.length != null);\n\n // Firefox treats undefined and null as 0 in the fromIndex argument which\n // leads it to always return -1\n var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n\n if (fromIndex < 0) {\n fromIndex = Math.max(0, arr.length + fromIndex);\n }\n\n if (typeof arr === 'string') {\n // Array.prototype.lastIndexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.lastIndexOf(obj, fromIndex);\n }\n\n for (var i = fromIndex; i >= 0; i--) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\n\n\n/**\n * Calls a function for each element in an array. Skips holes in the array.\n * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}\n *\n * @param {IArrayLike<T>|string} arr Array or array like object over\n * which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function takes 3 arguments (the element, the index and the\n * array). The return value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @template T,S\n */\ngoog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\n function(arr, f, opt_obj) {\n goog.asserts.assert(arr.length != null);\n\n Array.prototype.forEach.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = 0; i < l; i++) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n };\n\n\n/**\n * Calls a function for each element in an array, starting from the last\n * element rather than the first.\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function\n * takes 3 arguments (the element, the index and the array). The return\n * value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @template T,S\n */\ngoog.array.forEachRight = function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = l - 1; i >= 0; --i) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n};\n\n\n/**\n * Calls a function for each element in an array, and if the function returns\n * true adds the element to a new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?):boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and must\n * return a Boolean. If the return value is true the element is added to the\n * result array. If it is false the element is not included.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {!Array<T>} a new array in which only elements that passed the test\n * are present.\n * @template T,S\n */\ngoog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\n function(arr, f, opt_obj) {\n goog.asserts.assert(arr.length != null);\n\n return Array.prototype.filter.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var res = [];\n var resLength = 0;\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = 0; i < l; i++) {\n if (i in arr2) {\n var val = arr2[i]; // in case f mutates arr2\n if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {\n res[resLength++] = val;\n }\n }\n }\n return res;\n };\n\n\n/**\n * Calls a function for each element in an array and inserts the result into a\n * new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-map}\n *\n * @param {IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call\n * for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return something. The result will be\n * inserted into a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the results from f.\n * @template THIS, VALUE, RESULT\n */\ngoog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\n function(arr, f, opt_obj) {\n goog.asserts.assert(arr.length != null);\n\n return Array.prototype.map.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var res = new Array(l);\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = 0; i < l; i++) {\n if (i in arr2) {\n res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n return res;\n };\n\n\n/**\n * Passes every element of an array into a function and accumulates the result.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}\n *\n * For example:\n * var a = [1, 2, 3, 4];\n * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);\n * returns 10\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Result of evaluating f repeatedly across the values of the array.\n * @template T,S,R\n */\ngoog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\n function(arr, f, val, opt_obj) {\n goog.asserts.assert(arr.length != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduce.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n var rval = val;\n goog.array.forEach(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\n\n\n/**\n * Passes every element of an array into a function and accumulates the result,\n * starting from the last element and working towards the first.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}\n *\n * For example:\n * var a = ['a', 'b', 'c'];\n * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');\n * returns 'cba'\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Object returned as a result of evaluating f repeatedly across the\n * values of the array.\n * @template T,S,R\n */\ngoog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\n function(arr, f, val, opt_obj) {\n goog.asserts.assert(arr.length != null);\n goog.asserts.assert(f != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduceRight.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n var rval = val;\n goog.array.forEachRight(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\n\n\n/**\n * Calls f for each element of an array. If any call returns true, some()\n * returns true (without checking the remaining elements). If all calls\n * return false, some() returns false.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-some}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} true if any element passes the test.\n * @template T,S\n */\ngoog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\n function(arr, f, opt_obj) {\n goog.asserts.assert(arr.length != null);\n\n return Array.prototype.some.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return true;\n }\n }\n return false;\n };\n\n\n/**\n * Call f for each element of an array. If all calls return true, every()\n * returns true. If any call returns false, every() returns false and\n * does not continue to check the remaining elements.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-every}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} false if any element fails the test.\n * @template T,S\n */\ngoog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\n function(arr, f, opt_obj) {\n goog.asserts.assert(arr.length != null);\n\n return Array.prototype.every.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = 0; i < l; i++) {\n if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return false;\n }\n }\n return true;\n };\n\n\n/**\n * Counts the array elements that fulfill the predicate, i.e. for which the\n * callback function returns true. Skips holes in the array.\n *\n * @param {!IArrayLike<T>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this: S, T, number, ?): boolean} f The function to call for\n * every element. Takes 3 arguments (the element, the index and the array).\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @return {number} The number of the matching elements.\n * @template T,S\n */\ngoog.array.count = function(arr, f, opt_obj) {\n var count = 0;\n goog.array.forEach(arr, function(element, index, arr) {\n if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {\n ++count;\n }\n }, opt_obj);\n return count;\n};\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The first array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\ngoog.array.find = function(arr, f, opt_obj) {\n var i = goog.array.findIndex(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n};\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the first array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\ngoog.array.findIndex = function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n};\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The last array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\ngoog.array.findRight = function(arr, f, opt_obj) {\n var i = goog.array.findIndexRight(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n};\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the last array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\ngoog.array.findIndexRight = function(arr, f, opt_obj) {\n var l = arr.length; // must be fixed during loop... see docs\n var arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (var i = l - 1; i >= 0; i--) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n};\n\n\n/**\n * Whether the array contains the given object.\n * @param {IArrayLike<?>|string} arr The array to test for the presence of the\n * element.\n * @param {*} obj The object for which to test.\n * @return {boolean} true if obj is present.\n */\ngoog.array.contains = function(arr, obj) {\n return goog.array.indexOf(arr, obj) >= 0;\n};\n\n\n/**\n * Whether the array is empty.\n * @param {IArrayLike<?>|string} arr The array to test.\n * @return {boolean} true if empty.\n */\ngoog.array.isEmpty = function(arr) {\n return arr.length == 0;\n};\n\n\n/**\n * Clears the array.\n * @param {IArrayLike<?>} arr Array or array like object to clear.\n */\ngoog.array.clear = function(arr) {\n // For non real arrays we don't have the magic length so we delete the\n // indices.\n if (!Array.isArray(arr)) {\n for (var i = arr.length - 1; i >= 0; i--) {\n delete arr[i];\n }\n }\n arr.length = 0;\n};\n\n\n/**\n * Pushes an item into an array, if it's not already in the array.\n * @param {Array<T>} arr Array into which to insert the item.\n * @param {T} obj Value to add.\n * @template T\n */\ngoog.array.insert = function(arr, obj) {\n if (!goog.array.contains(arr, obj)) {\n arr.push(obj);\n }\n};\n\n\n/**\n * Inserts an object at the given index of the array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {*} obj The object to insert.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\ngoog.array.insertAt = function(arr, obj, opt_i) {\n goog.array.splice(arr, opt_i, 0, obj);\n};\n\n\n/**\n * Inserts at the given index of the array, all elements of another array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {IArrayLike<?>} elementsToAdd The array of elements to add.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\ngoog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {\n goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);\n};\n\n\n/**\n * Inserts an object into an array before a specified object.\n * @param {Array<T>} arr The array to modify.\n * @param {T} obj The object to insert.\n * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2\n * is omitted or not found, obj is inserted at the end of the array.\n * @template T\n */\ngoog.array.insertBefore = function(arr, obj, opt_obj2) {\n var i;\n if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {\n arr.push(obj);\n } else {\n goog.array.insertAt(arr, obj, i);\n }\n};\n\n\n/**\n * Removes the first occurrence of a particular value from an array.\n * @param {IArrayLike<T>} arr Array from which to remove\n * value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\ngoog.array.remove = function(arr, obj) {\n var i = goog.array.indexOf(arr, obj);\n var rv;\n if ((rv = i >= 0)) {\n goog.array.removeAt(arr, i);\n }\n return rv;\n};\n\n\n/**\n * Removes the last occurrence of a particular value from an array.\n * @param {!IArrayLike<T>} arr Array from which to remove value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\ngoog.array.removeLast = function(arr, obj) {\n var i = goog.array.lastIndexOf(arr, obj);\n if (i >= 0) {\n goog.array.removeAt(arr, i);\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes from an array the element at index i\n * @param {IArrayLike<?>} arr Array or array like object from which to\n * remove value.\n * @param {number} i The index to remove.\n * @return {boolean} True if an element was removed.\n */\ngoog.array.removeAt = function(arr, i) {\n goog.asserts.assert(arr.length != null);\n\n // use generic form of splice\n // splice returns the removed items and if successful the length of that\n // will be 1\n return Array.prototype.splice.call(arr, i, 1).length == 1;\n};\n\n\n/**\n * Removes the first value that satisfies the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {boolean} True if an element was removed.\n * @template T,S\n */\ngoog.array.removeIf = function(arr, f, opt_obj) {\n var i = goog.array.findIndex(arr, f, opt_obj);\n if (i >= 0) {\n goog.array.removeAt(arr, i);\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes all values that satisfy the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The number of items removed\n * @template T,S\n */\ngoog.array.removeAllIf = function(arr, f, opt_obj) {\n var removedCount = 0;\n goog.array.forEachRight(arr, function(val, index) {\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\n if (goog.array.removeAt(arr, index)) {\n removedCount++;\n }\n }\n });\n return removedCount;\n};\n\n\n/**\n * Returns a new array that is the result of joining the arguments. If arrays\n * are passed then their items are added, however, if non-arrays are passed they\n * will be added to the return array as is.\n *\n * Note that ArrayLike objects will be added as is, rather than having their\n * items added.\n *\n * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\n * goog.array.concat(0, [1, 2]) -> [0, 1, 2]\n * goog.array.concat([1, 2], null) -> [1, 2, null]\n *\n * There is bug in all current versions of IE (6, 7 and 8) where arrays created\n * in an iframe become corrupted soon (not immediately) after the iframe is\n * destroyed. This is common if loading data via goog.net.IframeIo, for example.\n * This corruption only affects the concat method which will start throwing\n * Catastrophic Errors (#-2147418113).\n *\n * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.\n *\n * Internally goog.array should use this, so that all methods will continue to\n * work on these broken array objects.\n *\n * @param {...*} var_args Items to concatenate. Arrays will have each item\n * added, while primitives and objects will be added as is.\n * @return {!Array<?>} The new resultant array.\n */\ngoog.array.concat = function(var_args) {\n return Array.prototype.concat.apply([], arguments);\n};\n\n\n/**\n * Returns a new array that contains the contents of all the arrays passed.\n * @param {...!Array<T>} var_args\n * @return {!Array<T>}\n * @template T\n */\ngoog.array.join = function(var_args) {\n return Array.prototype.concat.apply([], arguments);\n};\n\n\n/**\n * Converts an object to an array.\n * @param {IArrayLike<T>|string} object The object to convert to an\n * array.\n * @return {!Array<T>} The object converted into an array. If object has a\n * length property, every property indexed with a non-negative number\n * less than length will be included in the result. If object does not\n * have a length property, an empty array will be returned.\n * @template T\n */\ngoog.array.toArray = function(object) {\n var length = object.length;\n\n // If length is not a number the following is false. This case is kept for\n // backwards compatibility since there are callers that pass objects that are\n // not array like.\n if (length > 0) {\n var rv = new Array(length);\n for (var i = 0; i < length; i++) {\n rv[i] = object[i];\n }\n return rv;\n }\n return [];\n};\n\n\n/**\n * Does a shallow copy of an array.\n * @param {IArrayLike<T>|string} arr Array or array-like object to\n * clone.\n * @return {!Array<T>} Clone of the input array.\n * @template T\n */\ngoog.array.clone = goog.array.toArray;\n\n\n/**\n * Extends an array with another array, element, or \"array like\" object.\n * This function operates 'in-place', it does not create a new Array.\n *\n * Example:\n * var a = [];\n * goog.array.extend(a, [0, 1]);\n * a; // [0, 1]\n * goog.array.extend(a, 2);\n * a; // [0, 1, 2]\n *\n * @param {Array<VALUE>} arr1 The array to modify.\n * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of\n * elements to add to arr1.\n * @template VALUE\n */\ngoog.array.extend = function(arr1, var_args) {\n for (var i = 1; i < arguments.length; i++) {\n var arr2 = arguments[i];\n if (goog.isArrayLike(arr2)) {\n var len1 = arr1.length || 0;\n var len2 = arr2.length || 0;\n arr1.length = len1 + len2;\n for (var j = 0; j < len2; j++) {\n arr1[len1 + j] = arr2[j];\n }\n } else {\n arr1.push(arr2);\n }\n }\n};\n\n\n/**\n * Adds or removes elements from an array. This is a generic version of Array\n * splice. This means that it might work on other objects similar to arrays,\n * such as the arguments object.\n *\n * @param {IArrayLike<T>} arr The array to modify.\n * @param {number|undefined} index The index at which to start changing the\n * array. If not defined, treated as 0.\n * @param {number} howMany How many elements to remove (0 means no removal. A\n * value below 0 is treated as zero and so is any other non number. Numbers\n * are floored).\n * @param {...T} var_args Optional, additional elements to insert into the\n * array.\n * @return {!Array<T>} the removed elements.\n * @template T\n */\ngoog.array.splice = function(arr, index, howMany, var_args) {\n goog.asserts.assert(arr.length != null);\n\n return Array.prototype.splice.apply(arr, goog.array.slice(arguments, 1));\n};\n\n\n/**\n * Returns a new array from a segment of an array. This is a generic version of\n * Array slice. This means that it might work on other objects similar to\n * arrays, such as the arguments object.\n *\n * @param {IArrayLike<T>|string} arr The array from\n * which to copy a segment.\n * @param {number} start The index of the first element to copy.\n * @param {number=} opt_end The index after the last element to copy.\n * @return {!Array<T>} A new array containing the specified segment of the\n * original array.\n * @template T\n */\ngoog.array.slice = function(arr, start, opt_end) {\n goog.asserts.assert(arr.length != null);\n\n // passing 1 arg to slice is not the same as passing 2 where the second is\n // null or undefined (in that case the second argument is treated as 0).\n // we could use slice on the arguments object and then use apply instead of\n // testing the length\n if (arguments.length <= 2) {\n return Array.prototype.slice.call(arr, start);\n } else {\n return Array.prototype.slice.call(arr, start, opt_end);\n }\n};\n\n\n/**\n * Removes all duplicates from an array (retaining only the first\n * occurrence of each array element). This function modifies the\n * array in place and doesn't change the order of the non-duplicate items.\n *\n * For objects, duplicates are identified as having the same unique ID as\n * defined by {@link goog.getUid}.\n *\n * Alternatively you can specify a custom hash function that returns a unique\n * value for each item in the array it should consider unique.\n *\n * Runtime: N,\n * Worstcase space: 2N (no dupes)\n *\n * @param {IArrayLike<T>} arr The array from which to remove\n * duplicates.\n * @param {Array=} opt_rv An optional array in which to return the results,\n * instead of performing the removal inplace. If specified, the original\n * array will remain unchanged.\n * @param {function(T):string=} opt_hashFn An optional function to use to\n * apply to every item in the array. This function should return a unique\n * value for each item in the array it should consider unique.\n * @template T\n */\ngoog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {\n var returnArray = opt_rv || arr;\n var defaultHashFn = function(item) {\n // Prefix each type with a single character representing the type to\n // prevent conflicting keys (e.g. true and 'true').\n return goog.isObject(item) ? 'o' + goog.getUid(item) :\n (typeof item).charAt(0) + item;\n };\n var hashFn = opt_hashFn || defaultHashFn;\n\n var seen = {}, cursorInsert = 0, cursorRead = 0;\n while (cursorRead < arr.length) {\n var current = arr[cursorRead++];\n var key = hashFn(current);\n if (!Object.prototype.hasOwnProperty.call(seen, key)) {\n seen[key] = true;\n returnArray[cursorInsert++] = current;\n }\n }\n returnArray.length = cursorInsert;\n};\n\n\n/**\n * Searches the specified array for the specified target using the binary\n * search algorithm. If no opt_compareFn is specified, elements are compared\n * using <code>goog.array.defaultCompare</code>, which compares the elements\n * using the built in < and > operators. This will produce the expected\n * behavior for homogeneous arrays of String(s) and Number(s). The array\n * specified <b>must</b> be sorted in ascending order (as defined by the\n * comparison function). If the array is not sorted, results are undefined.\n * If the array contains multiple instances of the specified target value, the\n * left-most instance will be found.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {TARGET} target The sought value.\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, the target value and an element from your array, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @template TARGET, VALUE\n */\ngoog.array.binarySearch = function(arr, target, opt_compareFn) {\n return goog.array.binarySearch_(\n arr, opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,\n target);\n};\n\n\n/**\n * Selects an index in the specified array using the binary search algorithm.\n * The evaluator receives an element and determines whether the desired index\n * is before, at, or after it. The evaluator must be consistent (formally,\n * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)\n * must be monotonically non-increasing).\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {function(this:THIS, VALUE, number, ?): number} evaluator\n * Evaluator function that receives 3 arguments (the element, the index and\n * the array). Should return a negative number, zero, or a positive number\n * depending on whether the desired index is before, at, or after the\n * element passed to it.\n * @param {THIS=} opt_obj The object to be used as the value of 'this'\n * within evaluator.\n * @return {number} Index of the leftmost element matched by the evaluator, if\n * such exists; otherwise (-(insertion point) - 1). The insertion point is\n * the index of the first element for which the evaluator returns negative,\n * or arr.length if no such element exists. The return value is non-negative\n * iff a match is found.\n * @template THIS, VALUE\n */\ngoog.array.binarySelect = function(arr, evaluator, opt_obj) {\n return goog.array.binarySearch_(\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\n opt_obj);\n};\n\n\n/**\n * Implementation of a binary search algorithm which knows how to use both\n * comparison functions and evaluators. If an evaluator is provided, will call\n * the evaluator with the given optional data object, conforming to the\n * interface defined in binarySelect. Otherwise, if a comparison function is\n * provided, will call the comparison function against the given data object.\n *\n * This implementation purposefully does not use goog.bind or goog.partial for\n * performance reasons.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<?>} arr The array to be searched.\n * @param {function(?, ?, ?): number | function(?, ?): number} compareFn\n * Either an evaluator or a comparison function, as defined by binarySearch\n * and binarySelect above.\n * @param {boolean} isEvaluator Whether the function is an evaluator or a\n * comparison function.\n * @param {?=} opt_target If the function is a comparison function, then\n * this is the target to binary search for.\n * @param {Object=} opt_selfObj If the function is an evaluator, this is an\n * optional this object for the evaluator.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @private\n */\ngoog.array.binarySearch_ = function(\n arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\n var left = 0; // inclusive\n var right = arr.length; // exclusive\n var found;\n while (left < right) {\n var middle = left + ((right - left) >>> 1);\n var compareResult;\n if (isEvaluator) {\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\n } else {\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\n // for the type of binarySearch_, which the type system can't express yet.\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\n opt_target, arr[middle]);\n }\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // We are looking for the lowest index so we can't return immediately.\n found = !compareResult;\n }\n }\n // left is the index if found, or the insertion point otherwise.\n // Avoiding bitwise not operator, as that causes a loss in precision for array\n // indexes outside the bounds of a 32-bit signed integer. Array indexes have\n // a maximum value of 2^32-2 https://tc39.es/ecma262/#array-index\n return found ? left : -left - 1;\n};\n\n\n/**\n * Sorts the specified array into ascending order. If no opt_compareFn is\n * specified, elements are compared using\n * <code>goog.array.defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s), unlike the native sort,\n * but will give unpredictable results for heterogeneous lists of strings and\n * numbers with different numbers of digits.\n *\n * This sort is not guaranteed to be stable.\n *\n * Runtime: Same as <code>Array.prototype.sort</code>\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T,T):number=} opt_compareFn Optional comparison\n * function by which the\n * array is to be ordered. Should take 2 arguments to compare, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @template T\n */\ngoog.array.sort = function(arr, opt_compareFn) {\n // TODO(arv): Update type annotation since null is not accepted.\n arr.sort(opt_compareFn || goog.array.defaultCompare);\n};\n\n\n/**\n * Sorts the specified array into ascending order in a stable way. If no\n * opt_compareFn is specified, elements are compared using\n * <code>goog.array.defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s).\n *\n * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional\n * O(n) overhead of copying the array twice.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T, T): number=} opt_compareFn Optional comparison function\n * by which the array is to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T\n */\ngoog.array.stableSort = function(arr, opt_compareFn) {\n var compArr = new Array(arr.length);\n for (var i = 0; i < arr.length; i++) {\n compArr[i] = {index: i, value: arr[i]};\n }\n var valueCompareFn = opt_compareFn || goog.array.defaultCompare;\n function stableCompareFn(obj1, obj2) {\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\n }\n goog.array.sort(compArr, stableCompareFn);\n for (var i = 0; i < arr.length; i++) {\n arr[i] = compArr[i].value;\n }\n};\n\n\n/**\n * Sort the specified array into ascending order based on item keys\n * returned by the specified key function.\n * If no opt_compareFn is specified, the keys are compared in ascending order\n * using <code>goog.array.defaultCompare</code>.\n *\n * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>\n * and f(n) is runtime of the key function.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {function(T): K} keyFn Function taking array element and returning\n * a key used for sorting this element.\n * @param {?function(K, K): number=} opt_compareFn Optional comparison function\n * by which the keys are to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T,K\n */\ngoog.array.sortByKey = function(arr, keyFn, opt_compareFn) {\n var keyCompareFn = opt_compareFn || goog.array.defaultCompare;\n goog.array.sort(\n arr, function(a, b) { return keyCompareFn(keyFn(a), keyFn(b)); });\n};\n\n\n/**\n * Sorts an array of objects by the specified object key and compare\n * function. If no compare function is provided, the key values are\n * compared in ascending order using <code>goog.array.defaultCompare</code>.\n * This won't work for keys that get renamed by the compiler. So use\n * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.\n * @param {Array<Object>} arr An array of objects to sort.\n * @param {string} key The object key to sort by.\n * @param {Function=} opt_compareFn The function to use to compare key\n * values.\n */\ngoog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {\n goog.array.sortByKey(arr, function(obj) { return obj[key]; }, opt_compareFn);\n};\n\n\n/**\n * Tells if the array is sorted.\n * @param {!IArrayLike<T>} arr The array.\n * @param {?function(T,T):number=} opt_compareFn Function to compare the\n * array elements.\n * Should take 2 arguments to compare, and return a negative number, zero,\n * or a positive number depending on whether the first argument is less\n * than, equal to, or greater than the second.\n * @param {boolean=} opt_strict If true no equal elements are allowed.\n * @return {boolean} Whether the array is sorted.\n * @template T\n */\ngoog.array.isSorted = function(arr, opt_compareFn, opt_strict) {\n var compare = opt_compareFn || goog.array.defaultCompare;\n for (var i = 1; i < arr.length; i++) {\n var compareResult = compare(arr[i - 1], arr[i]);\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * Compares two arrays for equality. Two arrays are considered equal if they\n * have the same length and their corresponding elements are equal according to\n * the comparison function.\n *\n * @param {IArrayLike<?>} arr1 The first array to compare.\n * @param {IArrayLike<?>} arr2 The second array to compare.\n * @param {Function=} opt_equalsFn Optional comparison function.\n * Should take 2 arguments to compare, and return true if the arguments\n * are equal. Defaults to {@link goog.array.defaultCompareEquality} which\n * compares the elements using the built-in '===' operator.\n * @return {boolean} Whether the two arrays are equal.\n */\ngoog.array.equals = function(arr1, arr2, opt_equalsFn) {\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\n arr1.length != arr2.length) {\n return false;\n }\n var l = arr1.length;\n var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;\n for (var i = 0; i < l; i++) {\n if (!equalsFn(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * 3-way array compare function.\n * @param {!IArrayLike<VALUE>} arr1 The first array to\n * compare.\n * @param {!IArrayLike<VALUE>} arr2 The second array to\n * compare.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is to be ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {number} Negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template VALUE\n */\ngoog.array.compare3 = function(arr1, arr2, opt_compareFn) {\n var compare = opt_compareFn || goog.array.defaultCompare;\n var l = Math.min(arr1.length, arr2.length);\n for (var i = 0; i < l; i++) {\n var result = compare(arr1[i], arr2[i]);\n if (result != 0) {\n return result;\n }\n }\n return goog.array.defaultCompare(arr1.length, arr2.length);\n};\n\n\n/**\n * Compares its two arguments for order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is less than, equal to, or greater than the second,\n * respectively.\n * @template VALUE\n */\ngoog.array.defaultCompare = function(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n};\n\n\n/**\n * Compares its two arguments for inverse order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is greater than, equal to, or less than the second,\n * respectively.\n * @template VALUE\n */\ngoog.array.inverseDefaultCompare = function(a, b) {\n return -goog.array.defaultCompare(a, b);\n};\n\n\n/**\n * Compares its two arguments for equality, using the built in === operator.\n * @param {*} a The first object to compare.\n * @param {*} b The second object to compare.\n * @return {boolean} True if the two arguments are equal, false otherwise.\n */\ngoog.array.defaultCompareEquality = function(a, b) {\n return a === b;\n};\n\n\n/**\n * Inserts a value into a sorted array. The array is not modified if the\n * value is already present.\n * @param {IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to insert.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was inserted.\n * @template VALUE\n */\ngoog.array.binaryInsert = function(array, value, opt_compareFn) {\n var index = goog.array.binarySearch(array, value, opt_compareFn);\n if (index < 0) {\n goog.array.insertAt(array, value, -(index + 1));\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes a value from a sorted array.\n * @param {!IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to remove.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was removed.\n * @template VALUE\n */\ngoog.array.binaryRemove = function(array, value, opt_compareFn) {\n var index = goog.array.binarySearch(array, value, opt_compareFn);\n return (index >= 0) ? goog.array.removeAt(array, index) : false;\n};\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {IArrayLike<T>} array The array.\n * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index\n * and the array) and must return a valid object key (a string, number,\n * etc), or undefined, if that object should not be placed in a bucket.\n * @param {S=} opt_obj The object to be used as the value of 'this' within\n * sorter.\n * @return {!Object<!Array<T>>} An object, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template T,S\n */\ngoog.array.bucket = function(array, sorter, opt_obj) {\n var buckets = {};\n\n for (var i = 0; i < array.length; i++) {\n var value = array[i];\n var key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n var bucket = buckets[key] || (buckets[key] = []);\n bucket.push(value);\n }\n }\n\n return buckets;\n};\n\n\n/**\n * Creates a new object built from the provided array and the key-generation\n * function.\n * @param {IArrayLike<T>} arr Array or array like object over\n * which to iterate whose elements will be the values in the new object.\n * @param {?function(this:S, T, number, ?) : string} keyFunc The function to\n * call for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a string that will be used as the\n * key for the element in the new object. If the function returns the same\n * key for more than one element, the value for that key is\n * implementation-defined.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within keyFunc.\n * @return {!Object<T>} The new object.\n * @template T,S\n */\ngoog.array.toObject = function(arr, keyFunc, opt_obj) {\n var ret = {};\n goog.array.forEach(arr, function(element, index) {\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\n element;\n });\n return ret;\n};\n\n\n/**\n * Creates a range of numbers in an arithmetic progression.\n *\n * Range takes 1, 2, or 3 arguments:\n * <pre>\n * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]\n * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]\n * range(-2, -5, -1) produces [-2, -3, -4]\n * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.\n * </pre>\n *\n * @param {number} startOrEnd The starting value of the range if an end argument\n * is provided. Otherwise, the start value is 0, and this is the end value.\n * @param {number=} opt_end The optional end value of the range.\n * @param {number=} opt_step The step size between range values. Defaults to 1\n * if opt_step is undefined or 0.\n * @return {!Array<number>} An array of numbers for the requested range. May be\n * an empty array if adding the step would not converge toward the end\n * value.\n */\ngoog.array.range = function(startOrEnd, opt_end, opt_step) {\n var array = [];\n var start = 0;\n var end = startOrEnd;\n var step = opt_step || 1;\n if (opt_end !== undefined) {\n start = startOrEnd;\n end = opt_end;\n }\n\n if (step * (end - start) < 0) {\n // Sign mismatch: start + step will never reach the end value.\n return [];\n }\n\n if (step > 0) {\n for (var i = start; i < end; i += step) {\n array.push(i);\n }\n } else {\n for (var i = start; i > end; i += step) {\n array.push(i);\n }\n }\n return array;\n};\n\n\n/**\n * Returns an array consisting of the given value repeated N times.\n *\n * @param {VALUE} value The value to repeat.\n * @param {number} n The repeat count.\n * @return {!Array<VALUE>} An array with the repeated value.\n * @template VALUE\n */\ngoog.array.repeat = function(value, n) {\n var array = [];\n for (var i = 0; i < n; i++) {\n array[i] = value;\n }\n return array;\n};\n\n\n/**\n * Returns an array consisting of every argument with all arrays\n * expanded in-place recursively.\n *\n * @param {...*} var_args The values to flatten.\n * @return {!Array<?>} An array containing the flattened values.\n */\ngoog.array.flatten = function(var_args) {\n var CHUNK_SIZE = 8192;\n\n var result = [];\n for (var i = 0; i < arguments.length; i++) {\n var element = arguments[i];\n if (Array.isArray(element)) {\n for (var c = 0; c < element.length; c += CHUNK_SIZE) {\n var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);\n var recurseResult = goog.array.flatten.apply(null, chunk);\n for (var r = 0; r < recurseResult.length; r++) {\n result.push(recurseResult[r]);\n }\n }\n } else {\n result.push(element);\n }\n }\n return result;\n};\n\n\n/**\n * Rotates an array in-place. After calling this method, the element at\n * index i will be the element previously at index (i - n) %\n * array.length, for all values of i between 0 and array.length - 1,\n * inclusive.\n *\n * For example, suppose list comprises [t, a, n, k, s]. After invoking\n * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].\n *\n * @param {!Array<T>} array The array to rotate.\n * @param {number} n The amount to rotate.\n * @return {!Array<T>} The array.\n * @template T\n */\ngoog.array.rotate = function(array, n) {\n goog.asserts.assert(array.length != null);\n\n if (array.length) {\n n %= array.length;\n if (n > 0) {\n Array.prototype.unshift.apply(array, array.splice(-n, n));\n } else if (n < 0) {\n Array.prototype.push.apply(array, array.splice(0, -n));\n }\n }\n return array;\n};\n\n\n/**\n * Moves one item of an array to a new position keeping the order of the rest\n * of the items. Example use case: keeping a list of JavaScript objects\n * synchronized with the corresponding list of DOM elements after one of the\n * elements has been dragged to a new position.\n * @param {!IArrayLike<?>} arr The array to modify.\n * @param {number} fromIndex Index of the item to move between 0 and\n * {@code arr.length - 1}.\n * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.\n */\ngoog.array.moveItem = function(arr, fromIndex, toIndex) {\n goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\n goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);\n // Remove 1 item at fromIndex.\n var removedItems = Array.prototype.splice.call(arr, fromIndex, 1);\n // Insert the removed item at toIndex.\n Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);\n // We don't use goog.array.insertAt and goog.array.removeAt, because they're\n // significantly slower than splice.\n};\n\n\n/**\n * Creates a new array for which the element at position i is an array of the\n * ith element of the provided arrays. The returned array will only be as long\n * as the shortest array provided; additional values are ignored. For example,\n * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].\n *\n * This is similar to the zip() function in Python. See {@link\n * http://docs.python.org/library/functions.html#zip}\n *\n * @param {...!IArrayLike<?>} var_args Arrays to be combined.\n * @return {!Array<!Array<?>>} A new array of arrays created from\n * provided arrays.\n */\ngoog.array.zip = function(var_args) {\n if (!arguments.length) {\n return [];\n }\n var result = [];\n var minLen = arguments[0].length;\n for (var i = 1; i < arguments.length; i++) {\n if (arguments[i].length < minLen) {\n minLen = arguments[i].length;\n }\n }\n for (var i = 0; i < minLen; i++) {\n var value = [];\n for (var j = 0; j < arguments.length; j++) {\n value.push(arguments[j][i]);\n }\n result.push(value);\n }\n return result;\n};\n\n\n/**\n * Shuffles the values in the specified array using the Fisher-Yates in-place\n * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()\n * and so resets the state of that random number generator. Similarly, may reset\n * the state of any other specified random number generator.\n *\n * Runtime: O(n)\n *\n * @param {!Array<?>} arr The array to be shuffled.\n * @param {function():number=} opt_randFn Optional random function to use for\n * shuffling.\n * Takes no arguments, and returns a random number on the interval [0, 1).\n * Defaults to Math.random() using JavaScript's built-in Math library.\n */\ngoog.array.shuffle = function(arr, opt_randFn) {\n var randFn = opt_randFn || Math.random;\n\n for (var i = arr.length - 1; i > 0; i--) {\n // Choose a random array index in [0, i] (inclusive with i).\n var j = Math.floor(randFn() * (i + 1));\n\n var tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n};\n\n\n/**\n * Returns a new array of elements from arr, based on the indexes of elements\n * provided by index_arr. For example, the result of index copying\n * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].\n *\n * @param {!IArrayLike<T>} arr The array to get a indexed copy from.\n * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.\n * @return {!Array<T>} A new array of elements from arr in index_arr order.\n * @template T\n */\ngoog.array.copyByIndex = function(arr, index_arr) {\n var result = [];\n goog.array.forEach(index_arr, function(index) { result.push(arr[index]); });\n return result;\n};\n\n\n/**\n * Maps each element of the input array into zero or more elements of the output\n * array.\n *\n * @param {!IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function\n * to call for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return an array. The result will be\n * used to extend a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the concatenation of all arrays\n * returned from f.\n * @template THIS, VALUE, RESULT\n */\ngoog.array.concatMap = function(arr, f, opt_obj) {\n return goog.array.concat.apply([], goog.array.map(arr, f, opt_obj));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview String functions called from Closure packages that couldn't\n * depend on each other. Outside Closure, use goog.string function which\n * delegate to these.\n */\n\n\ngoog.provide('goog.string.internal');\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n * @see goog.string.startsWith\n */\ngoog.string.internal.startsWith = function(str, prefix) {\n return str.lastIndexOf(prefix, 0) == 0;\n};\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n * @see goog.string.endsWith\n */\ngoog.string.internal.endsWith = function(str, suffix) {\n const l = str.length - suffix.length;\n return l >= 0 && str.indexOf(suffix, l) == l;\n};\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveStartsWith\n */\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\n return goog.string.internal.caseInsensitiveCompare(\n prefix, str.substr(0, prefix.length)) == 0;\n};\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveEndsWith\n */\ngoog.string.internal.caseInsensitiveEndsWith = function(str, suffix) {\n return (\n goog.string.internal.caseInsensitiveCompare(\n suffix, str.substr(str.length - suffix.length, suffix.length)) == 0);\n};\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n * @see goog.string.caseInsensitiveEquals\n */\ngoog.string.internal.caseInsensitiveEquals = function(str1, str2) {\n return str1.toLowerCase() == str2.toLowerCase();\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @see goog.string.isEmptyOrWhitespace\n */\ngoog.string.internal.isEmptyOrWhitespace = function(str) {\n // testing length == 0 first is actually slower in all browsers (about the\n // same in Opera).\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return /^[\\s\\xa0]*$/.test(str);\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.internal.trim =\n (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) {\n return str.trim();\n } : function(str) {\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s\n // character class (as required by section 7.2 of the ECMAScript spec),\n // we explicitly include it in the regexp to enforce consistent\n // cross-browser behavior.\n // NOTE: We don't use String#replace because it might have side effects\n // causing this function to not compile to 0 bytes.\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(str)[1];\n };\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n * @see goog.string.caseInsensitiveCompare\n */\ngoog.string.internal.caseInsensitiveCompare = function(str1, str2) {\n const test1 = String(str1).toLowerCase();\n const test2 = String(str2).toLowerCase();\n\n if (test1 < test2) {\n return -1;\n } else if (test1 == test2) {\n return 0;\n } else {\n return 1;\n }\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n * @see goog.string.newLineToBr\n */\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\n return str.replace(/(\\r\\n|\\r|\\n)/g, opt_xml ? '<br />' : '<br>');\n};\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars\n * @return {string} An escaped copy of `str`.\n * @see goog.string.htmlEscape\n */\ngoog.string.internal.htmlEscape = function(\n str, opt_isLikelyToContainHtmlChars) {\n if (opt_isLikelyToContainHtmlChars) {\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;')\n .replace(goog.string.internal.LT_RE_, '&lt;')\n .replace(goog.string.internal.GT_RE_, '&gt;')\n .replace(goog.string.internal.QUOT_RE_, '&quot;')\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;')\n .replace(goog.string.internal.NULL_RE_, '&#0;');\n return str;\n\n } else {\n // quick test helps in the case when there are no chars to replace, in\n // worst case this makes barely a difference to the time taken\n if (!goog.string.internal.ALL_RE_.test(str)) return str;\n\n // str.indexOf is faster than regex.test in this case\n if (str.indexOf('&') != -1) {\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;');\n }\n if (str.indexOf('<') != -1) {\n str = str.replace(goog.string.internal.LT_RE_, '&lt;');\n }\n if (str.indexOf('>') != -1) {\n str = str.replace(goog.string.internal.GT_RE_, '&gt;');\n }\n if (str.indexOf('\"') != -1) {\n str = str.replace(goog.string.internal.QUOT_RE_, '&quot;');\n }\n if (str.indexOf('\\'') != -1) {\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;');\n }\n if (str.indexOf('\\x00') != -1) {\n str = str.replace(goog.string.internal.NULL_RE_, '&#0;');\n }\n return str;\n }\n};\n\n\n/**\n * Regular expression that matches an ampersand, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.AMP_RE_ = /&/g;\n\n\n/**\n * Regular expression that matches a less than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.LT_RE_ = /</g;\n\n\n/**\n * Regular expression that matches a greater than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.GT_RE_ = />/g;\n\n\n/**\n * Regular expression that matches a double quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.QUOT_RE_ = /\"/g;\n\n\n/**\n * Regular expression that matches a single quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.SINGLE_QUOTE_RE_ = /'/g;\n\n\n/**\n * Regular expression that matches null character, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.NULL_RE_ = /\\x00/g;\n\n\n/**\n * Regular expression that matches any character that needs to be escaped.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.ALL_RE_ = /[\\x00&<>\"']/;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n * @see goog.string.whitespaceEscape\n */\ngoog.string.internal.whitespaceEscape = function(str, opt_xml) {\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.internal.newLineToBr(\n str.replace(/ /g, ' &#160;'), opt_xml);\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.contains\n */\ngoog.string.internal.contains = function(str, subString) {\n return str.indexOf(subString) != -1;\n};\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.caseInsensitiveContains\n */\ngoog.string.internal.caseInsensitiveContains = function(str, subString) {\n return goog.string.internal.contains(\n str.toLowerCase(), subString.toLowerCase());\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n * @see goog.string.compareVersions\n */\ngoog.string.internal.compareVersions = function(version1, version2) {\n let order = 0;\n // Trim leading and trailing whitespace and split the versions into\n // subversions.\n const v1Subs = goog.string.internal.trim(String(version1)).split('.');\n const v2Subs = goog.string.internal.trim(String(version2)).split('.');\n const subCount = Math.max(v1Subs.length, v2Subs.length);\n\n // Iterate over the subversions, as long as they appear to be equivalent.\n for (let subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\n let v1Sub = v1Subs[subIdx] || '';\n let v2Sub = v2Subs[subIdx] || '';\n\n do {\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\n // Two different RegExp objects are use to make it clear the code\n // is side-effect free\n const v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\n const v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\n // Break if there are no more matches.\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\n break;\n }\n\n // Parse the numeric part of the subversion. A missing number is\n // equivalent to 0.\n const v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\n const v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\n\n // Compare the subversion components. The number has the highest\n // precedence. Next, if the numbers are equal, a subversion without any\n // qualifier is always higher than a subversion with any qualifier. Next,\n // the qualifiers are compared as strings.\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\n goog.string.internal.compareElements_(\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\n // Stop as soon as an inequality is discovered.\n\n v1Sub = v1Comp[3];\n v2Sub = v2Comp[3];\n } while (order == 0);\n }\n\n return order;\n};\n\n\n/**\n * Compares elements of a version number.\n *\n * @param {string|number|boolean} left An element from a version number.\n * @param {string|number|boolean} right An element from a version number.\n *\n * @return {number} 1 if `left` is higher.\n * 0 if arguments are equal.\n * -1 if `right` is higher.\n * @private\n */\ngoog.string.internal.compareElements_ = function(left, right) {\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n }\n return 0;\n};\n","// Copyright 2013 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 Utilities used by goog.labs.userAgent tools. These functions\n * should not be used outside of goog.labs.userAgent.*.\n *\n */\n\ngoog.provide('goog.labs.userAgent.util');\n\ngoog.require('goog.string.internal');\n\n\n/**\n * Gets the native userAgent string from navigator if it exists.\n * If navigator or navigator.userAgent string is missing, returns an empty\n * string.\n * @return {string}\n * @private\n */\ngoog.labs.userAgent.util.getNativeUserAgentString_ = function() {\n var navigator = goog.labs.userAgent.util.getNavigator_();\n if (navigator) {\n var userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n};\n\n\n/**\n * Getter for the native navigator.\n * This is a separate function so it can be stubbed out in testing.\n * @return {Navigator}\n * @private\n */\ngoog.labs.userAgent.util.getNavigator_ = function() {\n return goog.global.navigator;\n};\n\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgent but use a specified value for detection instead.\n * @private {string}\n */\ngoog.labs.userAgent.util.userAgent_ =\n goog.labs.userAgent.util.getNativeUserAgentString_();\n\n\n/**\n * Applications may override browser detection on the built in\n * navigator.userAgent object by setting this string. Set to null to use the\n * browser object instead.\n * @param {?string=} opt_userAgent The User-Agent override.\n */\ngoog.labs.userAgent.util.setUserAgent = function(opt_userAgent) {\n goog.labs.userAgent.util.userAgent_ =\n opt_userAgent || goog.labs.userAgent.util.getNativeUserAgentString_();\n};\n\n\n/**\n * @return {string} The user agent string.\n */\ngoog.labs.userAgent.util.getUserAgent = function() {\n return goog.labs.userAgent.util.userAgent_;\n};\n\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string.\n */\ngoog.labs.userAgent.util.matchUserAgent = function(str) {\n var userAgent = goog.labs.userAgent.util.getUserAgent();\n return goog.string.internal.contains(userAgent, str);\n};\n\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string, ignoring\n * case.\n */\ngoog.labs.userAgent.util.matchUserAgentIgnoreCase = function(str) {\n var userAgent = goog.labs.userAgent.util.getUserAgent();\n return goog.string.internal.caseInsensitiveContains(userAgent, str);\n};\n\n\n/**\n * Parses the user agent into tuples for each section.\n * @param {string} userAgent\n * @return {!Array<!Array<string>>} Tuples of key, version, and the contents\n * of the parenthetical.\n */\ngoog.labs.userAgent.util.extractVersionTuples = function(userAgent) {\n // Matches each section of a user agent string.\n // Example UA:\n // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)\n // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\n // This has three version tuples: Mozilla, AppleWebKit, and Mobile.\n\n var versionRegExp = new RegExp(\n // Key. Note that a key may have a space.\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\n '(\\\\w[\\\\w ]+)' +\n\n '/' + // slash\n '([^\\\\s]+)' + // version (i.e. '5.0b')\n '\\\\s*' + // whitespace\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\n 'g');\n\n var data = [];\n var match;\n\n // Iterate and collect the version tuples. Each iteration will be the\n // next regex match.\n while (match = versionRegExp.exec(userAgent)) {\n data.push([\n match[1], // key\n match[2], // value\n // || undefined as this is not undefined in IE7 and IE8\n match[3] || undefined // info\n ]);\n }\n\n return data;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating objects/maps/hashes.\n */\n\ngoog.provide('goog.object');\n\n\n/**\n * Whether two values are not observably distinguishable. This\n * correctly detects that 0 is not the same as -0 and two NaNs are\n * practically equivalent.\n *\n * The implementation is as suggested by harmony:egal proposal.\n *\n * @param {*} v The first value to compare.\n * @param {*} v2 The second value to compare.\n * @return {boolean} Whether two values are not observably distinguishable.\n * @see http://wiki.ecmascript.org/doku.php?id=harmony:egal\n */\ngoog.object.is = function(v, v2) {\n if (v === v2) {\n // 0 === -0, but they are not identical.\n // We need the cast because the compiler requires that v2 is a\n // number (although 1/v2 works with non-number). We cast to ? to\n // stop the compiler from type-checking this statement.\n return v !== 0 || 1 / v === 1 / /** @type {?} */ (v2);\n }\n\n // NaN is non-reflexive: NaN !== NaN, although they are identical.\n return v !== v && v2 !== v2;\n};\n\n\n/**\n * Calls a function for each element in an object/map/hash.\n *\n * @param {Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,Object<K,V>):?} f The function to call\n * for every element. This function takes 3 arguments (the value, the\n * key and the object) and the return value is ignored.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @template T,K,V\n */\ngoog.object.forEach = function(obj, f, opt_obj) {\n for (const key in obj) {\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n};\n\n\n/**\n * Calls a function for each element in an object/map/hash. If that call returns\n * true, adds the element to a new object.\n *\n * @param {Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call\n * for every element. This\n * function takes 3 arguments (the value, the key and the object)\n * and should return a boolean. If the return value is true the\n * element is added to the result object. If it is false the\n * element is not included.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,V>} a new object in which only elements that passed the\n * test are present.\n * @template T,K,V\n */\ngoog.object.filter = function(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n res[key] = obj[key];\n }\n }\n return res;\n};\n\n\n/**\n * For every element in an object/map/hash calls a function and inserts the\n * result into a new object.\n *\n * @param {Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,Object<K,V>):R} f The function to call\n * for every element. This function\n * takes 3 arguments (the value, the key and the object)\n * and should return something. The result will be inserted\n * into a new object.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,R>} a new object with the results from f.\n * @template T,K,V,R\n */\ngoog.object.map = function(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n return res;\n};\n\n\n/**\n * Calls a function for each element in an object/map/hash. If any\n * call returns true, returns true (without checking the rest). If\n * all calls return false, returns false.\n *\n * @param {Object<K,V>} obj The object to check.\n * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to\n * call for every element. This function\n * takes 3 arguments (the value, the key and the object) and should\n * return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} true if any element passes the test.\n * @template T,K,V\n */\ngoog.object.some = function(obj, f, opt_obj) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Calls a function for each element in an object/map/hash. If\n * all calls return true, returns true. If any call returns false, returns\n * false at this point and does not continue to check the remaining elements.\n *\n * @param {Object<K,V>} obj The object to check.\n * @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to\n * call for every element. This function\n * takes 3 arguments (the value, the key and the object) and should\n * return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} false if any element fails the test.\n * @template T,K,V\n */\ngoog.object.every = function(obj, f, opt_obj) {\n for (const key in obj) {\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * Returns the number of key-value pairs in the object map.\n *\n * @param {Object} obj The object for which to get the number of key-value\n * pairs.\n * @return {number} The number of key-value pairs in the object map.\n */\ngoog.object.getCount = function(obj) {\n let rv = 0;\n for (const key in obj) {\n rv++;\n }\n return rv;\n};\n\n\n/**\n * Returns one key from the object map, if any exists.\n * For map literals the returned key will be the first one in most of the\n * browsers (a know exception is Konqueror).\n *\n * @param {Object} obj The object to pick a key from.\n * @return {string|undefined} The key or undefined if the object is empty.\n */\ngoog.object.getAnyKey = function(obj) {\n for (const key in obj) {\n return key;\n }\n};\n\n\n/**\n * Returns one value from the object map, if any exists.\n * For map literals the returned value will be the first one in most of the\n * browsers (a know exception is Konqueror).\n *\n * @param {Object<K,V>} obj The object to pick a value from.\n * @return {V|undefined} The value or undefined if the object is empty.\n * @template K,V\n */\ngoog.object.getAnyValue = function(obj) {\n for (const key in obj) {\n return obj[key];\n }\n};\n\n\n/**\n * Whether the object/hash/map contains the given object as a value.\n * An alias for goog.object.containsValue(obj, val).\n *\n * @param {Object<K,V>} obj The object in which to look for val.\n * @param {V} val The object for which to check.\n * @return {boolean} true if val is present.\n * @template K,V\n */\ngoog.object.contains = function(obj, val) {\n return goog.object.containsValue(obj, val);\n};\n\n\n/**\n * Returns the values of the object/map/hash.\n *\n * @param {Object<K,V>} obj The object from which to get the values.\n * @return {!Array<V>} The values in the object/map/hash.\n * @template K,V\n */\ngoog.object.getValues = function(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = obj[key];\n }\n return res;\n};\n\n\n/**\n * Returns the keys of the object/map/hash.\n *\n * @param {Object} obj The object from which to get the keys.\n * @return {!Array<string>} Array of property keys.\n */\ngoog.object.getKeys = function(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = key;\n }\n return res;\n};\n\n\n/**\n * Get a value from an object multiple levels deep. This is useful for\n * pulling values from deeply nested objects, such as JSON responses.\n * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)\n *\n * @param {!Object} obj An object to get the value from. Can be array-like.\n * @param {...(string|number|!IArrayLike<number|string>)}\n * var_args A number of keys\n * (as strings, or numbers, for array-like objects). Can also be\n * specified as a single array of keys.\n * @return {*} The resulting value. If, at any point, the value for a key\n * in the current object is null or undefined, returns undefined.\n */\ngoog.object.getValueByKeys = function(obj, var_args) {\n const isArrayLike = goog.isArrayLike(var_args);\n const keys = isArrayLike ?\n /** @type {!IArrayLike<number|string>} */ (var_args) :\n arguments;\n\n // Start with the 2nd parameter for the variable parameters syntax.\n for (let i = isArrayLike ? 0 : 1; i < keys.length; i++) {\n if (obj == null) return undefined;\n obj = obj[keys[i]];\n }\n\n return obj;\n};\n\n\n/**\n * Whether the object/map/hash contains the given key.\n *\n * @param {Object} obj The object in which to look for key.\n * @param {?} key The key for which to check.\n * @return {boolean} true If the map contains the key.\n */\ngoog.object.containsKey = function(obj, key) {\n return obj !== null && key in obj;\n};\n\n\n/**\n * Whether the object/map/hash contains the given value. This is O(n).\n *\n * @param {Object<K,V>} obj The object in which to look for val.\n * @param {V} val The value for which to check.\n * @return {boolean} true If the map contains the value.\n * @template K,V\n */\ngoog.object.containsValue = function(obj, val) {\n for (const key in obj) {\n if (obj[key] == val) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its key.\n * @param {Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,Object<K,V>):boolean} f The\n * function to call for every element. Takes 3 arguments (the value,\n * the key and the object) and should return a boolean.\n * @param {T=} opt_this An optional \"this\" context for the function.\n * @return {string|undefined} The key of an element for which the function\n * returns true or undefined if no such element is found.\n * @template T,K,V\n */\ngoog.object.findKey = function(obj, f, opt_this) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_this), obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n};\n\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its value.\n * @param {Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,Object<K,V>):boolean} f The function\n * to call for every element. Takes 3 arguments (the value, the key\n * and the object) and should return a boolean.\n * @param {T=} opt_this An optional \"this\" context for the function.\n * @return {V} The value of an element for which the function returns true or\n * undefined if no such element is found.\n * @template T,K,V\n */\ngoog.object.findValue = function(obj, f, opt_this) {\n const key = goog.object.findKey(obj, f, opt_this);\n return key && obj[key];\n};\n\n\n/**\n * Whether the object/map/hash is empty.\n *\n * @param {Object} obj The object to test.\n * @return {boolean} true if obj is empty.\n */\ngoog.object.isEmpty = function(obj) {\n for (const key in obj) {\n return false;\n }\n return true;\n};\n\n\n/**\n * Removes all key value pairs from the object/map/hash.\n *\n * @param {Object} obj The object to clear.\n */\ngoog.object.clear = function(obj) {\n for (const i in obj) {\n delete obj[i];\n }\n};\n\n\n/**\n * Removes a key-value pair based on the key.\n *\n * @param {Object} obj The object from which to remove the key.\n * @param {?} key The key to remove.\n * @return {boolean} Whether an element was removed.\n */\ngoog.object.remove = function(obj, key) {\n let rv;\n if (rv = key in /** @type {!Object} */ (obj)) {\n delete obj[key];\n }\n return rv;\n};\n\n\n/**\n * Adds a key-value pair to the object. Throws an exception if the key is\n * already in use. Use set if you want to change an existing pair.\n *\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} val The value to add.\n * @template K,V\n */\ngoog.object.add = function(obj, key, val) {\n if (obj !== null && key in obj) {\n throw new Error('The object already contains the key \"' + key + '\"');\n }\n goog.object.set(obj, key, val);\n};\n\n\n/**\n * Returns the value for the given key.\n *\n * @param {Object<K,V>} obj The object from which to get the value.\n * @param {string} key The key for which to get the value.\n * @param {R=} opt_val The value to return if no item is found for the given\n * key (default is undefined).\n * @return {V|R|undefined} The value for the given key.\n * @template K,V,R\n */\ngoog.object.get = function(obj, key, opt_val) {\n if (obj !== null && key in obj) {\n return obj[key];\n }\n return opt_val;\n};\n\n\n/**\n * Adds a key-value pair to the object/map/hash.\n *\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add.\n * @template K,V\n */\ngoog.object.set = function(obj, key, value) {\n obj[key] = value;\n};\n\n\n/**\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\n *\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\ngoog.object.setIfUndefined = function(obj, key, value) {\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\n};\n\n\n/**\n * Sets a key and value to an object if the key is not set. The value will be\n * the return value of the given function. If the key already exists, the\n * object will not be changed and the function will not be called (the function\n * will be lazily evaluated -- only called if necessary).\n *\n * This function is particularly useful when used with an `Object` which is\n * acting as a cache.\n *\n * @param {!Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {function():V} f The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\ngoog.object.setWithReturnValueIfNotSet = function(obj, key, f) {\n if (key in obj) {\n return obj[key];\n }\n\n const val = f();\n obj[key] = val;\n return val;\n};\n\n\n/**\n * Compares two objects for equality using === on the values.\n *\n * @param {!Object<K,V>} a\n * @param {!Object<K,V>} b\n * @return {boolean}\n * @template K,V\n */\ngoog.object.equals = function(a, b) {\n for (const k in a) {\n if (!(k in b) || a[k] !== b[k]) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * Returns a shallow clone of the object.\n *\n * @param {Object<K,V>} obj Object to clone.\n * @return {!Object<K,V>} Clone of the input object.\n * @template K,V\n */\ngoog.object.clone = function(obj) {\n // We cannot use the prototype trick because a lot of methods depend on where\n // the actual key is set.\n\n const res = {};\n for (const key in obj) {\n res[key] = obj[key];\n }\n return res;\n // We could also use goog.mixin but I wanted this to be independent from that.\n};\n\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n *\n * WARNINGS:\n * <code>goog.object.unsafeClone</code> does not detect reference loops. Objects\n * that refer to themselves will cause infinite recursion.\n *\n * <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and\n * copies UIDs created by <code>getUid</code> into cloned results.\n *\n * @param {T} obj The value to clone.\n * @return {T} A clone of the input value.\n * @template T\n */\ngoog.object.unsafeClone = function(obj) {\n const type = goog.typeOf(obj);\n if (type == 'object' || type == 'array') {\n if (goog.isFunction(obj.clone)) {\n return obj.clone();\n }\n const clone = type == 'array' ? [] : {};\n for (const key in obj) {\n clone[key] = goog.object.unsafeClone(obj[key]);\n }\n return clone;\n }\n\n return obj;\n};\n\n\n/**\n * Returns a new object in which all the keys and values are interchanged\n * (keys become values and values become keys). If multiple keys map to the\n * same value, the chosen transposed value is implementation-dependent.\n *\n * @param {Object} obj The object to transpose.\n * @return {!Object} The transposed object.\n */\ngoog.object.transpose = function(obj) {\n const transposed = {};\n for (const key in obj) {\n transposed[obj[key]] = key;\n }\n return transposed;\n};\n\n\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {Array<string>}\n * @private\n */\ngoog.object.PROTOTYPE_FIELDS_ = [\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\n 'toLocaleString', 'toString', 'valueOf'\n];\n\n\n/**\n * Extends an object with another object.\n * This operates 'in-place'; it does not create a new Object.\n *\n * Example:\n * var o = {};\n * goog.object.extend(o, {a: 0, b: 1});\n * o; // {a: 0, b: 1}\n * goog.object.extend(o, {b: 2, c: 3});\n * o; // {a: 0, b: 2, c: 3}\n *\n * @param {Object} target The object to modify. Existing properties will be\n * overwritten if they are also present in one of the objects in\n * `var_args`.\n * @param {...(Object|null|undefined)} var_args The objects from which values\n * will be copied.\n * @deprecated Prefer Object.assign\n */\ngoog.object.extend = function(target, var_args) {\n let key;\n let source;\n for (let i = 1; i < arguments.length; i++) {\n source = arguments[i];\n for (key in source) {\n target[key] = source[key];\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n\n for (let j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {\n key = goog.object.PROTOTYPE_FIELDS_[j];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n};\n\n\n/**\n * Creates a new object built from the key-value pairs provided as arguments.\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise even arguments are used as\n * the property names and odd arguments are used as the property values.\n * @return {!Object} The new object.\n * @throws {Error} If there are uneven number of arguments or there is only one\n * non array argument.\n */\ngoog.object.create = function(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return goog.object.create.apply(null, arguments[0]);\n }\n\n if (argLength % 2) {\n throw new Error('Uneven number of arguments');\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i += 2) {\n rv[arguments[i]] = arguments[i + 1];\n }\n return rv;\n};\n\n\n/**\n * Creates a new object where the property names come from the arguments but\n * the value is always set to true\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise the arguments are used\n * as the property names.\n * @return {!Object} The new object.\n */\ngoog.object.createSet = function(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return goog.object.createSet.apply(null, arguments[0]);\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i++) {\n rv[arguments[i]] = true;\n }\n return rv;\n};\n\n\n/**\n * Creates an immutable view of the underlying object, if the browser\n * supports immutable objects.\n *\n * In default mode, writes to this view will fail silently. In strict mode,\n * they will throw an error.\n *\n * @param {!Object<K,V>} obj An object.\n * @return {!Object<K,V>} An immutable view of that object, or the\n * original object if this browser does not support immutables.\n * @template K,V\n */\ngoog.object.createImmutableView = function(obj) {\n let result = obj;\n if (Object.isFrozen && !Object.isFrozen(obj)) {\n result = Object.create(obj);\n Object.freeze(result);\n }\n return result;\n};\n\n\n/**\n * @param {!Object} obj An object.\n * @return {boolean} Whether this is an immutable view of the object.\n */\ngoog.object.isImmutableView = function(obj) {\n return !!Object.isFrozen && Object.isFrozen(obj);\n};\n\n\n/**\n * Get all properties names on a given Object regardless of enumerability.\n *\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\n * `Object.getPrototypeOf` then this is equivalent to using\n * `goog.object.getKeys`\n *\n * @param {?Object} obj The object to get the properties of.\n * @param {boolean=} opt_includeObjectPrototype Whether properties defined on\n * `Object.prototype` should be included in the result.\n * @param {boolean=} opt_includeFunctionPrototype Whether properties defined on\n * `Function.prototype` should be included in the result.\n * @return {!Array<string>}\n * @public\n */\ngoog.object.getAllPropertyNames = function(\n obj, opt_includeObjectPrototype, opt_includeFunctionPrototype) {\n if (!obj) {\n return [];\n }\n\n // Naively use a for..in loop to get the property names if the browser doesn't\n // support any other APIs for getting it.\n if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\n return goog.object.getKeys(obj);\n }\n\n const visitedSet = {};\n\n // Traverse the prototype chain and add all properties to the visited set.\n let proto = obj;\n while (proto &&\n (proto !== Object.prototype || !!opt_includeObjectPrototype) &&\n (proto !== Function.prototype || !!opt_includeFunctionPrototype)) {\n const names = Object.getOwnPropertyNames(proto);\n for (let i = 0; i < names.length; i++) {\n visitedSet[names[i]] = true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n\n return goog.object.getKeys(visitedSet);\n};\n\n\n/**\n * Given a ES5 or ES6 class reference, return its super class / super\n * constructor.\n *\n * This should be used in rare cases where you need to walk up the inheritance\n * tree (this is generally a bad idea). But this work with ES5 and ES6 classes,\n * unlike relying on the superClass_ property.\n *\n * Note: To start walking up the hierarchy from an instance call this with its\n * `constructor` property; e.g. `getSuperClass(instance.constructor)`.\n *\n * @param {function(new: ?)} constructor\n * @return {?Object}\n */\ngoog.object.getSuperClass = function(constructor) {\n var proto = Object.getPrototypeOf(constructor.prototype);\n return proto && proto.constructor;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.dom.asserts');\n\ngoog.require('goog.asserts');\n\n/**\n * @fileoverview Custom assertions to ensure that an element has the appropriate\n * type.\n *\n * Using a goog.dom.safe wrapper on an object on the incorrect type (via an\n * incorrect static type cast) can result in security bugs: For instance,\n * g.d.s.setAnchorHref ensures that the URL assigned to the .href attribute\n * satisfies the SafeUrl contract, i.e., is safe to dereference as a hyperlink.\n * However, the value assigned to a HTMLLinkElement's .href property requires\n * the stronger TrustedResourceUrl contract, since it can refer to a stylesheet.\n * Thus, using g.d.s.setAnchorHref on an (incorrectly statically typed) object\n * of type HTMLLinkElement can result in a security vulnerability.\n * Assertions of the correct run-time type help prevent such incorrect use.\n *\n * In some cases, code using the DOM API is tested using mock objects (e.g., a\n * plain object such as {'href': url} instead of an actual Location object).\n * To allow such mocking, the assertions permit objects of types that are not\n * relevant DOM API objects at all (for instance, not Element or Location).\n *\n * Note that instanceof checks don't work straightforwardly in older versions of\n * IE, or across frames (see,\n * http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object,\n * http://stackoverflow.com/questions/26248599/instanceof-htmlelement-in-iframe-is-not-element-or-object).\n *\n * Hence, these assertions may pass vacuously in such scenarios. The resulting\n * risk of security bugs is limited by the following factors:\n * - A bug can only arise in scenarios involving incorrect static typing (the\n * wrapper methods are statically typed to demand objects of the appropriate,\n * precise type).\n * - Typically, code is tested and exercised in multiple browsers.\n */\n\n/**\n * Asserts that a given object is a Location.\n *\n * To permit this assertion to pass in the context of tests where DOM APIs might\n * be mocked, also accepts any other type except for subtypes of {!Element}.\n * This is to ensure that, for instance, HTMLLinkElement is not being used in\n * place of a Location, since this could result in security bugs due to stronger\n * contracts required for assignments to the href property of the latter.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!Location}\n */\ngoog.dom.asserts.assertIsLocation = function(o) {\n if (goog.asserts.ENABLE_ASSERTS) {\n var win = goog.dom.asserts.getWindow_(o);\n if (win) {\n if (!o || (!(o instanceof win.Location) && o instanceof win.Element)) {\n goog.asserts.fail(\n 'Argument is not a Location (or a non-Element mock); got: %s',\n goog.dom.asserts.debugStringForType_(o));\n }\n }\n }\n return /** @type {!Location} */ (o);\n};\n\n\n/**\n * Asserts that a given object is either the given subtype of Element\n * or a non-Element, non-Location Mock.\n *\n * To permit this assertion to pass in the context of tests where DOM\n * APIs might be mocked, also accepts any other type except for\n * subtypes of {!Element}. This is to ensure that, for instance,\n * HTMLScriptElement is not being used in place of a HTMLImageElement,\n * since this could result in security bugs due to stronger contracts\n * required for assignments to the src property of the latter.\n *\n * The DOM type is looked up in the window the object belongs to. In\n * some contexts, this might not be possible (e.g. when running tests\n * outside a browser, cross-domain lookup). In this case, the\n * assertions are skipped.\n *\n * @param {?Object} o The object whose type to assert.\n * @param {string} typename The name of the DOM type.\n * @return {!Element} The object.\n * @private\n */\n// TODO(bangert): Make an analog of goog.dom.TagName to correctly handle casts?\ngoog.dom.asserts.assertIsElementType_ = function(o, typename) {\n if (goog.asserts.ENABLE_ASSERTS) {\n var win = goog.dom.asserts.getWindow_(o);\n if (win && typeof win[typename] != 'undefined') {\n if (!o ||\n (!(o instanceof win[typename]) &&\n (o instanceof win.Location || o instanceof win.Element))) {\n goog.asserts.fail(\n 'Argument is not a %s (or a non-Element, non-Location mock); ' +\n 'got: %s',\n typename, goog.dom.asserts.debugStringForType_(o));\n }\n }\n }\n return /** @type {!Element} */ (o);\n};\n\n/**\n * Asserts that a given object is a HTMLAnchorElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not of type Location nor a subtype\n * of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLAnchorElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlAnchorElement instead.\n */\ngoog.dom.asserts.assertIsHTMLAnchorElement = function(o) {\n return /** @type {!HTMLAnchorElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLAnchorElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLButtonElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLButtonElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlButtonElement instead.\n */\ngoog.dom.asserts.assertIsHTMLButtonElement = function(o) {\n return /** @type {!HTMLButtonElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLButtonElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLLinkElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLLinkElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlLinkElement instead.\n */\ngoog.dom.asserts.assertIsHTMLLinkElement = function(o) {\n return /** @type {!HTMLLinkElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLLinkElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLImageElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLImageElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlImageElement instead.\n */\ngoog.dom.asserts.assertIsHTMLImageElement = function(o) {\n return /** @type {!HTMLImageElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLImageElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLAudioElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLAudioElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlAudioElement instead.\n */\ngoog.dom.asserts.assertIsHTMLAudioElement = function(o) {\n return /** @type {!HTMLAudioElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLAudioElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLVideoElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLVideoElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlVideoElement instead.\n */\ngoog.dom.asserts.assertIsHTMLVideoElement = function(o) {\n return /** @type {!HTMLVideoElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLVideoElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLInputElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLInputElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlInputElement instead.\n */\ngoog.dom.asserts.assertIsHTMLInputElement = function(o) {\n return /** @type {!HTMLInputElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLInputElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLTextAreaElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLTextAreaElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlTextAreaElement instead.\n */\ngoog.dom.asserts.assertIsHTMLTextAreaElement = function(o) {\n return /** @type {!HTMLTextAreaElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLTextAreaElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLCanvasElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLCanvasElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlCanvasElement instead.\n */\ngoog.dom.asserts.assertIsHTMLCanvasElement = function(o) {\n return /** @type {!HTMLCanvasElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLCanvasElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLEmbedElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLEmbedElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlEmbedElement instead.\n */\ngoog.dom.asserts.assertIsHTMLEmbedElement = function(o) {\n return /** @type {!HTMLEmbedElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLEmbedElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLFormElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLFormElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlFormElement instead.\n */\ngoog.dom.asserts.assertIsHTMLFormElement = function(o) {\n return /** @type {!HTMLFormElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLFormElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLFrameElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLFrameElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlFrameElement instead.\n */\ngoog.dom.asserts.assertIsHTMLFrameElement = function(o) {\n return /** @type {!HTMLFrameElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLFrameElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLIFrameElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLIFrameElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlIFrameElement instead.\n */\ngoog.dom.asserts.assertIsHTMLIFrameElement = function(o) {\n return /** @type {!HTMLIFrameElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLIFrameElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLObjectElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLObjectElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlObjectElement instead.\n */\ngoog.dom.asserts.assertIsHTMLObjectElement = function(o) {\n return /** @type {!HTMLObjectElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLObjectElement'));\n};\n\n/**\n * Asserts that a given object is a HTMLScriptElement.\n *\n * To permit this assertion to pass in the context of tests where elements might\n * be mocked, also accepts objects that are not a subtype of Element.\n *\n * @param {?Object} o The object whose type to assert.\n * @return {!HTMLScriptElement}\n * @deprecated Use goog.asserts.dom.assertIsHtmlScriptElement instead.\n */\ngoog.dom.asserts.assertIsHTMLScriptElement = function(o) {\n return /** @type {!HTMLScriptElement} */ (\n goog.dom.asserts.assertIsElementType_(o, 'HTMLScriptElement'));\n};\n\n/**\n * Returns a string representation of a value's type.\n *\n * @param {*} value An object, or primitive.\n * @return {string} The best display name for the value.\n * @private\n */\ngoog.dom.asserts.debugStringForType_ = function(value) {\n if (goog.isObject(value)) {\n try {\n return /** @type {string|undefined} */ (value.constructor.displayName) ||\n value.constructor.name || Object.prototype.toString.call(value);\n } catch (e) {\n return '<object could not be stringified>';\n }\n } else {\n return value === undefined ? 'undefined' :\n value === null ? 'null' : typeof value;\n }\n};\n\n/**\n * Gets window of element.\n * @param {?Object} o\n * @return {?Window}\n * @private\n * @suppress {strictMissingProperties} ownerDocument not defined on Object\n */\ngoog.dom.asserts.getWindow_ = function(o) {\n try {\n var doc = o && o.ownerDocument;\n // This can throw “Blocked a frame with origin \"chrome-extension://...\" from\n // accessing a cross-origin frame” in Chrome extension.\n var win =\n doc && /** @type {?Window} */ (doc.defaultView || doc.parentWindow);\n win = win || /** @type {!Window} */ (goog.global);\n // This can throw “Permission denied to access property \"Element\" on\n // cross-origin object”.\n if (win.Element && win.Location) {\n return win;\n }\n } catch (ex) {\n }\n return null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.string.Const');\n\ngoog.require('goog.asserts');\ngoog.require('goog.string.TypedString');\n\n\n\n/**\n * Wrapper for compile-time-constant strings.\n *\n * Const is a wrapper for strings that can only be created from program\n * constants (i.e., string literals). This property relies on a custom Closure\n * compiler check that `goog.string.Const.from` is only invoked on\n * compile-time-constant expressions.\n *\n * Const is useful in APIs whose correct and secure use requires that certain\n * arguments are not attacker controlled: Compile-time constants are inherently\n * under the control of the application and not under control of external\n * attackers, and hence are safe to use in such contexts.\n *\n * Instances of this type must be created via its factory method\n * `goog.string.Const.from` and not by invoking its constructor. The\n * constructor intentionally takes no parameters and the type is immutable;\n * hence only a default instance corresponding to the empty string can be\n * obtained via constructor invocation. Use goog.string.Const.EMPTY\n * instead of using this constructor to get an empty Const string.\n *\n * @see goog.string.Const#from\n * @constructor\n * @final\n * @struct\n * @implements {goog.string.TypedString}\n * @param {Object=} opt_token package-internal implementation detail.\n * @param {string=} opt_content package-internal implementation detail.\n */\ngoog.string.Const = function(opt_token, opt_content) {\n /**\n * The wrapped value of this Const object. The field has a purposely ugly\n * name to make (non-compiled) code that attempts to directly access this\n * field stand out.\n * @private {string}\n */\n this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ =\n ((opt_token ===\n goog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_) &&\n opt_content) ||\n '';\n\n /**\n * A type marker used to implement additional run-time type checking.\n * @see goog.string.Const#unwrap\n * @const {!Object}\n * @private\n */\n this.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ =\n goog.string.Const.TYPE_MARKER_;\n};\n\n\n/**\n * @override\n * @const\n */\ngoog.string.Const.prototype.implementsGoogStringTypedString = true;\n\n\n/**\n * Returns this Const's value a string.\n *\n * IMPORTANT: In code where it is security-relevant that an object's type is\n * indeed `goog.string.Const`, use `goog.string.Const.unwrap`\n * instead of this method.\n *\n * @see goog.string.Const#unwrap\n * @override\n */\ngoog.string.Const.prototype.getTypedStringValue = function() {\n return this.stringConstValueWithSecurityContract__googStringSecurityPrivate_;\n};\n\n\nif (goog.DEBUG) {\n /**\n * Returns a debug-string representation of this value.\n *\n * To obtain the actual string value wrapped inside an object of this type,\n * use `goog.string.Const.unwrap`.\n *\n * @see goog.string.Const#unwrap\n * @override\n */\n goog.string.Const.prototype.toString = function() {\n return 'Const{' +\n this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ +\n '}';\n };\n}\n\n\n/**\n * Performs a runtime check that the provided object is indeed an instance\n * of `goog.string.Const`, and returns its value.\n * @param {!goog.string.Const} stringConst The object to extract from.\n * @return {string} The Const object's contained string, unless the run-time\n * type check fails. In that case, `unwrap` returns an innocuous\n * string, or, if assertions are enabled, throws\n * `goog.asserts.AssertionError`.\n */\ngoog.string.Const.unwrap = function(stringConst) {\n // Perform additional run-time type-checking to ensure that stringConst is\n // indeed an instance of the expected type. This provides some additional\n // protection against security bugs due to application code that disables type\n // checks.\n if (stringConst instanceof goog.string.Const &&\n stringConst.constructor === goog.string.Const &&\n stringConst.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ ===\n goog.string.Const.TYPE_MARKER_) {\n return stringConst\n .stringConstValueWithSecurityContract__googStringSecurityPrivate_;\n } else {\n goog.asserts.fail(\n 'expected object of type Const, got \\'' + stringConst + '\\'');\n return 'type_error:Const';\n }\n};\n\n\n/**\n * Creates a Const object from a compile-time constant string.\n *\n * It is illegal to invoke this function on an expression whose\n * compile-time-constant value cannot be determined by the Closure compiler.\n *\n * Correct invocations include,\n * <pre>\n * var s = goog.string.Const.from('hello');\n * var t = goog.string.Const.from('hello' + 'world');\n * </pre>\n *\n * In contrast, the following are illegal:\n * <pre>\n * var s = goog.string.Const.from(getHello());\n * var t = goog.string.Const.from('hello' + world);\n * </pre>\n *\n * @param {string} s A constant string from which to create a Const.\n * @return {!goog.string.Const} A Const object initialized to stringConst.\n */\ngoog.string.Const.from = function(s) {\n return new goog.string.Const(\n goog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_, s);\n};\n\n/**\n * Type marker for the Const type, used to implement additional run-time\n * type checking.\n * @const {!Object}\n * @private\n */\ngoog.string.Const.TYPE_MARKER_ = {};\n\n/**\n * @type {!Object}\n * @private\n * @const\n */\ngoog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_ = {};\n\n/**\n * A Const instance wrapping the empty string.\n * @const {!goog.string.Const}\n */\ngoog.string.Const.EMPTY = goog.string.Const.from('');\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The TrustedResourceUrl type and its builders.\n *\n * TODO(xtof): Link to document stating type contract.\n */\n\ngoog.provide('goog.html.TrustedResourceUrl');\n\ngoog.require('goog.asserts');\ngoog.require('goog.fs.blob');\ngoog.require('goog.fs.url');\ngoog.require('goog.html.SafeScript');\ngoog.require('goog.html.trustedtypes');\ngoog.require('goog.i18n.bidi.Dir');\ngoog.require('goog.i18n.bidi.DirectionalString');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.TypedString');\n\n\n\n/**\n * A URL which is under application control and from which script, CSS, and\n * other resources that represent executable code, can be fetched.\n *\n * Given that the URL can only be constructed from strings under application\n * control and is used to load resources, bugs resulting in a malformed URL\n * should not have a security impact and are likely to be easily detectable\n * during testing. Given the wide number of non-RFC compliant URLs in use,\n * stricter validation could prevent some applications from being able to use\n * this type.\n *\n * Instances of this type must be created via the factory method,\n * (`fromConstant`, `fromConstants`, `format` or\n * `formatWithParams`), and not by invoking its constructor. The constructor\n * is organized in a way that only methods from that file can call it and\n * initialize with non-empty values. Anyone else calling constructor will\n * get default instance with empty value.\n *\n * @see goog.html.TrustedResourceUrl#fromConstant\n * @constructor\n * @final\n * @struct\n * @implements {goog.i18n.bidi.DirectionalString}\n * @implements {goog.string.TypedString}\n * @param {!Object=} opt_token package-internal implementation detail.\n * @param {!TrustedScriptURL|string=} opt_content package-internal\n * implementation detail.\n */\ngoog.html.TrustedResourceUrl = function(opt_token, opt_content) {\n /**\n * The contained value of this TrustedResourceUrl. The field has a purposely\n * ugly name to make (non-compiled) code that attempts to directly access this\n * field stand out.\n * @const\n * @private {!TrustedScriptURL|string}\n */\n this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ =\n ((opt_token ===\n goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_) &&\n opt_content) ||\n '';\n\n /**\n * A type marker used to implement additional run-time type checking.\n * @see goog.html.TrustedResourceUrl#unwrap\n * @const {!Object}\n * @private\n */\n this.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =\n goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;\n};\n\n\n/**\n * @override\n * @const\n */\ngoog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true;\n\n\n/**\n * Returns this TrustedResourceUrl's value as a string.\n *\n * IMPORTANT: In code where it is security relevant that an object's type is\n * indeed `TrustedResourceUrl`, use\n * `goog.html.TrustedResourceUrl.unwrap` instead of this method. If in\n * doubt, assume that it's security relevant. In particular, note that\n * goog.html functions which return a goog.html type do not guarantee that\n * the returned instance is of the right type. For example:\n *\n * <pre>\n * var fakeSafeHtml = new String('fake');\n * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;\n * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);\n * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by\n * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof\n * // goog.html.SafeHtml.\n * </pre>\n *\n * @see goog.html.TrustedResourceUrl#unwrap\n * @override\n */\ngoog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() {\n return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_\n .toString();\n};\n\n\n/**\n * @override\n * @const\n */\ngoog.html.TrustedResourceUrl.prototype.implementsGoogI18nBidiDirectionalString =\n true;\n\n\n/**\n * Returns this URLs directionality, which is always `LTR`.\n * @override\n */\ngoog.html.TrustedResourceUrl.prototype.getDirection = function() {\n return goog.i18n.bidi.Dir.LTR;\n};\n\n\n/**\n * Creates a new TrustedResourceUrl with params added to URL. Both search and\n * hash params can be specified.\n *\n * @param {string|?Object<string, *>|undefined} searchParams Search parameters\n * to add to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for\n * exact format definition.\n * @param {(string|?Object<string, *>)=} opt_hashParams Hash parameters to add\n * to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact\n * format definition.\n * @return {!goog.html.TrustedResourceUrl} New TrustedResourceUrl with params.\n */\ngoog.html.TrustedResourceUrl.prototype.cloneWithParams = function(\n searchParams, opt_hashParams) {\n var url = goog.html.TrustedResourceUrl.unwrap(this);\n var parts = goog.html.TrustedResourceUrl.URL_PARAM_PARSER_.exec(url);\n var urlBase = parts[1];\n var urlSearch = parts[2] || '';\n var urlHash = parts[3] || '';\n\n return goog.html.TrustedResourceUrl\n .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(\n urlBase +\n goog.html.TrustedResourceUrl.stringifyParams_(\n '?', urlSearch, searchParams) +\n goog.html.TrustedResourceUrl.stringifyParams_(\n '#', urlHash, opt_hashParams));\n};\n\n\nif (goog.DEBUG) {\n /**\n * Returns a debug string-representation of this value.\n *\n * To obtain the actual string value wrapped in a TrustedResourceUrl, use\n * `goog.html.TrustedResourceUrl.unwrap`.\n *\n * @see goog.html.TrustedResourceUrl#unwrap\n * @override\n */\n goog.html.TrustedResourceUrl.prototype.toString = function() {\n return 'TrustedResourceUrl{' +\n this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '}';\n };\n}\n\n\n/**\n * Performs a runtime check that the provided object is indeed a\n * TrustedResourceUrl object, and returns its value.\n *\n * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to\n * extract from.\n * @return {string} The trustedResourceUrl object's contained string, unless\n * the run-time type check fails. In that case, `unwrap` returns an\n * innocuous string, or, if assertions are enabled, throws\n * `goog.asserts.AssertionError`.\n */\ngoog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) {\n return goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(trustedResourceUrl)\n .toString();\n};\n\n\n/**\n * Unwraps value as TrustedScriptURL if supported or as a string if not.\n * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl\n * @return {!TrustedScriptURL|string}\n * @see goog.html.TrustedResourceUrl.unwrap\n */\ngoog.html.TrustedResourceUrl.unwrapTrustedScriptURL = function(\n trustedResourceUrl) {\n // Perform additional Run-time type-checking to ensure that\n // trustedResourceUrl is indeed an instance of the expected type. This\n // provides some additional protection against security bugs due to\n // application code that disables type checks.\n // Specifically, the following checks are performed:\n // 1. The object is an instance of the expected type.\n // 2. The object is not an instance of a subclass.\n // 3. The object carries a type marker for the expected type. \"Faking\" an\n // object requires a reference to the type marker, which has names intended\n // to stand out in code reviews.\n if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl &&\n trustedResourceUrl.constructor === goog.html.TrustedResourceUrl &&\n trustedResourceUrl\n .TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===\n goog.html.TrustedResourceUrl\n .TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {\n return trustedResourceUrl\n .privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_;\n } else {\n goog.asserts.fail('expected object of type TrustedResourceUrl, got \\'' +\n trustedResourceUrl + '\\' of type ' + goog.typeOf(trustedResourceUrl));\n return 'type_error:TrustedResourceUrl';\n }\n};\n\n\n/**\n * Creates a TrustedResourceUrl from a format string and arguments.\n *\n * The arguments for interpolation into the format string map labels to values.\n * Values of type `goog.string.Const` are interpolated without modifcation.\n * Values of other types are cast to string and encoded with\n * encodeURIComponent.\n *\n * `%{<label>}` markers are used in the format string to indicate locations\n * to be interpolated with the valued mapped to the given label. `<label>`\n * must contain only alphanumeric and `_` characters.\n *\n * The format string must match goog.html.TrustedResourceUrl.BASE_URL_.\n *\n * Example usage:\n *\n * var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(\n * 'https://www.google.com/search?q=%{query}'), {'query': searchTerm});\n *\n * var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from(\n * '//www.youtube.com/v/%{videoId}?hl=en&fs=1%{autoplay}'), {\n * 'videoId': videoId,\n * 'autoplay': opt_autoplay ?\n * goog.string.Const.from('&autoplay=1') : goog.string.Const.EMPTY\n * });\n *\n * While this function can be used to create a TrustedResourceUrl from only\n * constants, fromConstant() and fromConstants() are generally preferable for\n * that purpose.\n *\n * @param {!goog.string.Const} format The format string.\n * @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping\n * of labels to values to be interpolated into the format string.\n * goog.string.Const values are interpolated without encoding.\n * @return {!goog.html.TrustedResourceUrl}\n * @throws {!Error} On an invalid format string or if a label used in the\n * the format string is not present in args.\n */\ngoog.html.TrustedResourceUrl.format = function(format, args) {\n var formatStr = goog.string.Const.unwrap(format);\n if (!goog.html.TrustedResourceUrl.BASE_URL_.test(formatStr)) {\n throw new Error('Invalid TrustedResourceUrl format: ' + formatStr);\n }\n var result = formatStr.replace(\n goog.html.TrustedResourceUrl.FORMAT_MARKER_, function(match, id) {\n if (!Object.prototype.hasOwnProperty.call(args, id)) {\n throw new Error(\n 'Found marker, \"' + id + '\", in format string, \"' + formatStr +\n '\", but no valid label mapping found ' +\n 'in args: ' + JSON.stringify(args));\n }\n var arg = args[id];\n if (arg instanceof goog.string.Const) {\n return goog.string.Const.unwrap(arg);\n } else {\n return encodeURIComponent(String(arg));\n }\n });\n return goog.html.TrustedResourceUrl\n .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(result);\n};\n\n\n/**\n * @private @const {!RegExp}\n */\ngoog.html.TrustedResourceUrl.FORMAT_MARKER_ = /%{(\\w+)}/g;\n\n\n/**\n * The URL must be absolute, scheme-relative or path-absolute. So it must\n * start with:\n * - https:// followed by allowed origin characters.\n * - // followed by allowed origin characters.\n * - Any absolute or relative path.\n *\n * Based on\n * https://url.spec.whatwg.org/commit-snapshots/56b74ce7cca8883eab62e9a12666e2fac665d03d/#url-parsing\n * an initial / which is not followed by another / or \\ will end up in the \"path\n * state\" and from there it can only go to \"fragment state\" and \"query state\".\n *\n * We don't enforce a well-formed domain name. So '.' or '1.2' are valid.\n * That's ok because the origin comes from a compile-time constant.\n *\n * A regular expression is used instead of goog.uri for several reasons:\n * - Strictness. E.g. we don't want any userinfo component and we don't\n * want '/./, nor \\' in the first path component.\n * - Small trusted base. goog.uri is generic and might need to change,\n * reasoning about all the ways it can parse a URL now and in the future\n * is error-prone.\n * - Code size. We expect many calls to .format(), many of which might\n * not be using goog.uri.\n * - Simplicity. Using goog.uri would likely not result in simpler nor shorter\n * code.\n * @private @const {!RegExp}\n */\ngoog.html.TrustedResourceUrl.BASE_URL_ = new RegExp(\n '^((https:)?//[0-9a-z.:[\\\\]-]+/' // Origin.\n + '|/[^/\\\\\\\\]' // Absolute path.\n + '|[^:/\\\\\\\\%]+/' // Relative path.\n + '|[^:/\\\\\\\\%]*[?#]' // Query string or fragment.\n + '|about:blank#' // about:blank with fragment.\n + ')',\n 'i');\n\n/**\n * RegExp for splitting a URL into the base, search field, and hash field.\n *\n * @private @const {!RegExp}\n */\ngoog.html.TrustedResourceUrl.URL_PARAM_PARSER_ =\n /^([^?#]*)(\\?[^#]*)?(#[\\s\\S]*)?/;\n\n\n/**\n * Formats the URL same as TrustedResourceUrl.format and then adds extra URL\n * parameters.\n *\n * Example usage:\n *\n * // Creates '//www.youtube.com/v/abc?autoplay=1' for videoId='abc' and\n * // opt_autoplay=1. Creates '//www.youtube.com/v/abc' for videoId='abc'\n * // and opt_autoplay=undefined.\n * var url = goog.html.TrustedResourceUrl.formatWithParams(\n * goog.string.Const.from('//www.youtube.com/v/%{videoId}'),\n * {'videoId': videoId},\n * {'autoplay': opt_autoplay});\n *\n * @param {!goog.string.Const} format The format string.\n * @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping\n * of labels to values to be interpolated into the format string.\n * goog.string.Const values are interpolated without encoding.\n * @param {string|?Object<string, *>|undefined} searchParams Parameters to add\n * to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact\n * format definition.\n * @param {(string|?Object<string, *>)=} opt_hashParams Hash parameters to add\n * to URL. See goog.html.TrustedResourceUrl.stringifyParams_ for exact\n * format definition.\n * @return {!goog.html.TrustedResourceUrl}\n * @throws {!Error} On an invalid format string or if a label used in the\n * the format string is not present in args.\n */\ngoog.html.TrustedResourceUrl.formatWithParams = function(\n format, args, searchParams, opt_hashParams) {\n var url = goog.html.TrustedResourceUrl.format(format, args);\n return url.cloneWithParams(searchParams, opt_hashParams);\n};\n\n\n/**\n * Creates a TrustedResourceUrl object from a compile-time constant string.\n *\n * Compile-time constant strings are inherently program-controlled and hence\n * trusted.\n *\n * @param {!goog.string.Const} url A compile-time-constant string from which to\n * create a TrustedResourceUrl.\n * @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object\n * initialized to `url`.\n */\ngoog.html.TrustedResourceUrl.fromConstant = function(url) {\n return goog.html.TrustedResourceUrl\n .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(\n goog.string.Const.unwrap(url));\n};\n\n\n/**\n * Creates a TrustedResourceUrl object from a compile-time constant strings.\n *\n * Compile-time constant strings are inherently program-controlled and hence\n * trusted.\n *\n * @param {!Array<!goog.string.Const>} parts Compile-time-constant strings from\n * which to create a TrustedResourceUrl.\n * @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object\n * initialized to concatenation of `parts`.\n */\ngoog.html.TrustedResourceUrl.fromConstants = function(parts) {\n var unwrapped = '';\n for (var i = 0; i < parts.length; i++) {\n unwrapped += goog.string.Const.unwrap(parts[i]);\n }\n return goog.html.TrustedResourceUrl\n .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(unwrapped);\n};\n\n/**\n * Creates a TrustedResourceUrl object by generating a Blob from a SafeScript\n * object and then calling createObjectURL with that blob.\n *\n * SafeScript objects are trusted to contain executable JavaScript code.\n *\n * Caller must call goog.fs.url.revokeObjectUrl() on the unwrapped url to\n * release the underlying blob.\n *\n * Throws if browser doesn't support blob construction.\n *\n * @param {!goog.html.SafeScript} safeScript A script from which to create a\n * TrustedResourceUrl.\n * @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object\n * initialized to a new blob URL.\n */\ngoog.html.TrustedResourceUrl.fromSafeScript = function(safeScript) {\n var blob = goog.fs.blob.getBlobWithProperties(\n [goog.html.SafeScript.unwrap(safeScript)], 'text/javascript');\n var url = goog.fs.url.createObjectUrl(blob);\n return goog.html.TrustedResourceUrl\n .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url);\n};\n\n\n/**\n * Type marker for the TrustedResourceUrl type, used to implement additional\n * run-time type checking.\n * @const {!Object}\n * @private\n */\ngoog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};\n\n\n/**\n * Package-internal utility method to create TrustedResourceUrl instances.\n *\n * @param {string} url The string to initialize the TrustedResourceUrl object\n * with.\n * @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl\n * object.\n * @package\n */\ngoog.html.TrustedResourceUrl\n .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) {\n var value = goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY ?\n goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY\n .createScriptURL(url) :\n url;\n return new goog.html.TrustedResourceUrl(\n goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_, value);\n};\n\n\n/**\n * Stringifies the passed params to be used as either a search or hash field of\n * a URL.\n *\n * @param {string} prefix The prefix character for the given field ('?' or '#').\n * @param {string} currentString The existing field value (including the prefix\n * character, if the field is present).\n * @param {string|?Object<string, *>|undefined} params The params to set or\n * append to the field.\n * - If `undefined` or `null`, the field remains unchanged.\n * - If a string, then the string will be escaped and the field will be\n * overwritten with that value.\n * - If an Object, that object is treated as a set of key-value pairs to be\n * appended to the current field. Note that JavaScript doesn't guarantee the\n * order of values in an object which might result in non-deterministic order\n * of the parameters. However, browsers currently preserve the order. The\n * rules for each entry:\n * - If an array, it will be processed as if each entry were an additional\n * parameter with exactly the same key, following the same logic below.\n * - If `undefined` or `null`, it will be skipped.\n * - Otherwise, it will be turned into a string, escaped, and appended.\n * @return {string}\n * @private\n */\ngoog.html.TrustedResourceUrl.stringifyParams_ = function(\n prefix, currentString, params) {\n if (params == null) {\n // Do not modify the field.\n return currentString;\n }\n if (typeof params === 'string') {\n // Set field to the passed string.\n return params ? prefix + encodeURIComponent(params) : '';\n }\n // Add on parameters to field from key-value object.\n for (var key in params) {\n var value = params[key];\n var outputValues = Array.isArray(value) ? value : [value];\n for (var i = 0; i < outputValues.length; i++) {\n var outputValue = outputValues[i];\n if (outputValue != null) {\n if (!currentString) {\n currentString = prefix;\n }\n currentString += (currentString.length > prefix.length ? '&' : '') +\n encodeURIComponent(key) + '=' +\n encodeURIComponent(String(outputValue));\n }\n }\n }\n return currentString;\n};\n\n/**\n * Token used to ensure that object is created only from this file. No code\n * outside of this file can access this token.\n * @private {!Object}\n * @const\n */\ngoog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_ = {};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The SafeUrl type and its builders.\n *\n * TODO(xtof): Link to document stating type contract.\n */\n\ngoog.provide('goog.html.SafeUrl');\n\ngoog.require('goog.asserts');\ngoog.require('goog.fs.url');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.i18n.bidi.Dir');\ngoog.require('goog.i18n.bidi.DirectionalString');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.TypedString');\ngoog.require('goog.string.internal');\n\n\n\n/**\n * A string that is safe to use in URL context in DOM APIs and HTML documents.\n *\n * A SafeUrl is a string-like object that carries the security type contract\n * that its value as a string will not cause untrusted script execution\n * when evaluated as a hyperlink URL in a browser.\n *\n * Values of this type are guaranteed to be safe to use in URL/hyperlink\n * contexts, such as assignment to URL-valued DOM properties, in the sense that\n * the use will not result in a Cross-Site-Scripting vulnerability. Similarly,\n * SafeUrls can be interpolated into the URL context of an HTML template (e.g.,\n * inside a href attribute). However, appropriate HTML-escaping must still be\n * applied.\n *\n * Note that, as documented in `goog.html.SafeUrl.unwrap`, this type's\n * contract does not guarantee that instances are safe to interpolate into HTML\n * without appropriate escaping.\n *\n * Note also that this type's contract does not imply any guarantees regarding\n * the resource the URL refers to. In particular, SafeUrls are <b>not</b>\n * safe to use in a context where the referred-to resource is interpreted as\n * trusted code, e.g., as the src of a script tag.\n *\n * Instances of this type must be created via the factory methods\n * (`goog.html.SafeUrl.fromConstant`, `goog.html.SafeUrl.sanitize`),\n * etc and not by invoking its constructor. The constructor is organized in a\n * way that only methods from that file can call it and initialize with\n * non-empty values. Anyone else calling constructor will get default instance\n * with empty value.\n *\n * @see goog.html.SafeUrl#fromConstant\n * @see goog.html.SafeUrl#from\n * @see goog.html.SafeUrl#sanitize\n * @constructor\n * @final\n * @struct\n * @implements {goog.i18n.bidi.DirectionalString}\n * @implements {goog.string.TypedString}\n * @param {!Object=} opt_token package-internal implementation detail.\n * @param {string=} opt_content package-internal implementation detail.\n */\ngoog.html.SafeUrl = function(opt_token, opt_content) {\n /**\n * The contained value of this SafeUrl. The field has a purposely ugly\n * name to make (non-compiled) code that attempts to directly access this\n * field stand out.\n * @private {string}\n */\n this.privateDoNotAccessOrElseSafeUrlWrappedValue_ =\n ((opt_token === goog.html.SafeUrl.CONSTRUCTOR_TOKEN_PRIVATE_) &&\n opt_content) ||\n '';\n\n /**\n * A type marker used to implement additional run-time type checking.\n * @see goog.html.SafeUrl#unwrap\n * @const {!Object}\n * @private\n */\n this.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =\n goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;\n};\n\n\n/**\n * The innocuous string generated by goog.html.SafeUrl.sanitize when passed\n * an unsafe URL.\n *\n * about:invalid is registered in\n * http://www.w3.org/TR/css3-values/#about-invalid.\n * http://tools.ietf.org/html/rfc6694#section-2.2.1 permits about URLs to\n * contain a fragment, which is not to be considered when determining if an\n * about URL is well-known.\n *\n * Using about:invalid seems preferable to using a fixed data URL, since\n * browsers might choose to not report CSP violations on it, as legitimate\n * CSS function calls to attr() can result in this URL being produced. It is\n * also a standard URL which matches exactly the semantics we need:\n * \"The about:invalid URI references a non-existent document with a generic\n * error condition. It can be used when a URI is necessary, but the default\n * value shouldn't be resolveable as any type of document\".\n *\n * @const {string}\n */\ngoog.html.SafeUrl.INNOCUOUS_STRING = 'about:invalid#zClosurez';\n\n\n/**\n * @override\n * @const\n */\ngoog.html.SafeUrl.prototype.implementsGoogStringTypedString = true;\n\n\n/**\n * Returns this SafeUrl's value a string.\n *\n * IMPORTANT: In code where it is security relevant that an object's type is\n * indeed `SafeUrl`, use `goog.html.SafeUrl.unwrap` instead of this\n * method. If in doubt, assume that it's security relevant. In particular, note\n * that goog.html functions which return a goog.html type do not guarantee that\n * the returned instance is of the right type.\n *\n * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the\n * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST\n * be appropriately escaped before embedding in a HTML document. Note that the\n * required escaping is context-sensitive (e.g. a different escaping is\n * required for embedding a URL in a style property within a style\n * attribute, as opposed to embedding in a href attribute).\n *\n * @see goog.html.SafeUrl#unwrap\n * @override\n */\ngoog.html.SafeUrl.prototype.getTypedStringValue = function() {\n return this.privateDoNotAccessOrElseSafeUrlWrappedValue_.toString();\n};\n\n\n/**\n * @override\n * @const\n */\ngoog.html.SafeUrl.prototype.implementsGoogI18nBidiDirectionalString = true;\n\n\n/**\n * Returns this URLs directionality, which is always `LTR`.\n * @override\n */\ngoog.html.SafeUrl.prototype.getDirection = function() {\n return goog.i18n.bidi.Dir.LTR;\n};\n\n\nif (goog.DEBUG) {\n /**\n * Returns a debug string-representation of this value.\n *\n * To obtain the actual string value wrapped in a SafeUrl, use\n * `goog.html.SafeUrl.unwrap`.\n *\n * @see goog.html.SafeUrl#unwrap\n * @override\n */\n goog.html.SafeUrl.prototype.toString = function() {\n return 'SafeUrl{' + this.privateDoNotAccessOrElseSafeUrlWrappedValue_ + '}';\n };\n}\n\n\n/**\n * Performs a runtime check that the provided object is indeed a SafeUrl\n * object, and returns its value.\n *\n * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the\n * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST\n * be appropriately escaped before embedding in a HTML document. Note that the\n * required escaping is context-sensitive (e.g. a different escaping is\n * required for embedding a URL in a style property within a style\n * attribute, as opposed to embedding in a href attribute).\n *\n * @param {!goog.html.SafeUrl} safeUrl The object to extract from.\n * @return {string} The SafeUrl object's contained string, unless the run-time\n * type check fails. In that case, `unwrap` returns an innocuous\n * string, or, if assertions are enabled, throws\n * `goog.asserts.AssertionError`.\n */\ngoog.html.SafeUrl.unwrap = function(safeUrl) {\n // Perform additional Run-time type-checking to ensure that safeUrl is indeed\n // an instance of the expected type. This provides some additional protection\n // against security bugs due to application code that disables type checks.\n // Specifically, the following checks are performed:\n // 1. The object is an instance of the expected type.\n // 2. The object is not an instance of a subclass.\n // 3. The object carries a type marker for the expected type. \"Faking\" an\n // object requires a reference to the type marker, which has names intended\n // to stand out in code reviews.\n if (safeUrl instanceof goog.html.SafeUrl &&\n safeUrl.constructor === goog.html.SafeUrl &&\n safeUrl.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===\n goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {\n return safeUrl.privateDoNotAccessOrElseSafeUrlWrappedValue_;\n } else {\n goog.asserts.fail('expected object of type SafeUrl, got \\'' +\n safeUrl + '\\' of type ' + goog.typeOf(safeUrl));\n return 'type_error:SafeUrl';\n }\n};\n\n\n/**\n * Creates a SafeUrl object from a compile-time constant string.\n *\n * Compile-time constant strings are inherently program-controlled and hence\n * trusted.\n *\n * @param {!goog.string.Const} url A compile-time-constant string from which to\n * create a SafeUrl.\n * @return {!goog.html.SafeUrl} A SafeUrl object initialized to `url`.\n */\ngoog.html.SafeUrl.fromConstant = function(url) {\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n goog.string.Const.unwrap(url));\n};\n\n\n/**\n * A pattern that matches Blob or data types that can have SafeUrls created\n * from URL.createObjectURL(blob) or via a data: URI.\n *\n * This has some parameter support (most notably, we haven't implemented the\n * more complex parts like %-encoded characters or non-alphanumerical ones for\n * simplicity's sake). The specs are fairly complex, and they don't\n * always match Chrome's behavior: we settled on a subset where we're confident\n * all parties involved agree.\n *\n * The spec is available at https://mimesniff.spec.whatwg.org/ (and see\n * https://tools.ietf.org/html/rfc2397 for data: urls, which override some of\n * it).\n * @const\n * @private\n */\ngoog.html.SAFE_MIME_TYPE_PATTERN_ = new RegExp(\n // Note: Due to content-sniffing concerns, only add MIME types for\n // media formats.\n '^(?:audio/(?:3gpp2|3gpp|aac|L16|midi|mp3|mp4|mpeg|oga|ogg|opus|x-m4a|x-wav|wav|webm)|' +\n 'image/(?:bmp|gif|jpeg|jpg|png|tiff|webp|x-icon)|' +\n // TODO(user): Due to content-sniffing concerns, text/csv should\n // be removed from the whitelist.\n 'text/csv|' +\n 'video/(?:mpeg|mp4|ogg|webm|quicktime))' +\n '(?:;\\\\w+=(?:\\\\w+|\"[\\\\w;=]+\"))*$', // MIME type parameters\n 'i');\n\n\n/**\n * @param {string} mimeType The MIME type to check if safe.\n * @return {boolean} True if the MIME type is safe and creating a Blob via\n * `SafeUrl.fromBlob()` with that type will not fail due to the type. False\n * otherwise.\n */\ngoog.html.SafeUrl.isSafeMimeType = function(mimeType) {\n return goog.html.SAFE_MIME_TYPE_PATTERN_.test(mimeType);\n};\n\n\n/**\n * Creates a SafeUrl wrapping a blob URL for the given `blob`.\n *\n * The blob URL is created with `URL.createObjectURL`. If the MIME type\n * for `blob` is not of a known safe audio, image or video MIME type,\n * then the SafeUrl will wrap {@link #INNOCUOUS_STRING}.\n *\n * @see http://www.w3.org/TR/FileAPI/#url\n * @param {!Blob} blob\n * @return {!goog.html.SafeUrl} The blob URL, or an innocuous string wrapped\n * as a SafeUrl.\n */\ngoog.html.SafeUrl.fromBlob = function(blob) {\n var url = goog.html.SAFE_MIME_TYPE_PATTERN_.test(blob.type) ?\n goog.fs.url.createObjectUrl(blob) :\n goog.html.SafeUrl.INNOCUOUS_STRING;\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);\n};\n\n\n/**\n * Matches a base-64 data URL, with the first match group being the MIME type.\n * @const\n * @private\n */\ngoog.html.DATA_URL_PATTERN_ = /^data:([^,]*);base64,[a-z0-9+\\/]+=*$/i;\n\n\n/**\n * Creates a SafeUrl wrapping a data: URL, after validating it matches a\n * known-safe audio, image or video MIME type.\n *\n * @param {string} dataUrl A valid base64 data URL with one of the whitelisted\n * audio, image or video MIME types.\n * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}\n * wrapped as a SafeUrl if it does not pass.\n */\ngoog.html.SafeUrl.fromDataUrl = function(dataUrl) {\n // RFC4648 suggest to ignore CRLF in base64 encoding.\n // See https://tools.ietf.org/html/rfc4648.\n // Remove the CR (%0D) and LF (%0A) from the dataUrl.\n var filteredDataUrl = dataUrl.replace(/(%0A|%0D)/g, '');\n // There's a slight risk here that a browser sniffs the content type if it\n // doesn't know the MIME type and executes HTML within the data: URL. For this\n // to cause XSS it would also have to execute the HTML in the same origin\n // of the page with the link. It seems unlikely that both of these will\n // happen, particularly in not really old IEs.\n var match = filteredDataUrl.match(goog.html.DATA_URL_PATTERN_);\n var valid = match && goog.html.SAFE_MIME_TYPE_PATTERN_.test(match[1]);\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n valid ? filteredDataUrl : goog.html.SafeUrl.INNOCUOUS_STRING);\n};\n\n\n/**\n * Creates a SafeUrl wrapping a tel: URL.\n *\n * @param {string} telUrl A tel URL.\n * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}\n * wrapped as a SafeUrl if it does not pass.\n */\ngoog.html.SafeUrl.fromTelUrl = function(telUrl) {\n // There's a risk that a tel: URL could immediately place a call once\n // clicked, without requiring user confirmation. For that reason it is\n // handled in this separate function.\n if (!goog.string.internal.caseInsensitiveStartsWith(telUrl, 'tel:')) {\n telUrl = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n telUrl);\n};\n\n\n/**\n * Matches a sip/sips URL. We only allow urls that consist of an email address.\n * The characters '?' and '#' are not allowed in the local part of the email\n * address.\n * @const\n * @private\n */\ngoog.html.SIP_URL_PATTERN_ = new RegExp(\n '^sip[s]?:[+a-z0-9_.!$%&\\'*\\\\/=^`{|}~-]+@([a-z0-9-]+\\\\.)+[a-z0-9]{2,63}$',\n 'i');\n\n\n/**\n * Creates a SafeUrl wrapping a sip: URL. We only allow urls that consist of an\n * email address. The characters '?' and '#' are not allowed in the local part\n * of the email address.\n *\n * @param {string} sipUrl A sip URL.\n * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}\n * wrapped as a SafeUrl if it does not pass.\n */\ngoog.html.SafeUrl.fromSipUrl = function(sipUrl) {\n if (!goog.html.SIP_URL_PATTERN_.test(decodeURIComponent(sipUrl))) {\n sipUrl = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n sipUrl);\n};\n\n\n/**\n * Creates a SafeUrl wrapping a fb-messenger://share URL.\n *\n * @param {string} facebookMessengerUrl A facebook messenger URL.\n * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}\n * wrapped as a SafeUrl if it does not pass.\n */\ngoog.html.SafeUrl.fromFacebookMessengerUrl = function(facebookMessengerUrl) {\n if (!goog.string.internal.caseInsensitiveStartsWith(\n facebookMessengerUrl, 'fb-messenger://share')) {\n facebookMessengerUrl = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n facebookMessengerUrl);\n};\n\n/**\n * Creates a SafeUrl wrapping a whatsapp://send URL.\n *\n * @param {string} whatsAppUrl A WhatsApp URL.\n * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}\n * wrapped as a SafeUrl if it does not pass.\n */\ngoog.html.SafeUrl.fromWhatsAppUrl = function(whatsAppUrl) {\n if (!goog.string.internal.caseInsensitiveStartsWith(\n whatsAppUrl, 'whatsapp://send')) {\n whatsAppUrl = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n whatsAppUrl);\n};\n\n/**\n * Creates a SafeUrl wrapping a sms: URL.\n *\n * @param {string} smsUrl A sms URL.\n * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}\n * wrapped as a SafeUrl if it does not pass.\n */\ngoog.html.SafeUrl.fromSmsUrl = function(smsUrl) {\n if (!goog.string.internal.caseInsensitiveStartsWith(smsUrl, 'sms:') ||\n !goog.html.SafeUrl.isSmsUrlBodyValid_(smsUrl)) {\n smsUrl = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n smsUrl);\n};\n\n\n/**\n * Validates SMS URL `body` parameter, which is optional and should appear at\n * most once and should be percent-encoded if present. Rejects many malformed\n * bodies, but may spuriously reject some URLs and does not reject all malformed\n * sms: URLs.\n *\n * @param {string} smsUrl A sms URL.\n * @return {boolean} Whether SMS URL has a valid `body` parameter if it exists.\n * @private\n */\ngoog.html.SafeUrl.isSmsUrlBodyValid_ = function(smsUrl) {\n var hash = smsUrl.indexOf('#');\n if (hash > 0) {\n smsUrl = smsUrl.substring(0, hash);\n }\n var bodyParams = smsUrl.match(/[?&]body=/gi);\n // \"body\" param is optional\n if (!bodyParams) {\n return true;\n }\n // \"body\" MUST only appear once\n if (bodyParams.length > 1) {\n return false;\n }\n // Get the encoded `body` parameter value.\n var bodyValue = smsUrl.match(/[?&]body=([^&]*)/)[1];\n if (!bodyValue) {\n return true;\n }\n try {\n decodeURIComponent(bodyValue);\n } catch (error) {\n return false;\n }\n return /^(?:[a-z0-9\\-_.~]|%[0-9a-f]{2})+$/i.test(bodyValue);\n};\n\n\n/**\n * Creates a SafeUrl wrapping a ssh: URL.\n *\n * @param {string} sshUrl A ssh URL.\n * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING}\n * wrapped as a SafeUrl if it does not pass.\n */\ngoog.html.SafeUrl.fromSshUrl = function(sshUrl) {\n if (!goog.string.internal.caseInsensitiveStartsWith(sshUrl, 'ssh://')) {\n sshUrl = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n sshUrl);\n};\n\n/**\n * Sanitizes a Chrome extension URL to SafeUrl, given a compile-time-constant\n * extension identifier. Can also be restricted to chrome extensions.\n *\n * @param {string} url The url to sanitize. Should start with the extension\n * scheme and the extension identifier.\n * @param {!goog.string.Const|!Array<!goog.string.Const>} extensionId The\n * extension id to accept, as a compile-time constant or an array of those.\n *\n * @return {!goog.html.SafeUrl} Either `url` if it's deemed safe, or\n * `INNOCUOUS_STRING` if it's not.\n */\ngoog.html.SafeUrl.sanitizeChromeExtensionUrl = function(url, extensionId) {\n return goog.html.SafeUrl.sanitizeExtensionUrl_(\n /^chrome-extension:\\/\\/([^\\/]+)\\//, url, extensionId);\n};\n\n/**\n * Sanitizes a Firefox extension URL to SafeUrl, given a compile-time-constant\n * extension identifier. Can also be restricted to chrome extensions.\n *\n * @param {string} url The url to sanitize. Should start with the extension\n * scheme and the extension identifier.\n * @param {!goog.string.Const|!Array<!goog.string.Const>} extensionId The\n * extension id to accept, as a compile-time constant or an array of those.\n *\n * @return {!goog.html.SafeUrl} Either `url` if it's deemed safe, or\n * `INNOCUOUS_STRING` if it's not.\n */\ngoog.html.SafeUrl.sanitizeFirefoxExtensionUrl = function(url, extensionId) {\n return goog.html.SafeUrl.sanitizeExtensionUrl_(\n /^moz-extension:\\/\\/([^\\/]+)\\//, url, extensionId);\n};\n\n/**\n * Sanitizes a Edge extension URL to SafeUrl, given a compile-time-constant\n * extension identifier. Can also be restricted to chrome extensions.\n *\n * @param {string} url The url to sanitize. Should start with the extension\n * scheme and the extension identifier.\n * @param {!goog.string.Const|!Array<!goog.string.Const>} extensionId The\n * extension id to accept, as a compile-time constant or an array of those.\n *\n * @return {!goog.html.SafeUrl} Either `url` if it's deemed safe, or\n * `INNOCUOUS_STRING` if it's not.\n */\ngoog.html.SafeUrl.sanitizeEdgeExtensionUrl = function(url, extensionId) {\n return goog.html.SafeUrl.sanitizeExtensionUrl_(\n /^ms-browser-extension:\\/\\/([^\\/]+)\\//, url, extensionId);\n};\n\n/**\n * Private helper for converting extension URLs to SafeUrl, given the scheme for\n * that particular extension type. Use the sanitizeFirefoxExtensionUrl,\n * sanitizeChromeExtensionUrl or sanitizeEdgeExtensionUrl unless you're building\n * new helpers.\n *\n * @private\n * @param {!RegExp} scheme The scheme to accept as a RegExp extracting the\n * extension identifier.\n * @param {string} url The url to sanitize. Should start with the extension\n * scheme and the extension identifier.\n * @param {!goog.string.Const|!Array<!goog.string.Const>} extensionId The\n * extension id to accept, as a compile-time constant or an array of those.\n *\n * @return {!goog.html.SafeUrl} Either `url` if it's deemed safe, or\n * `INNOCUOUS_STRING` if it's not.\n */\ngoog.html.SafeUrl.sanitizeExtensionUrl_ = function(scheme, url, extensionId) {\n var matches = scheme.exec(url);\n if (!matches) {\n url = goog.html.SafeUrl.INNOCUOUS_STRING;\n } else {\n var extractedExtensionId = matches[1];\n var acceptedExtensionIds;\n if (extensionId instanceof goog.string.Const) {\n acceptedExtensionIds = [goog.string.Const.unwrap(extensionId)];\n } else {\n acceptedExtensionIds = extensionId.map(function unwrap(x) {\n return goog.string.Const.unwrap(x);\n });\n }\n if (acceptedExtensionIds.indexOf(extractedExtensionId) == -1) {\n url = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);\n};\n\n\n/**\n * Creates a SafeUrl from TrustedResourceUrl. This is safe because\n * TrustedResourceUrl is more tightly restricted than SafeUrl.\n *\n * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl\n * @return {!goog.html.SafeUrl}\n */\ngoog.html.SafeUrl.fromTrustedResourceUrl = function(trustedResourceUrl) {\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl));\n};\n\n\n/**\n * A pattern that recognizes a commonly useful subset of URLs that satisfy\n * the SafeUrl contract.\n *\n * This regular expression matches a subset of URLs that will not cause script\n * execution if used in URL context within a HTML document. Specifically, this\n * regular expression matches if (comment from here on and regex copied from\n * Soy's EscapingConventions):\n * (1) Either a protocol in a whitelist (http, https, mailto or ftp).\n * (2) or no protocol. A protocol must be followed by a colon. The below\n * allows that by allowing colons only after one of the characters [/?#].\n * A colon after a hash (#) must be in the fragment.\n * Otherwise, a colon after a (?) must be in a query.\n * Otherwise, a colon after a single solidus (/) must be in a path.\n * Otherwise, a colon after a double solidus (//) must be in the authority\n * (before port).\n *\n * @private\n * @const {!RegExp}\n */\ngoog.html.SAFE_URL_PATTERN_ =\n /^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i;\n\n/**\n * Public version of goog.html.SAFE_URL_PATTERN_. Updating\n * goog.html.SAFE_URL_PATTERN_ doesn't seem to be backward compatible.\n * Namespace is also changed to goog.html.SafeUrl so it can be imported using\n * goog.require('goog.dom.SafeUrl').\n *\n * TODO(bangert): Remove SAFE_URL_PATTERN_\n * @const {!RegExp}\n */\ngoog.html.SafeUrl.SAFE_URL_PATTERN = goog.html.SAFE_URL_PATTERN_;\n\n\n/**\n * Creates a SafeUrl object from `url`. If `url` is a\n * goog.html.SafeUrl then it is simply returned. Otherwise the input string is\n * validated to match a pattern of commonly used safe URLs.\n *\n * `url` may be a URL with the http, https, mailto or ftp scheme,\n * or a relative URL (i.e., a URL without a scheme; specifically, a\n * scheme-relative, absolute-path-relative, or path-relative URL).\n *\n * @see http://url.spec.whatwg.org/#concept-relative-url\n * @param {string|!goog.string.TypedString} url The URL to validate.\n * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl.\n */\ngoog.html.SafeUrl.sanitize = function(url) {\n if (url instanceof goog.html.SafeUrl) {\n return url;\n } else if (typeof url == 'object' && url.implementsGoogStringTypedString) {\n url = /** @type {!goog.string.TypedString} */ (url).getTypedStringValue();\n } else {\n url = String(url);\n }\n if (!goog.html.SAFE_URL_PATTERN_.test(url)) {\n url = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);\n};\n\n/**\n * Creates a SafeUrl object from `url`. If `url` is a\n * goog.html.SafeUrl then it is simply returned. Otherwise the input string is\n * validated to match a pattern of commonly used safe URLs.\n *\n * `url` may be a URL with the http, https, mailto or ftp scheme,\n * or a relative URL (i.e., a URL without a scheme; specifically, a\n * scheme-relative, absolute-path-relative, or path-relative URL).\n *\n * This function asserts (using goog.asserts) that the URL matches this pattern.\n * If it does not, in addition to failing the assert, an innocous URL will be\n * returned.\n *\n * @see http://url.spec.whatwg.org/#concept-relative-url\n * @param {string|!goog.string.TypedString} url The URL to validate.\n * @param {boolean=} opt_allowDataUrl Whether to allow valid data: URLs.\n * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl.\n */\ngoog.html.SafeUrl.sanitizeAssertUnchanged = function(url, opt_allowDataUrl) {\n if (url instanceof goog.html.SafeUrl) {\n return url;\n } else if (typeof url == 'object' && url.implementsGoogStringTypedString) {\n url = /** @type {!goog.string.TypedString} */ (url).getTypedStringValue();\n } else {\n url = String(url);\n }\n if (opt_allowDataUrl && /^data:/i.test(url)) {\n var safeUrl = goog.html.SafeUrl.fromDataUrl(url);\n if (safeUrl.getTypedStringValue() == url) {\n return safeUrl;\n }\n }\n if (!goog.asserts.assert(\n goog.html.SAFE_URL_PATTERN_.test(url),\n '%s does not match the safe URL pattern', url)) {\n url = goog.html.SafeUrl.INNOCUOUS_STRING;\n }\n return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url);\n};\n\n\n\n/**\n * Type marker for the SafeUrl type, used to implement additional run-time\n * type checking.\n * @const {!Object}\n * @private\n */\ngoog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};\n\n\n/**\n * Package-internal utility method to create SafeUrl instances.\n *\n * @param {string} url The string to initialize the SafeUrl object with.\n * @return {!goog.html.SafeUrl} The initialized SafeUrl object.\n * @package\n */\ngoog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse = function(\n url) {\n return new goog.html.SafeUrl(\n goog.html.SafeUrl.CONSTRUCTOR_TOKEN_PRIVATE_, url);\n};\n\n\n/**\n * A SafeUrl corresponding to the special about:blank url.\n * @const {!goog.html.SafeUrl}\n */\ngoog.html.SafeUrl.ABOUT_BLANK =\n goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(\n 'about:blank');\n\n/**\n * Token used to ensure that object is created only from this file. No code\n * outside of this file can access this token.\n * @private {!Object}\n * @const\n */\ngoog.html.SafeUrl.CONSTRUCTOR_TOKEN_PRIVATE_ = {};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview The SafeHtml type and its builders.\n *\n * TODO(xtof): Link to document stating type contract.\n */\n\ngoog.provide('goog.html.SafeHtml');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.dom.TagName');\ngoog.require('goog.dom.tags');\ngoog.require('goog.html.SafeScript');\ngoog.require('goog.html.SafeStyle');\ngoog.require('goog.html.SafeStyleSheet');\ngoog.require('goog.html.SafeUrl');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.html.trustedtypes');\ngoog.require('goog.i18n.bidi.Dir');\ngoog.require('goog.i18n.bidi.DirectionalString');\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.object');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.TypedString');\ngoog.require('goog.string.internal');\n\n\n\n/**\n * A string that is safe to use in HTML context in DOM APIs and HTML documents.\n *\n * A SafeHtml is a string-like object that carries the security type contract\n * that its value as a string will not cause untrusted script execution when\n * evaluated as HTML in a browser.\n *\n * Values of this type are guaranteed to be safe to use in HTML contexts,\n * such as, assignment to the innerHTML DOM property, or interpolation into\n * a HTML template in HTML PC_DATA context, in the sense that the use will not\n * result in a Cross-Site-Scripting vulnerability.\n *\n * Instances of this type must be created via the factory methods\n * (`goog.html.SafeHtml.create`, `goog.html.SafeHtml.htmlEscape`),\n * etc and not by invoking its constructor. The constructor intentionally\n * takes no parameters and the type is immutable; hence only a default instance\n * corresponding to the empty string can be obtained via constructor invocation.\n *\n * Note that there is no `goog.html.SafeHtml.fromConstant`. The reason is that\n * the following code would create an unsafe HTML:\n *\n * ```\n * goog.html.SafeHtml.concat(\n * goog.html.SafeHtml.fromConstant(goog.string.Const.from('<script>')),\n * goog.html.SafeHtml.htmlEscape(userInput),\n * goog.html.SafeHtml.fromConstant(goog.string.Const.from('<\\/script>')));\n * ```\n *\n * There's `goog.dom.constHtmlToNode` to create a node from constant strings\n * only.\n *\n * @see goog.html.SafeHtml.create\n * @see goog.html.SafeHtml.htmlEscape\n * @constructor\n * @final\n * @struct\n * @implements {goog.i18n.bidi.DirectionalString}\n * @implements {goog.string.TypedString}\n */\ngoog.html.SafeHtml = function() {\n /**\n * The contained value of this SafeHtml. The field has a purposely ugly\n * name to make (non-compiled) code that attempts to directly access this\n * field stand out.\n * @private {!TrustedHTML|string}\n */\n this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = '';\n\n /**\n * A type marker used to implement additional run-time type checking.\n * @see goog.html.SafeHtml.unwrap\n * @const {!Object}\n * @private\n */\n this.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ =\n goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_;\n\n /**\n * This SafeHtml's directionality, or null if unknown.\n * @private {?goog.i18n.bidi.Dir}\n */\n this.dir_ = null;\n};\n\n\n/**\n * @define {boolean} Whether to strip out error messages or to leave them in.\n */\ngoog.html.SafeHtml.ENABLE_ERROR_MESSAGES =\n goog.define('goog.html.SafeHtml.ENABLE_ERROR_MESSAGES', goog.DEBUG);\n\n\n/**\n * Whether the `style` attribute is supported. Set to false to avoid the byte\n * weight of `goog.html.SafeStyle` where unneeded. An error will be thrown if\n * the `style` attribute is used.\n * @define {boolean}\n */\ngoog.html.SafeHtml.SUPPORT_STYLE_ATTRIBUTE =\n goog.define('goog.html.SafeHtml.SUPPORT_STYLE_ATTRIBUTE', true);\n\n\n/**\n * @override\n * @const\n */\ngoog.html.SafeHtml.prototype.implementsGoogI18nBidiDirectionalString = true;\n\n\n/** @override */\ngoog.html.SafeHtml.prototype.getDirection = function() {\n return this.dir_;\n};\n\n\n/**\n * @override\n * @const\n */\ngoog.html.SafeHtml.prototype.implementsGoogStringTypedString = true;\n\n\n/**\n * Returns this SafeHtml's value as string.\n *\n * IMPORTANT: In code where it is security relevant that an object's type is\n * indeed `SafeHtml`, use `goog.html.SafeHtml.unwrap` instead of\n * this method. If in doubt, assume that it's security relevant. In particular,\n * note that goog.html functions which return a goog.html type do not guarantee\n * that the returned instance is of the right type. For example:\n *\n * <pre>\n * var fakeSafeHtml = new String('fake');\n * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype;\n * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml);\n * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by\n * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml\n * // instanceof goog.html.SafeHtml.\n * </pre>\n *\n * @see goog.html.SafeHtml.unwrap\n * @override\n */\ngoog.html.SafeHtml.prototype.getTypedStringValue = function() {\n return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_.toString();\n};\n\n\nif (goog.DEBUG) {\n /**\n * Returns a debug string-representation of this value.\n *\n * To obtain the actual string value wrapped in a SafeHtml, use\n * `goog.html.SafeHtml.unwrap`.\n *\n * @see goog.html.SafeHtml.unwrap\n * @override\n */\n goog.html.SafeHtml.prototype.toString = function() {\n return 'SafeHtml{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ +\n '}';\n };\n}\n\n\n/**\n * Performs a runtime check that the provided object is indeed a SafeHtml\n * object, and returns its value.\n * @param {!goog.html.SafeHtml} safeHtml The object to extract from.\n * @return {string} The SafeHtml object's contained string, unless the run-time\n * type check fails. In that case, `unwrap` returns an innocuous\n * string, or, if assertions are enabled, throws\n * `goog.asserts.AssertionError`.\n */\ngoog.html.SafeHtml.unwrap = function(safeHtml) {\n return goog.html.SafeHtml.unwrapTrustedHTML(safeHtml).toString();\n};\n\n\n/**\n * Unwraps value as TrustedHTML if supported or as a string if not.\n * @param {!goog.html.SafeHtml} safeHtml\n * @return {!TrustedHTML|string}\n * @see goog.html.SafeHtml.unwrap\n */\ngoog.html.SafeHtml.unwrapTrustedHTML = function(safeHtml) {\n // Perform additional run-time type-checking to ensure that safeHtml is indeed\n // an instance of the expected type. This provides some additional protection\n // against security bugs due to application code that disables type checks.\n // Specifically, the following checks are performed:\n // 1. The object is an instance of the expected type.\n // 2. The object is not an instance of a subclass.\n // 3. The object carries a type marker for the expected type. \"Faking\" an\n // object requires a reference to the type marker, which has names intended\n // to stand out in code reviews.\n if (safeHtml instanceof goog.html.SafeHtml &&\n safeHtml.constructor === goog.html.SafeHtml &&\n safeHtml.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ ===\n goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) {\n return safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_;\n } else {\n goog.asserts.fail('expected object of type SafeHtml, got \\'' +\n safeHtml + '\\' of type ' + goog.typeOf(safeHtml));\n return 'type_error:SafeHtml';\n }\n};\n\n\n/**\n * Shorthand for union of types that can sensibly be converted to strings\n * or might already be SafeHtml (as SafeHtml is a goog.string.TypedString).\n * @private\n * @typedef {string|number|boolean|!goog.string.TypedString|\n * !goog.i18n.bidi.DirectionalString}\n */\ngoog.html.SafeHtml.TextOrHtml_;\n\n\n/**\n * Returns HTML-escaped text as a SafeHtml object.\n *\n * If text is of a type that implements\n * `goog.i18n.bidi.DirectionalString`, the directionality of the new\n * `SafeHtml` object is set to `text`'s directionality, if known.\n * Otherwise, the directionality of the resulting SafeHtml is unknown (i.e.,\n * `null`).\n *\n * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If\n * the parameter is of type SafeHtml it is returned directly (no escaping\n * is done).\n * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.\n */\ngoog.html.SafeHtml.htmlEscape = function(textOrHtml) {\n if (textOrHtml instanceof goog.html.SafeHtml) {\n return textOrHtml;\n }\n var textIsObject = typeof textOrHtml == 'object';\n var dir = null;\n if (textIsObject && textOrHtml.implementsGoogI18nBidiDirectionalString) {\n dir = /** @type {!goog.i18n.bidi.DirectionalString} */ (textOrHtml)\n .getDirection();\n }\n var textAsString;\n if (textIsObject && textOrHtml.implementsGoogStringTypedString) {\n textAsString = /** @type {!goog.string.TypedString} */ (textOrHtml)\n .getTypedStringValue();\n } else {\n textAsString = String(textOrHtml);\n }\n return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n goog.string.internal.htmlEscape(textAsString), dir);\n};\n\n\n/**\n * Returns HTML-escaped text as a SafeHtml object, with newlines changed to\n * &lt;br&gt;.\n * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If\n * the parameter is of type SafeHtml it is returned directly (no escaping\n * is done).\n * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.\n */\ngoog.html.SafeHtml.htmlEscapePreservingNewlines = function(textOrHtml) {\n if (textOrHtml instanceof goog.html.SafeHtml) {\n return textOrHtml;\n }\n var html = goog.html.SafeHtml.htmlEscape(textOrHtml);\n return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n goog.string.internal.newLineToBr(goog.html.SafeHtml.unwrap(html)),\n html.getDirection());\n};\n\n\n/**\n * Returns HTML-escaped text as a SafeHtml object, with newlines changed to\n * &lt;br&gt; and escaping whitespace to preserve spatial formatting. Character\n * entity #160 is used to make it safer for XML.\n * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If\n * the parameter is of type SafeHtml it is returned directly (no escaping\n * is done).\n * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml.\n */\ngoog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces = function(\n textOrHtml) {\n if (textOrHtml instanceof goog.html.SafeHtml) {\n return textOrHtml;\n }\n var html = goog.html.SafeHtml.htmlEscape(textOrHtml);\n return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n goog.string.internal.whitespaceEscape(goog.html.SafeHtml.unwrap(html)),\n html.getDirection());\n};\n\n\n/**\n * Coerces an arbitrary object into a SafeHtml object.\n *\n * If `textOrHtml` is already of type `goog.html.SafeHtml`, the same\n * object is returned. Otherwise, `textOrHtml` is coerced to string, and\n * HTML-escaped. If `textOrHtml` is of a type that implements\n * `goog.i18n.bidi.DirectionalString`, its directionality, if known, is\n * preserved.\n *\n * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text or SafeHtml to\n * coerce.\n * @return {!goog.html.SafeHtml} The resulting SafeHtml object.\n * @deprecated Use goog.html.SafeHtml.htmlEscape.\n */\ngoog.html.SafeHtml.from = goog.html.SafeHtml.htmlEscape;\n\n\n/**\n * @const\n * @private\n */\ngoog.html.SafeHtml.VALID_NAMES_IN_TAG_ = /^[a-zA-Z0-9-]+$/;\n\n\n/**\n * Set of attributes containing URL as defined at\n * http://www.w3.org/TR/html5/index.html#attributes-1.\n * @private @const {!Object<string,boolean>}\n */\ngoog.html.SafeHtml.URL_ATTRIBUTES_ = goog.object.createSet(\n 'action', 'cite', 'data', 'formaction', 'href', 'manifest', 'poster',\n 'src');\n\n\n/**\n * Tags which are unsupported via create(). They might be supported via a\n * tag-specific create method. These are tags which might require a\n * TrustedResourceUrl in one of their attributes or a restricted type for\n * their content.\n * @private @const {!Object<string,boolean>}\n */\ngoog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_ = goog.object.createSet(\n goog.dom.TagName.APPLET, goog.dom.TagName.BASE, goog.dom.TagName.EMBED,\n goog.dom.TagName.IFRAME, goog.dom.TagName.LINK, goog.dom.TagName.MATH,\n goog.dom.TagName.META, goog.dom.TagName.OBJECT, goog.dom.TagName.SCRIPT,\n goog.dom.TagName.STYLE, goog.dom.TagName.SVG, goog.dom.TagName.TEMPLATE);\n\n\n/**\n * @typedef {string|number|goog.string.TypedString|\n * goog.html.SafeStyle.PropertyMap|undefined}\n */\ngoog.html.SafeHtml.AttributeValue;\n\n\n/**\n * Creates a SafeHtml content consisting of a tag with optional attributes and\n * optional content.\n *\n * For convenience tag names and attribute names are accepted as regular\n * strings, instead of goog.string.Const. Nevertheless, you should not pass\n * user-controlled values to these parameters. Note that these parameters are\n * syntactically validated at runtime, and invalid values will result in\n * an exception.\n *\n * Example usage:\n *\n * goog.html.SafeHtml.create('br');\n * goog.html.SafeHtml.create('div', {'class': 'a'});\n * goog.html.SafeHtml.create('p', {}, 'a');\n * goog.html.SafeHtml.create('p', {}, goog.html.SafeHtml.create('br'));\n *\n * goog.html.SafeHtml.create('span', {\n * 'style': {'margin': '0'}\n * });\n *\n * To guarantee SafeHtml's type contract is upheld there are restrictions on\n * attribute values and tag names.\n *\n * - For attributes which contain script code (on*), a goog.string.Const is\n * required.\n * - For attributes which contain style (style), a goog.html.SafeStyle or a\n * goog.html.SafeStyle.PropertyMap is required.\n * - For attributes which are interpreted as URLs (e.g. src, href) a\n * goog.html.SafeUrl, goog.string.Const or string is required. If a string\n * is passed, it will be sanitized with SafeUrl.sanitize().\n * - For tags which can load code or set security relevant page metadata,\n * more specific goog.html.SafeHtml.create*() functions must be used. Tags\n * which are not supported by this function are applet, base, embed, iframe,\n * link, math, object, script, style, svg, and template.\n *\n * @param {!goog.dom.TagName|string} tagName The name of the tag. Only tag names\n * consisting of [a-zA-Z0-9-] are allowed. Tag names documented above are\n * disallowed.\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * Mapping from attribute names to their values. Only attribute names\n * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes\n * the attribute to be omitted.\n * @param {!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to\n * HTML-escape and put inside the tag. This must be empty for void tags\n * like <br>. Array elements are concatenated.\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n * @throws {Error} If invalid tag name, attribute name, or attribute value is\n * provided.\n * @throws {goog.asserts.AssertionError} If content for void tag is provided.\n */\ngoog.html.SafeHtml.create = function(tagName, opt_attributes, opt_content) {\n goog.html.SafeHtml.verifyTagName(String(tagName));\n return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(\n String(tagName), opt_attributes, opt_content);\n};\n\n\n/**\n * Verifies if the tag name is valid and if it doesn't change the context.\n * E.g. STRONG is fine but SCRIPT throws because it changes context. See\n * goog.html.SafeHtml.create for an explanation of allowed tags.\n * @param {string} tagName\n * @throws {Error} If invalid tag name is provided.\n * @package\n */\ngoog.html.SafeHtml.verifyTagName = function(tagName) {\n if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(tagName)) {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'Invalid tag name <' + tagName + '>.' :\n '');\n }\n if (tagName.toUpperCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n\n 'Tag name <' + tagName + '> is not allowed for SafeHtml.' :\n '');\n }\n};\n\n\n/**\n * Creates a SafeHtml representing an iframe tag.\n *\n * This by default restricts the iframe as much as possible by setting the\n * sandbox attribute to the empty string. If the iframe requires less\n * restrictions, set the sandbox attribute as tight as possible, but do not rely\n * on the sandbox as a security feature because it is not supported by older\n * browsers. If a sandbox is essential to security (e.g. for third-party\n * frames), use createSandboxIframe which checks for browser support.\n *\n * @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox\n *\n * @param {?goog.html.TrustedResourceUrl=} opt_src The value of the src\n * attribute. If null or undefined src will not be set.\n * @param {?goog.html.SafeHtml=} opt_srcdoc The value of the srcdoc attribute.\n * If null or undefined srcdoc will not be set.\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * Mapping from attribute names to their values. Only attribute names\n * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes\n * the attribute to be omitted.\n * @param {!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to\n * HTML-escape and put inside the tag. Array elements are concatenated.\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n * @throws {Error} If invalid tag name, attribute name, or attribute value is\n * provided. If opt_attributes contains the src or srcdoc attributes.\n */\ngoog.html.SafeHtml.createIframe = function(\n opt_src, opt_srcdoc, opt_attributes, opt_content) {\n if (opt_src) {\n // Check whether this is really TrustedResourceUrl.\n goog.html.TrustedResourceUrl.unwrap(opt_src);\n }\n\n var fixedAttributes = {};\n fixedAttributes['src'] = opt_src || null;\n fixedAttributes['srcdoc'] =\n opt_srcdoc && goog.html.SafeHtml.unwrap(opt_srcdoc);\n var defaultAttributes = {'sandbox': ''};\n var attributes = goog.html.SafeHtml.combineAttributes(\n fixedAttributes, defaultAttributes, opt_attributes);\n return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(\n 'iframe', attributes, opt_content);\n};\n\n\n/**\n * Creates a SafeHtml representing a sandboxed iframe tag.\n *\n * The sandbox attribute is enforced in its most restrictive mode, an empty\n * string. Consequently, the security requirements for the src and srcdoc\n * attributes are relaxed compared to SafeHtml.createIframe. This function\n * will throw on browsers that do not support the sandbox attribute, as\n * determined by SafeHtml.canUseSandboxIframe.\n *\n * The SafeHtml returned by this function can trigger downloads with no\n * user interaction on Chrome (though only a few, further attempts are blocked).\n * Firefox and IE will block all downloads from the sandbox.\n *\n * @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox\n * @see https://lists.w3.org/Archives/Public/public-whatwg-archive/2013Feb/0112.html\n *\n * @param {string|!goog.html.SafeUrl=} opt_src The value of the src\n * attribute. If null or undefined src will not be set.\n * @param {string=} opt_srcdoc The value of the srcdoc attribute.\n * If null or undefined srcdoc will not be set. Will not be sanitized.\n * @param {!Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * Mapping from attribute names to their values. Only attribute names\n * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes\n * the attribute to be omitted.\n * @param {!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to\n * HTML-escape and put inside the tag. Array elements are concatenated.\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n * @throws {Error} If invalid tag name, attribute name, or attribute value is\n * provided. If opt_attributes contains the src, srcdoc or sandbox\n * attributes. If browser does not support the sandbox attribute on iframe.\n */\ngoog.html.SafeHtml.createSandboxIframe = function(\n opt_src, opt_srcdoc, opt_attributes, opt_content) {\n if (!goog.html.SafeHtml.canUseSandboxIframe()) {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'The browser does not support sandboxed iframes.' :\n '');\n }\n\n var fixedAttributes = {};\n if (opt_src) {\n // Note that sanitize is a no-op on SafeUrl.\n fixedAttributes['src'] =\n goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(opt_src));\n } else {\n fixedAttributes['src'] = null;\n }\n fixedAttributes['srcdoc'] = opt_srcdoc || null;\n fixedAttributes['sandbox'] = '';\n var attributes =\n goog.html.SafeHtml.combineAttributes(fixedAttributes, {}, opt_attributes);\n return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(\n 'iframe', attributes, opt_content);\n};\n\n\n/**\n * Checks if the user agent supports sandboxed iframes.\n * @return {boolean}\n */\ngoog.html.SafeHtml.canUseSandboxIframe = function() {\n return goog.global['HTMLIFrameElement'] &&\n ('sandbox' in goog.global['HTMLIFrameElement'].prototype);\n};\n\n\n/**\n * Creates a SafeHtml representing a script tag with the src attribute.\n * @param {!goog.html.TrustedResourceUrl} src The value of the src\n * attribute.\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=}\n * opt_attributes\n * Mapping from attribute names to their values. Only attribute names\n * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined\n * causes the attribute to be omitted.\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n * @throws {Error} If invalid attribute name or value is provided. If\n * opt_attributes contains the src attribute.\n */\ngoog.html.SafeHtml.createScriptSrc = function(src, opt_attributes) {\n // TODO(mlourenco): The charset attribute should probably be blocked. If\n // its value is attacker controlled, the script contains attacker controlled\n // sub-strings (even if properly escaped) and the server does not set charset\n // then XSS is likely possible.\n // https://html.spec.whatwg.org/multipage/scripting.html#dom-script-charset\n\n // Check whether this is really TrustedResourceUrl.\n goog.html.TrustedResourceUrl.unwrap(src);\n\n var fixedAttributes = {'src': src};\n var defaultAttributes = {};\n var attributes = goog.html.SafeHtml.combineAttributes(\n fixedAttributes, defaultAttributes, opt_attributes);\n return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(\n 'script', attributes);\n};\n\n\n/**\n * Creates a SafeHtml representing a script tag. Does not allow the language,\n * src, text or type attributes to be set.\n * @param {!goog.html.SafeScript|!Array<!goog.html.SafeScript>}\n * script Content to put inside the tag. Array elements are\n * concatenated.\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * Mapping from attribute names to their values. Only attribute names\n * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes\n * the attribute to be omitted.\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n * @throws {Error} If invalid attribute name or attribute value is provided. If\n * opt_attributes contains the language, src, text or type attribute.\n */\ngoog.html.SafeHtml.createScript = function(script, opt_attributes) {\n for (var attr in opt_attributes) {\n var attrLower = attr.toLowerCase();\n if (attrLower == 'language' || attrLower == 'src' || attrLower == 'text' ||\n attrLower == 'type') {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'Cannot set \"' + attrLower + '\" attribute' :\n '');\n }\n }\n\n var content = '';\n script = goog.array.concat(script);\n for (var i = 0; i < script.length; i++) {\n content += goog.html.SafeScript.unwrap(script[i]);\n }\n // Convert to SafeHtml so that it's not HTML-escaped. This is safe because\n // as part of its contract, SafeScript should have no dangerous '<'.\n var htmlContent =\n goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n content, goog.i18n.bidi.Dir.NEUTRAL);\n return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(\n 'script', opt_attributes, htmlContent);\n};\n\n\n/**\n * Creates a SafeHtml representing a style tag. The type attribute is set\n * to \"text/css\".\n * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>}\n * styleSheet Content to put inside the tag. Array elements are\n * concatenated.\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * Mapping from attribute names to their values. Only attribute names\n * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes\n * the attribute to be omitted.\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n * @throws {Error} If invalid attribute name or attribute value is provided. If\n * opt_attributes contains the type attribute.\n */\ngoog.html.SafeHtml.createStyle = function(styleSheet, opt_attributes) {\n var fixedAttributes = {'type': 'text/css'};\n var defaultAttributes = {};\n var attributes = goog.html.SafeHtml.combineAttributes(\n fixedAttributes, defaultAttributes, opt_attributes);\n\n var content = '';\n styleSheet = goog.array.concat(styleSheet);\n for (var i = 0; i < styleSheet.length; i++) {\n content += goog.html.SafeStyleSheet.unwrap(styleSheet[i]);\n }\n // Convert to SafeHtml so that it's not HTML-escaped. This is safe because\n // as part of its contract, SafeStyleSheet should have no dangerous '<'.\n var htmlContent =\n goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n content, goog.i18n.bidi.Dir.NEUTRAL);\n return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(\n 'style', attributes, htmlContent);\n};\n\n\n/**\n * Creates a SafeHtml representing a meta refresh tag.\n * @param {!goog.html.SafeUrl|string} url Where to redirect. If a string is\n * passed, it will be sanitized with SafeUrl.sanitize().\n * @param {number=} opt_secs Number of seconds until the page should be\n * reloaded. Will be set to 0 if unspecified.\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n */\ngoog.html.SafeHtml.createMetaRefresh = function(url, opt_secs) {\n\n // Note that sanitize is a no-op on SafeUrl.\n var unwrappedUrl = goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(url));\n\n if (goog.labs.userAgent.browser.isIE() ||\n goog.labs.userAgent.browser.isEdge()) {\n // IE/EDGE can't parse the content attribute if the url contains a\n // semicolon. We can fix this by adding quotes around the url, but then we\n // can't parse quotes in the URL correctly. Also, it seems that IE/EDGE\n // did not unescape semicolons in these URLs at some point in the past. We\n // take a best-effort approach.\n //\n // If the URL has semicolons (which may happen in some cases, see\n // http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2\n // for instance), wrap it in single quotes to protect the semicolons.\n // If the URL has semicolons and single quotes, url-encode the single quotes\n // as well.\n //\n // This is imperfect. Notice that both ' and ; are reserved characters in\n // URIs, so this could do the wrong thing, but at least it will do the wrong\n // thing in only rare cases.\n if (goog.string.internal.contains(unwrappedUrl, ';')) {\n unwrappedUrl = \"'\" + unwrappedUrl.replace(/'/g, '%27') + \"'\";\n }\n }\n var attributes = {\n 'http-equiv': 'refresh',\n 'content': (opt_secs || 0) + '; url=' + unwrappedUrl\n };\n\n // This function will handle the HTML escaping for attributes.\n return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse(\n 'meta', attributes);\n};\n\n\n/**\n * @param {string} tagName The tag name.\n * @param {string} name The attribute name.\n * @param {!goog.html.SafeHtml.AttributeValue} value The attribute value.\n * @return {string} A \"name=value\" string.\n * @throws {Error} If attribute value is unsafe for the given tag and attribute.\n * @private\n */\ngoog.html.SafeHtml.getAttrNameAndValue_ = function(tagName, name, value) {\n // If it's goog.string.Const, allow any valid attribute name.\n if (value instanceof goog.string.Const) {\n value = goog.string.Const.unwrap(value);\n } else if (name.toLowerCase() == 'style') {\n if (goog.html.SafeHtml.SUPPORT_STYLE_ATTRIBUTE) {\n value = goog.html.SafeHtml.getStyleValue_(value);\n } else {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'Attribute \"style\" not supported.' :\n '');\n }\n } else if (/^on/i.test(name)) {\n // TODO(jakubvrana): Disallow more attributes with a special meaning.\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ? 'Attribute \"' + name +\n '\" requires goog.string.Const value, \"' + value + '\" given.' :\n '');\n // URL attributes handled differently according to tag.\n } else if (name.toLowerCase() in goog.html.SafeHtml.URL_ATTRIBUTES_) {\n if (value instanceof goog.html.TrustedResourceUrl) {\n value = goog.html.TrustedResourceUrl.unwrap(value);\n } else if (value instanceof goog.html.SafeUrl) {\n value = goog.html.SafeUrl.unwrap(value);\n } else if (typeof value === 'string') {\n value = goog.html.SafeUrl.sanitize(value).getTypedStringValue();\n } else {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'Attribute \"' + name + '\" on tag \"' + tagName +\n '\" requires goog.html.SafeUrl, goog.string.Const, or' +\n ' string, value \"' + value + '\" given.' :\n '');\n }\n }\n\n // Accept SafeUrl, TrustedResourceUrl, etc. for attributes which only require\n // HTML-escaping.\n if (value.implementsGoogStringTypedString) {\n // Ok to call getTypedStringValue() since there's no reliance on the type\n // contract for security here.\n value =\n /** @type {!goog.string.TypedString} */ (value).getTypedStringValue();\n }\n\n goog.asserts.assert(\n typeof value === 'string' || typeof value === 'number',\n 'String or number value expected, got ' + (typeof value) +\n ' with value: ' + value);\n return name + '=\"' + goog.string.internal.htmlEscape(String(value)) + '\"';\n};\n\n\n/**\n * Gets value allowed in \"style\" attribute.\n * @param {!goog.html.SafeHtml.AttributeValue} value It could be SafeStyle or a\n * map which will be passed to goog.html.SafeStyle.create.\n * @return {string} Unwrapped value.\n * @throws {Error} If string value is given.\n * @private\n */\ngoog.html.SafeHtml.getStyleValue_ = function(value) {\n if (!goog.isObject(value)) {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'The \"style\" attribute requires goog.html.SafeStyle or map ' +\n 'of style properties, ' + (typeof value) + ' given: ' + value :\n '');\n }\n if (!(value instanceof goog.html.SafeStyle)) {\n // Process the property bag into a style object.\n value = goog.html.SafeStyle.create(value);\n }\n return goog.html.SafeStyle.unwrap(value);\n};\n\n\n/**\n * Creates a SafeHtml content with known directionality consisting of a tag with\n * optional attributes and optional content.\n * @param {!goog.i18n.bidi.Dir} dir Directionality.\n * @param {string} tagName\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * @param {!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content\n * @return {!goog.html.SafeHtml} The SafeHtml content with the tag.\n */\ngoog.html.SafeHtml.createWithDir = function(\n dir, tagName, opt_attributes, opt_content) {\n var html = goog.html.SafeHtml.create(tagName, opt_attributes, opt_content);\n html.dir_ = dir;\n return html;\n};\n\n\n/**\n * Creates a new SafeHtml object by joining the parts with separator.\n * @param {!goog.html.SafeHtml.TextOrHtml_} separator\n * @param {!Array<!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>>} parts Parts to join. If a part\n * contains an array then each member of this array is also joined with the\n * separator.\n * @return {!goog.html.SafeHtml}\n */\ngoog.html.SafeHtml.join = function(separator, parts) {\n var separatorHtml = goog.html.SafeHtml.htmlEscape(separator);\n var dir = separatorHtml.getDirection();\n var content = [];\n\n /**\n * @param {!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>} argument\n */\n var addArgument = function(argument) {\n if (Array.isArray(argument)) {\n goog.array.forEach(argument, addArgument);\n } else {\n var html = goog.html.SafeHtml.htmlEscape(argument);\n content.push(goog.html.SafeHtml.unwrap(html));\n var htmlDir = html.getDirection();\n if (dir == goog.i18n.bidi.Dir.NEUTRAL) {\n dir = htmlDir;\n } else if (htmlDir != goog.i18n.bidi.Dir.NEUTRAL && dir != htmlDir) {\n dir = null;\n }\n }\n };\n\n goog.array.forEach(parts, addArgument);\n return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n content.join(goog.html.SafeHtml.unwrap(separatorHtml)), dir);\n};\n\n\n/**\n * Creates a new SafeHtml object by concatenating values.\n * @param {...(!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Values to concatenate.\n * @return {!goog.html.SafeHtml}\n */\ngoog.html.SafeHtml.concat = function(var_args) {\n return goog.html.SafeHtml.join(\n goog.html.SafeHtml.EMPTY, Array.prototype.slice.call(arguments));\n};\n\n\n/**\n * Creates a new SafeHtml object with known directionality by concatenating the\n * values.\n * @param {!goog.i18n.bidi.Dir} dir Directionality.\n * @param {...(!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Elements of array\n * arguments would be processed recursively.\n * @return {!goog.html.SafeHtml}\n */\ngoog.html.SafeHtml.concatWithDir = function(dir, var_args) {\n var html = goog.html.SafeHtml.concat(goog.array.slice(arguments, 1));\n html.dir_ = dir;\n return html;\n};\n\n\n/**\n * Type marker for the SafeHtml type, used to implement additional run-time\n * type checking.\n * @const {!Object}\n * @private\n */\ngoog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {};\n\n\n/**\n * Package-internal utility method to create SafeHtml instances.\n *\n * @param {string} html The string to initialize the SafeHtml object with.\n * @param {?goog.i18n.bidi.Dir} dir The directionality of the SafeHtml to be\n * constructed, or null if unknown.\n * @return {!goog.html.SafeHtml} The initialized SafeHtml object.\n * @package\n */\ngoog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse = function(\n html, dir) {\n return new goog.html.SafeHtml().initSecurityPrivateDoNotAccessOrElse_(\n html, dir);\n};\n\n\n/**\n * Called from createSafeHtmlSecurityPrivateDoNotAccessOrElse(). This\n * method exists only so that the compiler can dead code eliminate static\n * fields (like EMPTY) when they're not accessed.\n * @param {string} html\n * @param {?goog.i18n.bidi.Dir} dir\n * @return {!goog.html.SafeHtml}\n * @private\n */\ngoog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(\n html, dir) {\n this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ =\n goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY ?\n goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createHTML(\n html) :\n html;\n this.dir_ = dir;\n return this;\n};\n\n\n/**\n * Like create() but does not restrict which tags can be constructed.\n *\n * @param {string} tagName Tag name. Set or validated by caller.\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * @param {(!goog.html.SafeHtml.TextOrHtml_|\n * !Array<!goog.html.SafeHtml.TextOrHtml_>)=} opt_content\n * @return {!goog.html.SafeHtml}\n * @throws {Error} If invalid or unsafe attribute name or value is provided.\n * @throws {goog.asserts.AssertionError} If content for void tag is provided.\n * @package\n */\ngoog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse = function(\n tagName, opt_attributes, opt_content) {\n var dir = null;\n var result = '<' + tagName;\n result += goog.html.SafeHtml.stringifyAttributes(tagName, opt_attributes);\n\n var content = opt_content;\n if (content == null) {\n content = [];\n } else if (!Array.isArray(content)) {\n content = [content];\n }\n\n if (goog.dom.tags.isVoidTag(tagName.toLowerCase())) {\n goog.asserts.assert(\n !content.length, 'Void tag <' + tagName + '> does not allow content.');\n result += '>';\n } else {\n var html = goog.html.SafeHtml.concat(content);\n result += '>' + goog.html.SafeHtml.unwrap(html) + '</' + tagName + '>';\n dir = html.getDirection();\n }\n\n var dirAttribute = opt_attributes && opt_attributes['dir'];\n if (dirAttribute) {\n if (/^(ltr|rtl|auto)$/i.test(dirAttribute)) {\n // If the tag has the \"dir\" attribute specified then its direction is\n // neutral because it can be safely used in any context.\n dir = goog.i18n.bidi.Dir.NEUTRAL;\n } else {\n dir = null;\n }\n }\n\n return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n result, dir);\n};\n\n\n/**\n * Creates a string with attributes to insert after tagName.\n * @param {string} tagName\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * @return {string} Returns an empty string if there are no attributes, returns\n * a string starting with a space otherwise.\n * @throws {Error} If attribute value is unsafe for the given tag and attribute.\n * @package\n */\ngoog.html.SafeHtml.stringifyAttributes = function(tagName, opt_attributes) {\n var result = '';\n if (opt_attributes) {\n for (var name in opt_attributes) {\n if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(name)) {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'Invalid attribute name \"' + name + '\".' :\n '');\n }\n var value = opt_attributes[name];\n if (value == null) {\n continue;\n }\n result +=\n ' ' + goog.html.SafeHtml.getAttrNameAndValue_(tagName, name, value);\n }\n }\n return result;\n};\n\n\n/**\n * @param {!Object<string, ?goog.html.SafeHtml.AttributeValue>} fixedAttributes\n * @param {!Object<string, string>} defaultAttributes\n * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes\n * Optional attributes passed to create*().\n * @return {!Object<string, ?goog.html.SafeHtml.AttributeValue>}\n * @throws {Error} If opt_attributes contains an attribute with the same name\n * as an attribute in fixedAttributes.\n * @package\n */\ngoog.html.SafeHtml.combineAttributes = function(\n fixedAttributes, defaultAttributes, opt_attributes) {\n var combinedAttributes = {};\n var name;\n\n for (name in fixedAttributes) {\n goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case');\n combinedAttributes[name] = fixedAttributes[name];\n }\n for (name in defaultAttributes) {\n goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case');\n combinedAttributes[name] = defaultAttributes[name];\n }\n\n if (opt_attributes) {\n for (name in opt_attributes) {\n var nameLower = name.toLowerCase();\n if (nameLower in fixedAttributes) {\n throw new Error(\n goog.html.SafeHtml.ENABLE_ERROR_MESSAGES ?\n 'Cannot override \"' + nameLower + '\" attribute, got \"' + name +\n '\" with value \"' + opt_attributes[name] + '\"' :\n '');\n }\n if (nameLower in defaultAttributes) {\n delete combinedAttributes[nameLower];\n }\n combinedAttributes[name] = opt_attributes[name];\n }\n }\n\n return combinedAttributes;\n};\n\n\n/**\n * A SafeHtml instance corresponding to the HTML doctype: \"<!DOCTYPE html>\".\n * @const {!goog.html.SafeHtml}\n */\ngoog.html.SafeHtml.DOCTYPE_HTML =\n goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n '<!DOCTYPE html>', goog.i18n.bidi.Dir.NEUTRAL);\n\n\n/**\n * A SafeHtml instance corresponding to the empty string.\n * @const {!goog.html.SafeHtml}\n */\ngoog.html.SafeHtml.EMPTY =\n goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n '', goog.i18n.bidi.Dir.NEUTRAL);\n\n\n/**\n * A SafeHtml instance corresponding to the <br> tag.\n * @const {!goog.html.SafeHtml}\n */\ngoog.html.SafeHtml.BR =\n goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(\n '<br>', goog.i18n.bidi.Dir.NEUTRAL);\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for string manipulation.\n */\n\n\n/**\n * Namespace for string utilities\n */\ngoog.provide('goog.string');\ngoog.provide('goog.string.Unicode');\n\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\n * with detection of double-escaping as this letter is frequently used.\n */\ngoog.string.DETECT_DOUBLE_ESCAPING =\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\n\n\n/**\n * @define {boolean} Whether to force non-dom html unescaping.\n */\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\n\n\n/**\n * Common Unicode string characters.\n * @enum {string}\n */\ngoog.string.Unicode = {\n NBSP: '\\xa0'\n};\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n */\ngoog.string.startsWith = goog.string.internal.startsWith;\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n */\ngoog.string.endsWith = goog.string.internal.endsWith;\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveStartsWith =\n goog.string.internal.caseInsensitiveStartsWith;\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveEndsWith =\n goog.string.internal.caseInsensitiveEndsWith;\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n */\ngoog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;\n\n\n/**\n * Does simple python-style string substitution.\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\n * @param {string} str The string containing the pattern.\n * @param {...*} var_args The items to substitute into the pattern.\n * @return {string} A copy of `str` in which each occurrence of\n * {@code %s} has been replaced an argument from `var_args`.\n */\ngoog.string.subs = function(str, var_args) {\n var splitParts = str.split('%s');\n var returnString = '';\n\n var subsArguments = Array.prototype.slice.call(arguments, 1);\n while (subsArguments.length &&\n // Replace up to the last split part. We are inserting in the\n // positions between split parts.\n splitParts.length > 1) {\n returnString += splitParts.shift() + subsArguments.shift();\n }\n\n return returnString + splitParts.join('%s'); // Join unused '%s'\n};\n\n\n/**\n * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines\n * and tabs) to a single space, and strips leading and trailing whitespace.\n * @param {string} str Input string.\n * @return {string} A copy of `str` with collapsed whitespace.\n */\ngoog.string.collapseWhitespace = function(str) {\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+/g, ' ').replace(/^\\s+|\\s+$/g, '');\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n */\ngoog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is empty.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty.\n */\ngoog.string.isEmptyString = function(str) {\n return str.length == 0;\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n *\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmpty = goog.string.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))\n * instead.\n */\ngoog.string.isEmptyOrWhitespaceSafe = function(str) {\n return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));\n};\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n *\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;\n\n\n/**\n * Checks if a string is all breaking whitespace.\n * @param {string} str The string to check.\n * @return {boolean} Whether the string is all breaking whitespace.\n */\ngoog.string.isBreakingWhitespace = function(str) {\n return !/[^\\t\\n\\r ]/.test(str);\n};\n\n\n/**\n * Checks if a string contains all letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` consists entirely of letters.\n */\ngoog.string.isAlpha = function(str) {\n return !/[^a-zA-Z]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers.\n * @param {*} str string to check. If not a string, it will be\n * casted to one.\n * @return {boolean} True if `str` is numeric.\n */\ngoog.string.isNumeric = function(str) {\n return !/[^0-9]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers or letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` is alphanumeric.\n */\ngoog.string.isAlphaNumeric = function(str) {\n return !/[^a-zA-Z0-9]/.test(str);\n};\n\n\n/**\n * Checks if a character is a space character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a space.\n */\ngoog.string.isSpace = function(ch) {\n return ch == ' ';\n};\n\n\n/**\n * Checks if a character is a valid unicode character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a valid unicode character.\n */\ngoog.string.isUnicodeChar = function(ch) {\n return ch.length == 1 && ch >= ' ' && ch <= '~' ||\n ch >= '\\u0080' && ch <= '\\uFFFD';\n};\n\n\n/**\n * Takes a string and replaces newlines with a space. Multiple lines are\n * replaced with a single space.\n * @param {string} str The string from which to strip newlines.\n * @return {string} A copy of `str` stripped of newlines.\n */\ngoog.string.stripNewlines = function(str) {\n return str.replace(/(\\r\\n|\\r|\\n)+/g, ' ');\n};\n\n\n/**\n * Replaces Windows and Mac new lines with unix style: \\r or \\r\\n with \\n.\n * @param {string} str The string to in which to canonicalize newlines.\n * @return {string} `str` A copy of {@code} with canonicalized newlines.\n */\ngoog.string.canonicalizeNewlines = function(str) {\n return str.replace(/(\\r\\n|\\r|\\n)/g, '\\n');\n};\n\n\n/**\n * Normalizes whitespace in a string, replacing all whitespace chars with\n * a space.\n * @param {string} str The string in which to normalize whitespace.\n * @return {string} A copy of `str` with all whitespace normalized.\n */\ngoog.string.normalizeWhitespace = function(str) {\n return str.replace(/\\xa0|\\s/g, ' ');\n};\n\n\n/**\n * Normalizes spaces in a string, replacing all consecutive spaces and tabs\n * with a single space. Replaces non-breaking space with a space.\n * @param {string} str The string in which to normalize spaces.\n * @return {string} A copy of `str` with all consecutive spaces and tabs\n * replaced with a single space.\n */\ngoog.string.normalizeSpaces = function(str) {\n return str.replace(/\\xa0|[ \\t]+/g, ' ');\n};\n\n\n/**\n * Removes the breaking spaces from the left and right of the string and\n * collapses the sequences of breaking spaces in the middle into single spaces.\n * The original and the result strings render the same way in HTML.\n * @param {string} str A string in which to collapse spaces.\n * @return {string} Copy of the string with normalized breaking spaces.\n */\ngoog.string.collapseBreakingSpaces = function(str) {\n return str.replace(/[\\t\\r\\n ]+/g, ' ')\n .replace(/^[\\t\\r\\n ]+|[\\t\\r\\n ]+$/g, '');\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trim = goog.string.internal.trim;\n\n\n/**\n * Trims whitespaces at the left end of a string.\n * @param {string} str The string to left trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimLeft = function(str) {\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/^[\\s\\xa0]+/, '');\n};\n\n\n/**\n * Trims whitespaces at the right end of a string.\n * @param {string} str The string to right trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimRight = function(str) {\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+$/, '');\n};\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n */\ngoog.string.caseInsensitiveCompare =\n goog.string.internal.caseInsensitiveCompare;\n\n\n/**\n * Compares two strings interpreting their numeric substrings as numbers.\n *\n * @param {string} str1 First string.\n * @param {string} str2 Second string.\n * @param {!RegExp} tokenizerRegExp Splits a string into substrings of\n * non-negative integers, non-numeric characters and optionally fractional\n * numbers starting with a decimal point.\n * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if\n * str1 > str2.\n * @private\n */\ngoog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) {\n if (str1 == str2) {\n return 0;\n }\n if (!str1) {\n return -1;\n }\n if (!str2) {\n return 1;\n }\n\n // Using match to split the entire string ahead of time turns out to be faster\n // for most inputs than using RegExp.exec or iterating over each character.\n var tokens1 = str1.toLowerCase().match(tokenizerRegExp);\n var tokens2 = str2.toLowerCase().match(tokenizerRegExp);\n\n var count = Math.min(tokens1.length, tokens2.length);\n\n for (var i = 0; i < count; i++) {\n var a = tokens1[i];\n var b = tokens2[i];\n\n // Compare pairs of tokens, returning if one token sorts before the other.\n if (a != b) {\n // Only if both tokens are integers is a special comparison required.\n // Decimal numbers are sorted as strings (e.g., '.09' < '.1').\n var num1 = parseInt(a, 10);\n if (!isNaN(num1)) {\n var num2 = parseInt(b, 10);\n if (!isNaN(num2) && num1 - num2) {\n return num1 - num2;\n }\n }\n return a < b ? -1 : 1;\n }\n }\n\n // If one string is a substring of the other, the shorter string sorts first.\n if (tokens1.length != tokens2.length) {\n return tokens1.length - tokens2.length;\n }\n\n // The two strings must be equivalent except for case (perfect equality is\n // tested at the head of the function.) Revert to default ASCII string\n // comparison to stabilize the sort.\n return str1 < str2 ? -1 : 1;\n};\n\n\n/**\n * String comparison function that handles non-negative integer numbers in a\n * way humans might expect. Using this function, the string 'File 2.jpg' sorts\n * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison\n * is mostly case-insensitive, though strings that are identical except for case\n * are sorted with the upper-case strings before lower-case.\n *\n * This comparison function is up to 50x slower than either the default or the\n * case-insensitive compare. It should not be used in time-critical code, but\n * should be fast enough to sort several hundred short strings (like filenames)\n * with a reasonable delay.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.intAwareCompare = function(str1, str2) {\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\D+/g);\n};\n\n\n/**\n * String comparison function that handles non-negative integer and fractional\n * numbers in a way humans might expect. Using this function, the string\n * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent\n * to {@link goog.string.intAwareCompare} apart from the way how it interprets\n * dots.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.floatAwareCompare = function(str1, str2) {\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\.\\d+|\\D+/g);\n};\n\n\n/**\n * Alias for {@link goog.string.floatAwareCompare}.\n *\n * @param {string} str1\n * @param {string} str2\n * @return {number}\n */\ngoog.string.numerateCompare = goog.string.floatAwareCompare;\n\n\n/**\n * URL-encodes a string\n * @param {*} str The string to url-encode.\n * @return {string} An encoded copy of `str` that is safe for urls.\n * Note that '#', ':', and other characters used to delimit portions\n * of URLs *will* be encoded.\n */\ngoog.string.urlEncode = function(str) {\n return encodeURIComponent(String(str));\n};\n\n\n/**\n * URL-decodes the string. We need to specially handle '+'s because\n * the javascript library doesn't convert them to spaces.\n * @param {string} str The string to url decode.\n * @return {string} The decoded `str`.\n */\ngoog.string.urlDecode = function(str) {\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n */\ngoog.string.newLineToBr = goog.string.internal.newLineToBr;\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n *\n * It should be noted that > doesn't need to be escaped for the HTML or XML to\n * be valid, but it has been decided to escape it for consistency with other\n * implementations.\n *\n * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the\n * lowercase letter \"e\".\n *\n * NOTE(user):\n * HtmlEscape is often called during the generation of large blocks of HTML.\n * Using statics for the regular expressions and strings is an optimization\n * that can more than half the amount of time IE spends in this function for\n * large apps, since strings and regexes both contribute to GC allocations.\n *\n * Testing for the presence of a character before escaping increases the number\n * of function calls, but actually provides a speed increase for the average\n * case -- since the average case often doesn't require the escaping of all 4\n * characters and indexOf() is much cheaper than replace().\n * The worst case does suffer slightly from the additional calls, therefore the\n * opt_isLikelyToContainHtmlChars option has been included for situations\n * where all 4 HTML entities are very likely to be present and need escaping.\n *\n * Some benchmarks (times tended to fluctuate +-0.05ms):\n * FireFox IE6\n * (no chars / average (mix of cases) / all 4 chars)\n * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80\n * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84\n * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85\n *\n * An additional advantage of checking if replace actually needs to be called\n * is a reduction in the number of object allocations, so as the size of the\n * application grows the difference between the various methods would increase.\n *\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see\n * if the character needs replacing - use this option if you expect each of\n * the characters to appear often. Leave false if you expect few html\n * characters to occur in your strings, such as if you are escaping HTML.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {\n str = goog.string.internal.htmlEscape(str, opt_isLikelyToContainHtmlChars);\n if (goog.string.DETECT_DOUBLE_ESCAPING) {\n str = str.replace(goog.string.E_RE_, '&#101;');\n }\n return str;\n};\n\n\n/**\n * Regular expression that matches a lowercase letter \"e\", for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.E_RE_ = /e/g;\n\n\n/**\n * Unescapes an HTML string.\n *\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntities = function(str) {\n if (goog.string.contains(str, '&')) {\n // We are careful not to use a DOM if we do not have one or we explicitly\n // requested non-DOM html unescaping.\n if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&\n 'document' in goog.global) {\n return goog.string.unescapeEntitiesUsingDom_(str);\n } else {\n // Fall back on pure XML entities\n return goog.string.unescapePureXmlEntities_(str);\n }\n }\n return str;\n};\n\n\n/**\n * Unescapes a HTML string using the provided document.\n *\n * @param {string} str The string to unescape.\n * @param {!Document} document A document to use in escaping the string.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntitiesWithDocument = function(str, document) {\n if (goog.string.contains(str, '&')) {\n return goog.string.unescapeEntitiesUsingDom_(str, document);\n }\n return str;\n};\n\n\n/**\n * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric\n * entities. This function is XSS-safe and whitespace-preserving.\n * @private\n * @param {string} str The string to unescape.\n * @param {Document=} opt_document An optional document to use for creating\n * elements. If this is not specified then the default window.document\n * will be used.\n * @return {string} The unescaped `str` string.\n */\ngoog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {\n /** @type {!Object<string, string>} */\n var seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"'};\n /** @type {!Element} */\n var div;\n if (opt_document) {\n div = opt_document.createElement('div');\n } else {\n div = goog.global.document.createElement('div');\n }\n // Match as many valid entity characters as possible. If the actual entity\n // happens to be shorter, it will still work as innerHTML will return the\n // trailing characters unchanged. Since the entity characters do not include\n // open angle bracket, there is no chance of XSS from the innerHTML use.\n // Since no whitespace is passed to innerHTML, whitespace is preserved.\n return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {\n // Check for cached entity.\n var value = seen[s];\n if (value) {\n return value;\n }\n // Check for numeric entity.\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex numbers.\n var n = Number('0' + entity.substr(1));\n if (!isNaN(n)) {\n value = String.fromCharCode(n);\n }\n }\n // Fall back to innerHTML otherwise.\n if (!value) {\n // Append a non-entity character to avoid a bug in Webkit that parses\n // an invalid entity at the end of innerHTML text as the empty string.\n goog.dom.safe.setInnerHtml(\n div,\n goog.html.uncheckedconversions\n .safeHtmlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from('Single HTML entity.'), s + ' '));\n // Then remove the trailing character from the result.\n value = div.firstChild.nodeValue.slice(0, -1);\n }\n // Cache and return.\n return seen[s] = value;\n });\n};\n\n\n/**\n * Unescapes XML entities.\n * @private\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapePureXmlEntities_ = function(str) {\n return str.replace(/&([^;]+);/g, function(s, entity) {\n switch (entity) {\n case 'amp':\n return '&';\n case 'lt':\n return '<';\n case 'gt':\n return '>';\n case 'quot':\n return '\"';\n default:\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex.\n var n = Number('0' + entity.substr(1));\n if (!isNaN(n)) {\n return String.fromCharCode(n);\n }\n }\n // For invalid entities we just return the entity\n return s;\n }\n });\n};\n\n\n/**\n * Regular expression that matches an HTML entity.\n * See also HTML5: Tokenization / Tokenizing character references.\n * @private\n * @type {!RegExp}\n */\ngoog.string.HTML_ENTITY_PATTERN_ = /&([^;\\s<&]+);?/g;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.whitespaceEscape = function(str, opt_xml) {\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.newLineToBr(str.replace(/ /g, ' &#160;'), opt_xml);\n};\n\n\n/**\n * Preserve spaces that would be otherwise collapsed in HTML by replacing them\n * with non-breaking space Unicode characters.\n * @param {string} str The string in which to preserve whitespace.\n * @return {string} A copy of `str` with preserved whitespace.\n */\ngoog.string.preserveSpaces = function(str) {\n return str.replace(/(^|[\\n ]) /g, '$1' + goog.string.Unicode.NBSP);\n};\n\n\n/**\n * Strip quote characters around a string. The second argument is a string of\n * characters to treat as quotes. This can be a single character or a string of\n * multiple character and in that case each of those are treated as possible\n * quote characters. For example:\n *\n * <pre>\n * goog.string.stripQuotes('\"abc\"', '\"`') --> 'abc'\n * goog.string.stripQuotes('`abc`', '\"`') --> 'abc'\n * </pre>\n *\n * @param {string} str The string to strip.\n * @param {string} quoteChars The quote characters to strip.\n * @return {string} A copy of `str` without the quotes.\n */\ngoog.string.stripQuotes = function(str, quoteChars) {\n var length = quoteChars.length;\n for (var i = 0; i < length; i++) {\n var quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);\n if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {\n return str.substring(1, str.length - 1);\n }\n }\n return str;\n};\n\n\n/**\n * Truncates a string to a certain length and adds '...' if necessary. The\n * length also accounts for the ellipsis, so a maximum length of 10 and a string\n * 'Hello World!' produces 'Hello W...'.\n * @param {string} str The string to truncate.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cut off in the middle.\n * @return {string} The truncated `str` string.\n */\ngoog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (str.length > chars) {\n str = str.substring(0, chars - 3) + '...';\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Truncate a string in the middle, adding \"...\" if necessary,\n * and favoring the beginning of the string.\n * @param {string} str The string to truncate the middle of.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cutoff in the middle.\n * @param {number=} opt_trailingChars Optional number of trailing characters to\n * leave at the end of the string, instead of truncating as close to the\n * middle as possible.\n * @return {string} A truncated copy of `str`.\n */\ngoog.string.truncateMiddle = function(\n str, chars, opt_protectEscapedCharacters, opt_trailingChars) {\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (opt_trailingChars && str.length > chars) {\n if (opt_trailingChars > chars) {\n opt_trailingChars = chars;\n }\n var endPoint = str.length - opt_trailingChars;\n var startPoint = chars - opt_trailingChars;\n str = str.substring(0, startPoint) + '...' + str.substring(endPoint);\n } else if (str.length > chars) {\n // Favor the beginning of the string:\n var half = Math.floor(chars / 2);\n var endPos = str.length - half;\n half += chars % 2;\n str = str.substring(0, half) + '...' + str.substring(endPos);\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Special chars that need to be escaped for goog.string.quote.\n * @private {!Object<string, string>}\n */\ngoog.string.specialEscapeChars_ = {\n '\\0': '\\\\0',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\x0B': '\\\\x0B', // '\\v' is not supported in JScript\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n // To support the use case of embedding quoted strings inside of script\n // tags, we have to make sure HTML comments and opening/closing script tags do\n // not appear in the resulting string. The specific strings that must be\n // escaped are documented at:\n // https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements\n '<': '\\\\u003C' // NOTE: JSON.parse crashes on '\\\\x3c'.\n};\n\n\n/**\n * Character mappings used internally for goog.string.escapeChar.\n * @private {!Object<string, string>}\n */\ngoog.string.jsEscapeCache_ = {\n '\\'': '\\\\\\''\n};\n\n\n/**\n * Encloses a string in double quotes and escapes characters so that the\n * string is a valid JS string. The resulting string is safe to embed in\n * `<script>` tags as \"<\" is escaped.\n * @param {string} s The string to quote.\n * @return {string} A copy of `s` surrounded by double quotes.\n */\ngoog.string.quote = function(s) {\n s = String(s);\n var sb = ['\"'];\n for (var i = 0; i < s.length; i++) {\n var ch = s.charAt(i);\n var cc = ch.charCodeAt(0);\n sb[i + 1] = goog.string.specialEscapeChars_[ch] ||\n ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));\n }\n sb.push('\"');\n return sb.join('');\n};\n\n\n/**\n * Takes a string and returns the escaped string for that input string.\n * @param {string} str The string to escape.\n * @return {string} An escaped string representing `str`.\n */\ngoog.string.escapeString = function(str) {\n var sb = [];\n for (var i = 0; i < str.length; i++) {\n sb[i] = goog.string.escapeChar(str.charAt(i));\n }\n return sb.join('');\n};\n\n\n/**\n * Takes a character and returns the escaped string for that character. For\n * example escapeChar(String.fromCharCode(15)) -> \"\\\\x0E\".\n * @param {string} c The character to escape.\n * @return {string} An escaped string representing `c`.\n */\ngoog.string.escapeChar = function(c) {\n if (c in goog.string.jsEscapeCache_) {\n return goog.string.jsEscapeCache_[c];\n }\n\n if (c in goog.string.specialEscapeChars_) {\n return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];\n }\n\n var rv = c;\n var cc = c.charCodeAt(0);\n if (cc > 31 && cc < 127) {\n rv = c;\n } else {\n // tab is 9 but handled above\n if (cc < 256) {\n rv = '\\\\x';\n if (cc < 16 || cc > 256) {\n rv += '0';\n }\n } else {\n rv = '\\\\u';\n if (cc < 4096) { // \\u1000\n rv += '0';\n }\n }\n rv += cc.toString(16).toUpperCase();\n }\n\n return goog.string.jsEscapeCache_[c] = rv;\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.contains = goog.string.internal.contains;\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.caseInsensitiveContains =\n goog.string.internal.caseInsensitiveContains;\n\n\n/**\n * Returns the non-overlapping occurrences of ss in s.\n * If either s or ss evalutes to false, then returns zero.\n * @param {string} s The string to look in.\n * @param {string} ss The string to look for.\n * @return {number} Number of occurrences of ss in s.\n */\ngoog.string.countOf = function(s, ss) {\n return s && ss ? s.split(ss).length - 1 : 0;\n};\n\n\n/**\n * Removes a substring of a specified length at a specific\n * index in a string.\n * @param {string} s The base string from which to remove.\n * @param {number} index The index at which to remove the substring.\n * @param {number} stringLength The length of the substring to remove.\n * @return {string} A copy of `s` with the substring removed or the full\n * string if nothing is removed or the input is invalid.\n */\ngoog.string.removeAt = function(s, index, stringLength) {\n var resultStr = s;\n // If the index is greater or equal to 0 then remove substring\n if (index >= 0 && index < s.length && stringLength > 0) {\n resultStr = s.substr(0, index) +\n s.substr(index + stringLength, s.length - index - stringLength);\n }\n return resultStr;\n};\n\n\n/**\n * Removes the first occurrence of a substring from a string.\n * @param {string} str The base string from which to remove.\n * @param {string} substr The string to remove.\n * @return {string} A copy of `str` with `substr` removed or the\n * full string if nothing is removed.\n */\ngoog.string.remove = function(str, substr) {\n return str.replace(substr, '');\n};\n\n\n/**\n * Removes all occurrences of a substring from a string.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to remove.\n * @return {string} A copy of `s` with `ss` removed or the full\n * string if nothing is removed.\n */\ngoog.string.removeAll = function(s, ss) {\n var re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, '');\n};\n\n\n/**\n * Replaces all occurrences of a substring of a string with a new substring.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to replace.\n * @param {string} replacement The replacement string.\n * @return {string} A copy of `s` with `ss` replaced by\n * `replacement` or the original string if nothing is replaced.\n */\ngoog.string.replaceAll = function(s, ss, replacement) {\n var re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, replacement.replace(/\\$/g, '$$$$'));\n};\n\n\n/**\n * Escapes characters in the string that are not safe to use in a RegExp.\n * @param {*} s The string to escape. If not a string, it will be casted\n * to one.\n * @return {string} A RegExp safe, escaped copy of `s`.\n */\ngoog.string.regExpEscape = function(s) {\n return String(s)\n .replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\n .replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * Repeats a string n times.\n * @param {string} string The string to repeat.\n * @param {number} length The number of times to repeat.\n * @return {string} A string containing `length` repetitions of\n * `string`.\n */\ngoog.string.repeat = (String.prototype.repeat) ? function(string, length) {\n // The native method is over 100 times faster than the alternative.\n return string.repeat(length);\n} : function(string, length) {\n return new Array(length + 1).join(string);\n};\n\n\n/**\n * Pads number to given length and optionally rounds it to a given precision.\n * For example:\n * <pre>padNumber(1.25, 2, 3) -> '01.250'\n * padNumber(1.25, 2) -> '01.25'\n * padNumber(1.25, 2, 1) -> '01.3'\n * padNumber(1.25, 0) -> '1.25'</pre>\n *\n * @param {number} num The number to pad.\n * @param {number} length The desired length.\n * @param {number=} opt_precision The desired precision.\n * @return {string} `num` as a string with the given options.\n */\ngoog.string.padNumber = function(num, length, opt_precision) {\n var s =\n (opt_precision !== undefined) ? num.toFixed(opt_precision) : String(num);\n var index = s.indexOf('.');\n if (index == -1) {\n index = s.length;\n }\n return goog.string.repeat('0', Math.max(0, length - index)) + s;\n};\n\n\n/**\n * Returns a string representation of the given object, with\n * null and undefined being returned as the empty string.\n *\n * @param {*} obj The object to convert.\n * @return {string} A string representation of the `obj`.\n */\ngoog.string.makeSafe = function(obj) {\n return obj == null ? '' : String(obj);\n};\n\n\n/**\n * Concatenates string expressions. This is useful\n * since some browsers are very inefficient when it comes to using plus to\n * concat strings. Be careful when using null and undefined here since\n * these will not be included in the result. If you need to represent these\n * be sure to cast the argument to a String first.\n * For example:\n * <pre>buildString('a', 'b', 'c', 'd') -> 'abcd'\n * buildString(null, undefined) -> ''\n * </pre>\n * @param {...*} var_args A list of strings to concatenate. If not a string,\n * it will be casted to one.\n * @return {string} The concatenation of `var_args`.\n */\ngoog.string.buildString = function(var_args) {\n return Array.prototype.join.call(arguments, '');\n};\n\n\n/**\n * Returns a string with at least 64-bits of randomness.\n *\n * Doesn't trust JavaScript's random function entirely. Uses a combination of\n * random and current timestamp, and then encodes the string in base-36 to\n * make it shorter.\n *\n * @return {string} A random string, e.g. sn1s7vb4gcic.\n */\ngoog.string.getRandomString = function() {\n var x = 2147483648;\n return Math.floor(Math.random() * x).toString(36) +\n Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n */\ngoog.string.compareVersions = goog.string.internal.compareVersions;\n\n\n/**\n * String hash function similar to java.lang.String.hashCode().\n * The hash code for a string is computed as\n * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\n * where s[i] is the ith character of the string and n is the length of\n * the string. We mod the result to make it between 0 (inclusive) and 2^32\n * (exclusive).\n * @param {string} str A string.\n * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32\n * (exclusive). The empty string returns 0.\n */\ngoog.string.hashCode = function(str) {\n var result = 0;\n for (var i = 0; i < str.length; ++i) {\n // Normalize to 4 byte range, 0 ... 2^32.\n result = (31 * result + str.charCodeAt(i)) >>> 0;\n }\n return result;\n};\n\n\n/**\n * The most recent unique ID. |0 is equivalent to Math.floor in this case.\n * @type {number}\n * @private\n */\ngoog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;\n\n\n/**\n * Generates and returns a string which is unique in the current document.\n * This is useful, for example, to create unique IDs for DOM elements.\n * @return {string} A unique id.\n */\ngoog.string.createUniqueString = function() {\n return 'goog_' + goog.string.uniqueStringCounter_++;\n};\n\n\n/**\n * Converts the supplied string to a number, which may be Infinity or NaN.\n * This function strips whitespace: (toNumber(' 123') === 123)\n * This function accepts scientific notation: (toNumber('1e1') === 10)\n *\n * This is better than JavaScript's built-in conversions because, sadly:\n * (Number(' ') === 0) and (parseFloat('123a') === 123)\n *\n * @param {string} str The string to convert.\n * @return {number} The number the supplied string represents, or NaN.\n */\ngoog.string.toNumber = function(str) {\n var num = Number(str);\n if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {\n return NaN;\n }\n return num;\n};\n\n\n/**\n * Returns whether the given string is lower camel case (e.g. \"isFooBar\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is lower camel case.\n */\ngoog.string.isLowerCamelCase = function(str) {\n return /^[a-z]+([A-Z][a-z]*)*$/.test(str);\n};\n\n\n/**\n * Returns whether the given string is upper camel case (e.g. \"FooBarBaz\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is upper camel case.\n */\ngoog.string.isUpperCamelCase = function(str) {\n return /^([A-Z][a-z]*)+$/.test(str);\n};\n\n\n/**\n * Converts a string from selector-case to camelCase (e.g. from\n * \"multi-part-string\" to \"multiPartString\"), useful for converting\n * CSS selectors and HTML dataset keys to their equivalent JS properties.\n * @param {string} str The string in selector-case form.\n * @return {string} The string in camelCase form.\n */\ngoog.string.toCamelCase = function(str) {\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\n return match.toUpperCase();\n });\n};\n\n\n/**\n * Converts a string from camelCase to selector-case (e.g. from\n * \"multiPartString\" to \"multi-part-string\"), useful for converting JS\n * style and dataset properties to equivalent CSS selectors and HTML keys.\n * @param {string} str The string in camelCase form.\n * @return {string} The string in selector-case form.\n */\ngoog.string.toSelectorCase = function(str) {\n return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();\n};\n\n\n/**\n * Converts a string into TitleCase. First character of the string is always\n * capitalized in addition to the first letter of every subsequent word.\n * Words are delimited by one or more whitespaces by default. Custom delimiters\n * can optionally be specified to replace the default, which doesn't preserve\n * whitespace delimiters and instead must be explicitly included if needed.\n *\n * Default delimiter => \" \":\n * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three') => 'One Two Three'\n * goog.string.toTitleCase(' one two ') => ' One Two '\n * goog.string.toTitleCase('one_two_three') => 'One_two_three'\n * goog.string.toTitleCase('one-two-three') => 'One-two-three'\n *\n * Custom delimiter => \"_-.\":\n * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three', '_-.') => 'One two three'\n * goog.string.toTitleCase(' one two ', '_-.') => ' one two '\n * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'\n * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'\n * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'\n * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'\n * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'\n *\n * @param {string} str String value in camelCase form.\n * @param {string=} opt_delimiters Custom delimiter character set used to\n * distinguish words in the string value. Each character represents a\n * single delimiter. When provided, default whitespace delimiter is\n * overridden and must be explicitly included if needed.\n * @return {string} String value in TitleCase form.\n */\ngoog.string.toTitleCase = function(str, opt_delimiters) {\n var delimiters = (typeof opt_delimiters === 'string') ?\n goog.string.regExpEscape(opt_delimiters) :\n '\\\\s';\n\n // For IE8, we need to prevent using an empty character set. Otherwise,\n // incorrect matching will occur.\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\n\n var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\n return str.replace(regexp, function(all, p1, p2) {\n return p1 + p2.toUpperCase();\n });\n};\n\n\n/**\n * Capitalizes a string, i.e. converts the first letter to uppercase\n * and all other letters to lowercase, e.g.:\n *\n * goog.string.capitalize('one') => 'One'\n * goog.string.capitalize('ONE') => 'One'\n * goog.string.capitalize('one two') => 'One two'\n *\n * Note that this function does not trim initial whitespace.\n *\n * @param {string} str String value to capitalize.\n * @return {string} String value with first letter in uppercase.\n */\ngoog.string.capitalize = function(str) {\n return String(str.charAt(0)).toUpperCase() +\n String(str.substr(1)).toLowerCase();\n};\n\n\n/**\n * Parse a string in decimal or hexidecimal ('0xFFFF') form.\n *\n * To parse a particular radix, please use parseInt(string, radix) directly. See\n * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt\n *\n * This is a wrapper for the built-in parseInt function that will only parse\n * numbers as base 10 or base 16. Some JS implementations assume strings\n * starting with \"0\" are intended to be octal. ES3 allowed but discouraged\n * this behavior. ES5 forbids it. This function emulates the ES5 behavior.\n *\n * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj\n *\n * @param {string|number|null|undefined} value The value to be parsed.\n * @return {number} The number, parsed. If the string failed to parse, this\n * will be NaN.\n */\ngoog.string.parseInt = function(value) {\n // Force finite numbers to strings.\n if (isFinite(value)) {\n value = String(value);\n }\n\n if (typeof value === 'string') {\n // If the string starts with '0x' or '-0x', parse as hex.\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\n }\n\n return NaN;\n};\n\n\n/**\n * Splits a string on a separator a limited number of times.\n *\n * This implementation is more similar to Python or Java, where the limit\n * parameter specifies the maximum number of splits rather than truncating\n * the number of results.\n *\n * See http://docs.python.org/2/library/stdtypes.html#str.split\n * See JavaDoc: http://goo.gl/F2AsY\n * See Mozilla reference: http://goo.gl/dZdZs\n *\n * @param {string} str String to split.\n * @param {string} separator The separator.\n * @param {number} limit The limit to the number of splits. The resulting array\n * will have a maximum length of limit+1. Negative numbers are the same\n * as zero.\n * @return {!Array<string>} The string, split.\n */\ngoog.string.splitLimit = function(str, separator, limit) {\n var parts = str.split(separator);\n var returnVal = [];\n\n // Only continue doing this while we haven't hit the limit and we have\n // parts left.\n while (limit > 0 && parts.length) {\n returnVal.push(parts.shift());\n limit--;\n }\n\n // If there are remaining parts, append them to the end.\n if (parts.length) {\n returnVal.push(parts.join(separator));\n }\n\n return returnVal;\n};\n\n\n/**\n * Finds the characters to the right of the last instance of any separator\n *\n * This function is similar to goog.string.path.baseName, except it can take a\n * list of characters to split the string on. It will return the rightmost\n * grouping of characters to the right of any separator as a left-to-right\n * oriented string.\n *\n * @see goog.string.path.baseName\n * @param {string} str The string\n * @param {string|!Array<string>} separators A list of separator characters\n * @return {string} The last part of the string with respect to the separators\n */\ngoog.string.lastComponent = function(str, separators) {\n if (!separators) {\n return str;\n } else if (typeof separators == 'string') {\n separators = [separators];\n }\n\n var lastSeparatorIndex = -1;\n for (var i = 0; i < separators.length; i++) {\n if (separators[i] == '') {\n continue;\n }\n var currentSeparatorIndex = str.lastIndexOf(separators[i]);\n if (currentSeparatorIndex > lastSeparatorIndex) {\n lastSeparatorIndex = currentSeparatorIndex;\n }\n }\n if (lastSeparatorIndex == -1) {\n return str;\n }\n return str.slice(lastSeparatorIndex + 1);\n};\n\n\n/**\n * Computes the Levenshtein edit distance between two strings.\n * @param {string} a\n * @param {string} b\n * @return {number} The edit distance between the two strings.\n */\ngoog.string.editDistance = function(a, b) {\n var v0 = [];\n var v1 = [];\n\n if (a == b) {\n return 0;\n }\n\n if (!a.length || !b.length) {\n return Math.max(a.length, b.length);\n }\n\n for (var i = 0; i < b.length + 1; i++) {\n v0[i] = i;\n }\n\n for (var i = 0; i < a.length; i++) {\n v1[0] = i + 1;\n\n for (var j = 0; j < b.length; j++) {\n var cost = Number(a[i] != b[j]);\n // Cost for the substring is the minimum of adding one character, removing\n // one character, or a swap.\n v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);\n }\n\n for (var j = 0; j < v0.length; j++) {\n v0[j] = v1[j];\n }\n }\n\n return v1[b.length];\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Useful compiler idioms.\n */\n\ngoog.provide('goog.reflect');\n\n\n/**\n * Syntax for object literal casts.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an object literal whose keys need to have the same names\n * as the properties of some class even after they are renamed by the compiler.\n *\n * @param {!Function} type Type to cast to.\n * @param {Object} object Object literal to cast.\n * @return {Object} The object literal.\n */\ngoog.reflect.object = function(type, object) {\n return object;\n};\n\n/**\n * Syntax for renaming property strings.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an need to access a property as a string, but want\n * to also have the property renamed by the compiler. In contrast to\n * goog.reflect.object, this method takes an instance of an object.\n *\n * Properties must be simple names (not qualified names).\n *\n * @param {string} prop Name of the property\n * @param {!Object} object Instance of the object whose type will be used\n * for renaming\n * @return {string} The renamed property.\n */\ngoog.reflect.objectProperty = function(prop, object) {\n return prop;\n};\n\n/**\n * To assert to the compiler that an operation is needed when it would\n * otherwise be stripped. For example:\n * <code>\n * // Force a layout\n * goog.reflect.sinkValue(dialog.offsetHeight);\n * </code>\n * @param {T} x\n * @return {T}\n * @template T\n */\ngoog.reflect.sinkValue = function(x) {\n goog.reflect.sinkValue[' '](x);\n return x;\n};\n\n\n/**\n * The compiler should optimize this function away iff no one ever uses\n * goog.reflect.sinkValue.\n */\ngoog.reflect.sinkValue[' '] = goog.nullFunction;\n\n\n/**\n * Check if a property can be accessed without throwing an exception.\n * @param {Object} obj The owner of the property.\n * @param {string} prop The property name.\n * @return {boolean} Whether the property is accessible. Will also return true\n * if obj is null.\n */\ngoog.reflect.canAccessProperty = function(obj, prop) {\n\n try {\n goog.reflect.sinkValue(obj[prop]);\n return true;\n } catch (e) {\n }\n return false;\n};\n\n\n/**\n * Retrieves a value from a cache given a key. The compiler provides special\n * consideration for this call such that it is generally considered side-effect\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\n * then the entire call is considered to have side-effects.\n *\n * Conventionally storing the value on the cache would be considered a\n * side-effect and preclude unused calls from being pruned, ie. even if\n * the value was never used, it would still always be stored in the cache.\n *\n * Providing a side-effect free `valueFn` and `opt_keyFn`\n * allows unused calls to `goog.reflect.cache` to be pruned.\n *\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\n * @param {?} key The key to lookup in the cache. If it is not string or number\n * then a `opt_keyFn` should be provided. The key is also used as the\n * parameter to the `valueFn`.\n * @param {function(?):V} valueFn The value provider to use to calculate the\n * value to store in the cache. This function should be side-effect free\n * to take advantage of the optimization.\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\n * map key. This should be used if the given key is not a string or number.\n * If not provided then the given key is used. This function should be\n * side-effect free to take advantage of the optimization.\n * @return {V} The cached or calculated value.\n * @template K\n * @template V\n */\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\n const storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n return cacheObj[storedKey];\n }\n\n return (cacheObj[storedKey] = valueFn(key));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Rendering engine detection.\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For information on the browser brand (such as Safari versus Chrome), see\n * goog.userAgent.product.\n * @see ../demos/useragent.html\n */\n\ngoog.provide('goog.userAgent');\n\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.labs.userAgent.engine');\ngoog.require('goog.labs.userAgent.platform');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.reflect');\ngoog.require('goog.string');\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is IE.\n */\ngoog.userAgent.ASSUME_IE = goog.define('goog.userAgent.ASSUME_IE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is EDGE,\n * referring to EdgeHTML based Edge.\n */\ngoog.userAgent.ASSUME_EDGE = goog.define('goog.userAgent.ASSUME_EDGE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is GECKO.\n */\ngoog.userAgent.ASSUME_GECKO = goog.define('goog.userAgent.ASSUME_GECKO', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.\n */\ngoog.userAgent.ASSUME_WEBKIT =\n goog.define('goog.userAgent.ASSUME_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is a\n * mobile device running WebKit e.g. iPhone or Android.\n */\ngoog.userAgent.ASSUME_MOBILE_WEBKIT =\n goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is OPERA,\n * referring to Presto-based Opera.\n */\ngoog.userAgent.ASSUME_OPERA = goog.define('goog.userAgent.ASSUME_OPERA', false);\n\n\n/**\n * @define {boolean} Whether the\n * `goog.userAgent.isVersionOrHigher`\n * function will return true for any version.\n */\ngoog.userAgent.ASSUME_ANY_VERSION =\n goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);\n\n\n/**\n * Whether we know the browser engine at compile-time.\n * @type {boolean}\n * @private\n */\ngoog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||\n goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||\n goog.userAgent.ASSUME_OPERA;\n\n\n/**\n * Returns the userAgent string for the current browser.\n *\n * @return {string} The userAgent string.\n */\ngoog.userAgent.getUserAgentString = function() {\n return goog.labs.userAgent.util.getUserAgent();\n};\n\n\n/**\n * @return {?Navigator} The native navigator object.\n */\ngoog.userAgent.getNavigatorTyped = function() {\n // Need a local navigator reference instead of using the global one,\n // to avoid the rare case where they reference different objects.\n // (in a WorkerPool, for example).\n return goog.global['navigator'] || null;\n};\n\n\n/**\n * TODO(nnaze): Change type to \"Navigator\" and update compilation targets.\n * @return {?Object} The native navigator object.\n */\ngoog.userAgent.getNavigator = function() {\n return goog.userAgent.getNavigatorTyped();\n};\n\n\n/**\n * Whether the user agent is Presto-based Opera.\n * @type {boolean}\n */\ngoog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_OPERA :\n goog.labs.userAgent.browser.isOpera();\n\n\n/**\n * Whether the user agent is Internet Explorer.\n * @type {boolean}\n */\ngoog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_IE :\n goog.labs.userAgent.browser.isIE();\n\n\n/**\n * Whether the user agent is Microsoft Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_EDGE :\n goog.labs.userAgent.engine.isEdge();\n\n\n/**\n * Whether the user agent is MS Internet Explorer or MS Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;\n\n\n/**\n * Whether the user agent is Gecko. Gecko is the rendering engine used by\n * Mozilla, Firefox, and others.\n * @type {boolean}\n */\ngoog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_GECKO :\n goog.labs.userAgent.engine.isGecko();\n\n\n/**\n * Whether the user agent is WebKit. WebKit is the rendering engine that\n * Safari, Edge Chromium, Opera Chromium, Android and others use.\n * @type {boolean}\n */\ngoog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :\n goog.labs.userAgent.engine.isWebKit();\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * This is a separate function so that the logic can be tested.\n *\n * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().\n *\n * @return {boolean} Whether the user agent is running on a mobile device.\n * @private\n */\ngoog.userAgent.isMobile_ = function() {\n return goog.userAgent.WEBKIT &&\n goog.labs.userAgent.util.matchUserAgent('Mobile');\n};\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent\n * is promoted as the gecko/webkit logic is likely inaccurate.\n *\n * @type {boolean}\n */\ngoog.userAgent.MOBILE =\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();\n\n\n/**\n * Used while transitioning code to use WEBKIT instead.\n * @type {boolean}\n * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.\n * TODO(nicksantos): Delete this from goog.userAgent.\n */\ngoog.userAgent.SAFARI = goog.userAgent.WEBKIT;\n\n\n/**\n * @return {string} the platform (operating system) the user agent is running\n * on. Default to empty string because navigator.platform may not be defined\n * (on Rhino, for example).\n * @private\n */\ngoog.userAgent.determinePlatform_ = function() {\n var navigator = goog.userAgent.getNavigatorTyped();\n return navigator && navigator.platform || '';\n};\n\n\n/**\n * The platform (operating system) the user agent is running on. Default to\n * empty string because navigator.platform may not be defined (on Rhino, for\n * example).\n * @type {string}\n */\ngoog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Macintosh operating\n * system.\n */\ngoog.userAgent.ASSUME_MAC = goog.define('goog.userAgent.ASSUME_MAC', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Windows operating\n * system.\n */\ngoog.userAgent.ASSUME_WINDOWS =\n goog.define('goog.userAgent.ASSUME_WINDOWS', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Linux operating\n * system.\n */\ngoog.userAgent.ASSUME_LINUX = goog.define('goog.userAgent.ASSUME_LINUX', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a X11 windowing\n * system.\n */\ngoog.userAgent.ASSUME_X11 = goog.define('goog.userAgent.ASSUME_X11', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on Android.\n */\ngoog.userAgent.ASSUME_ANDROID =\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPhone.\n */\ngoog.userAgent.ASSUME_IPHONE =\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPad.\n */\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPod.\n */\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on KaiOS.\n */\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\n\n\n/**\n * @type {boolean}\n * @private\n */\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\n goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||\n goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD;\n\n\n/**\n * Whether the user agent is running on a Macintosh operating system.\n * @type {boolean}\n */\ngoog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_MAC :\n goog.labs.userAgent.platform.isMacintosh();\n\n\n/**\n * Whether the user agent is running on a Windows operating system.\n * @type {boolean}\n */\ngoog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_WINDOWS :\n goog.labs.userAgent.platform.isWindows();\n\n\n/**\n * Whether the user agent is Linux per the legacy behavior of\n * goog.userAgent.LINUX, which considered ChromeOS to also be\n * Linux.\n * @return {boolean}\n * @private\n */\ngoog.userAgent.isLegacyLinux_ = function() {\n return goog.labs.userAgent.platform.isLinux() ||\n goog.labs.userAgent.platform.isChromeOS();\n};\n\n\n/**\n * Whether the user agent is running on a Linux operating system.\n *\n * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,\n * while goog.labs.userAgent.platform considers ChromeOS and\n * Linux to be different OSes.\n *\n * @type {boolean}\n */\ngoog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_LINUX :\n goog.userAgent.isLegacyLinux_();\n\n\n/**\n * @return {boolean} Whether the user agent is an X11 windowing system.\n * @private\n */\ngoog.userAgent.isX11_ = function() {\n var navigator = goog.userAgent.getNavigatorTyped();\n return !!navigator &&\n goog.string.contains(navigator['appVersion'] || '', 'X11');\n};\n\n\n/**\n * Whether the user agent is running on a X11 windowing system.\n * @type {boolean}\n */\ngoog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_X11 :\n goog.userAgent.isX11_();\n\n\n/**\n * Whether the user agent is running on Android.\n * @type {boolean}\n */\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_ANDROID :\n goog.labs.userAgent.platform.isAndroid();\n\n\n/**\n * Whether the user agent is running on an iPhone.\n * @type {boolean}\n */\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPHONE :\n goog.labs.userAgent.platform.isIphone();\n\n\n/**\n * Whether the user agent is running on an iPad.\n * @type {boolean}\n */\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPAD :\n goog.labs.userAgent.platform.isIpad();\n\n\n/**\n * Whether the user agent is running on an iPod.\n * @type {boolean}\n */\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPOD :\n goog.labs.userAgent.platform.isIpod();\n\n\n/**\n * Whether the user agent is running on iOS.\n * @type {boolean}\n */\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD) :\n goog.labs.userAgent.platform.isIos();\n\n/**\n * Whether the user agent is running on KaiOS.\n * @type {boolean}\n */\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_KAIOS :\n goog.labs.userAgent.platform.isKaiOS();\n\n\n/**\n * @return {string} The string that describes the version number of the user\n * agent.\n * @private\n */\ngoog.userAgent.determineVersion_ = function() {\n // All browsers have different ways to detect the version and they all have\n // different naming schemes.\n // version is a string rather than a number because it may contain 'b', 'a',\n // and so on.\n var version = '';\n var arr = goog.userAgent.getVersionRegexResult_();\n if (arr) {\n version = arr ? arr[1] : '';\n }\n\n if (goog.userAgent.IE) {\n // IE9 can be in document mode 9 but be reporting an inconsistent user agent\n // version. If it is identifying as a version lower than 9 we take the\n // documentMode as the version instead. IE8 has similar behavior.\n // It is recommended to set the X-UA-Compatible header to ensure that IE9\n // uses documentMode 9.\n var docMode = goog.userAgent.getDocumentMode_();\n if (docMode != null && docMode > parseFloat(version)) {\n return String(docMode);\n }\n }\n\n return version;\n};\n\n\n/**\n * @return {?IArrayLike<string>|undefined} The version regex matches from\n * parsing the user\n * agent string. These regex statements must be executed inline so they can\n * be compiled out by the closure compiler with the rest of the useragent\n * detection logic when ASSUME_* is specified.\n * @private\n */\ngoog.userAgent.getVersionRegexResult_ = function() {\n var userAgent = goog.userAgent.getUserAgentString();\n if (goog.userAgent.GECKO) {\n return /rv\\:([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.EDGE) {\n return /Edge\\/([\\d\\.]+)/.exec(userAgent);\n }\n if (goog.userAgent.IE) {\n return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.WEBKIT) {\n // WebKit/125.4\n return /WebKit\\/(\\S+)/.exec(userAgent);\n }\n if (goog.userAgent.OPERA) {\n // If none of the above browsers were detected but the browser is Opera, the\n // only string that is of interest is 'Version/<number>'.\n return /(?:Version)[ \\/]?(\\S+)/.exec(userAgent);\n }\n return undefined;\n};\n\n\n/**\n * @return {number|undefined} Returns the document mode (for testing).\n * @private\n */\ngoog.userAgent.getDocumentMode_ = function() {\n // NOTE(user): goog.userAgent may be used in context where there is no DOM.\n var doc = goog.global['document'];\n return doc ? doc['documentMode'] : undefined;\n};\n\n\n/**\n * The version of the user agent. This is a string because it might contain\n * 'b' (as in beta) as well as multiple dots.\n * @type {string}\n */\ngoog.userAgent.VERSION = goog.userAgent.determineVersion_();\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string} v1 Version of first item.\n * @param {string} v2 Version of second item.\n *\n * @return {number} 1 if first argument is higher\n * 0 if arguments are equal\n * -1 if second argument is higher.\n * @deprecated Use goog.string.compareVersions.\n */\ngoog.userAgent.compare = function(v1, v2) {\n return goog.string.compareVersions(v1, v2);\n};\n\n\n/**\n * Cache for {@link goog.userAgent.isVersionOrHigher}.\n * Calls to compareVersions are surprisingly expensive and, as a browser's\n * version number is unlikely to change during a session, we cache the results.\n * @const\n * @private\n */\ngoog.userAgent.isVersionOrHigherCache_ = {};\n\n\n/**\n * Whether the user agent version is higher or the same as the given version.\n * NOTE: When checking the version numbers for Firefox and Safari, be sure to\n * use the engine's version, not the browser's version number. For example,\n * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.\n * Opera and Internet Explorer versions match the product release number.<br>\n * @see <a href=\"http://en.wikipedia.org/wiki/Safari_version_history\">\n * Webkit</a>\n * @see <a href=\"http://en.wikipedia.org/wiki/Gecko_engine\">Gecko</a>\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the user agent version is higher or the same as\n * the given version.\n */\ngoog.userAgent.isVersionOrHigher = function(version) {\n return goog.userAgent.ASSUME_ANY_VERSION ||\n goog.reflect.cache(\n goog.userAgent.isVersionOrHigherCache_, version, function() {\n return goog.string.compareVersions(\n goog.userAgent.VERSION, version) >= 0;\n });\n};\n\n\n/**\n * Deprecated alias to `goog.userAgent.isVersionOrHigher`.\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the user agent version is higher or the same as\n * the given version.\n * @deprecated Use goog.userAgent.isVersionOrHigher().\n */\ngoog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;\n\n\n/**\n * Whether the IE effective document mode is higher or the same as the given\n * document mode version.\n * NOTE: Only for IE, return false for another browser.\n *\n * @param {number} documentMode The document mode version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n */\ngoog.userAgent.isDocumentModeOrHigher = function(documentMode) {\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\n};\n\n\n/**\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\n * @param {number} version The version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\n */\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\n\n\n/**\n * For IE version < 7, documentMode is undefined, so attempt to use the\n * CSS1Compat property to see if we are in standards mode. If we are in\n * standards mode, treat the browser version as the document mode. Otherwise,\n * IE is emulating version 5.\n *\n * NOTE(user): Support for IE < 7 is long gone, so this is now simplified.\n * It returns document.documentMode for IE and undefined for everything else.\n *\n * @type {number|undefined}\n * @const\n */\ngoog.userAgent.DOCUMENT_MODE = (function() {\n var doc = goog.global['document'];\n if (!doc || !goog.userAgent.IE) {\n return undefined;\n }\n return goog.userAgent.getDocumentMode_();\n})();\n","// Copyright 2013 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 Closure user agent detection (Browser).\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For more information on rendering engine, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\n * goog.labs.userAgent.device respectively.)\n */\n\ngoog.provide('goog.labs.userAgent.browser');\n\ngoog.require('goog.array');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.object');\ngoog.require('goog.string.internal');\n\n\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\n// functions.\n\n\n/**\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium\n * based Opera (Opera 15+) is detected as Chrome to avoid unnecessary\n * special casing.\n * @private\n */\ngoog.labs.userAgent.browser.matchOpera_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('Opera');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is IE.\n * @private\n */\ngoog.labs.userAgent.browser.matchIE_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('Trident') ||\n goog.labs.userAgent.util.matchUserAgent('MSIE');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is Edge. This refers to EdgeHTML\n * based Edge.\n * @private\n */\ngoog.labs.userAgent.browser.matchEdgeHtml_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('Edge');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is Chromium based Edge.\n * @private\n */\ngoog.labs.userAgent.browser.matchEdgeChromium_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('Edg/');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is Chromium based Opera.\n * @private\n */\ngoog.labs.userAgent.browser.matchOperaChromium_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('OPR');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is Firefox.\n * @private\n */\ngoog.labs.userAgent.browser.matchFirefox_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('Firefox') ||\n goog.labs.userAgent.util.matchUserAgent('FxiOS');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is Safari.\n * @private\n */\ngoog.labs.userAgent.browser.matchSafari_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('Safari') &&\n !(goog.labs.userAgent.browser.matchChrome_() ||\n goog.labs.userAgent.browser.matchCoast_() ||\n goog.labs.userAgent.browser.matchOpera_() ||\n goog.labs.userAgent.browser.matchEdgeHtml_() ||\n goog.labs.userAgent.browser.matchEdgeChromium_() ||\n goog.labs.userAgent.browser.matchOperaChromium_() ||\n goog.labs.userAgent.browser.matchFirefox_() ||\n goog.labs.userAgent.browser.isSilk() ||\n goog.labs.userAgent.util.matchUserAgent('Android'));\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n * @private\n */\ngoog.labs.userAgent.browser.matchCoast_ = function() {\n return goog.labs.userAgent.util.matchUserAgent('Coast');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is iOS Webview.\n * @private\n */\ngoog.labs.userAgent.browser.matchIosWebview_ = function() {\n // iOS Webview does not show up as Chrome or Safari. Also check for Opera's\n // WebKit-based iOS browser, Coast.\n return (goog.labs.userAgent.util.matchUserAgent('iPad') ||\n goog.labs.userAgent.util.matchUserAgent('iPhone')) &&\n !goog.labs.userAgent.browser.matchSafari_() &&\n !goog.labs.userAgent.browser.matchChrome_() &&\n !goog.labs.userAgent.browser.matchCoast_() &&\n !goog.labs.userAgent.browser.matchFirefox_() &&\n goog.labs.userAgent.util.matchUserAgent('AppleWebKit');\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium browser. This\n * returns true for Chrome, Opera 15+, and Edge Chromium.\n * @private\n */\ngoog.labs.userAgent.browser.matchChrome_ = function() {\n return (goog.labs.userAgent.util.matchUserAgent('Chrome') ||\n goog.labs.userAgent.util.matchUserAgent('CriOS')) &&\n !goog.labs.userAgent.browser.matchEdgeHtml_();\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is the Android browser.\n * @private\n */\ngoog.labs.userAgent.browser.matchAndroidBrowser_ = function() {\n // Android can appear in the user agent string for Chrome on Android.\n // This is not the Android standalone browser if it does.\n return goog.labs.userAgent.util.matchUserAgent('Android') &&\n !(goog.labs.userAgent.browser.isChrome() ||\n goog.labs.userAgent.browser.isFirefox() ||\n goog.labs.userAgent.browser.isOpera() ||\n goog.labs.userAgent.browser.isSilk());\n};\n\n\n/**\n * @return {boolean} Whether the user's browser is Opera.\n */\ngoog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_;\n\n\n/**\n * @return {boolean} Whether the user's browser is IE.\n */\ngoog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_;\n\n\n/**\n * @return {boolean} Whether the user's browser is EdgeHTML based Edge.\n */\ngoog.labs.userAgent.browser.isEdge = goog.labs.userAgent.browser.matchEdgeHtml_;\n\n\n/**\n * @return {boolean} Whether the user's browser is Chromium based Edge.\n */\ngoog.labs.userAgent.browser.isEdgeChromium =\n goog.labs.userAgent.browser.matchEdgeChromium_;\n\n/**\n * @return {boolean} Whether the user's browser is Chromium based Opera.\n */\ngoog.labs.userAgent.browser.isOperaChromium =\n goog.labs.userAgent.browser.matchOperaChromium_;\n\n/**\n * @return {boolean} Whether the user's browser is Firefox.\n */\ngoog.labs.userAgent.browser.isFirefox =\n goog.labs.userAgent.browser.matchFirefox_;\n\n\n/**\n * @return {boolean} Whether the user's browser is Safari.\n */\ngoog.labs.userAgent.browser.isSafari = goog.labs.userAgent.browser.matchSafari_;\n\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\ngoog.labs.userAgent.browser.isCoast = goog.labs.userAgent.browser.matchCoast_;\n\n\n/**\n * @return {boolean} Whether the user's browser is iOS Webview.\n */\ngoog.labs.userAgent.browser.isIosWebview =\n goog.labs.userAgent.browser.matchIosWebview_;\n\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium based browser (\n * Chrome, Blink-based Opera (15+) and Edge Chromium).\n */\ngoog.labs.userAgent.browser.isChrome = goog.labs.userAgent.browser.matchChrome_;\n\n\n/**\n * @return {boolean} Whether the user's browser is the Android browser.\n */\ngoog.labs.userAgent.browser.isAndroidBrowser =\n goog.labs.userAgent.browser.matchAndroidBrowser_;\n\n\n/**\n * For more information, see:\n * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html\n * @return {boolean} Whether the user's browser is Silk.\n */\ngoog.labs.userAgent.browser.isSilk = function() {\n return goog.labs.userAgent.util.matchUserAgent('Silk');\n};\n\n\n/**\n * @return {string} The browser version or empty string if version cannot be\n * determined. Note that for Internet Explorer, this returns the version of\n * the browser, not the version of the rendering engine. (IE 8 in\n * compatibility mode will return 8.0 rather than 7.0. To determine the\n * rendering engine version, look at document.documentMode instead. See\n * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more\n * details.)\n */\ngoog.labs.userAgent.browser.getVersion = function() {\n var userAgentString = goog.labs.userAgent.util.getUserAgent();\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (goog.labs.userAgent.browser.isIE()) {\n return goog.labs.userAgent.browser.getIEVersion_(userAgentString);\n }\n\n var versionTuples =\n goog.labs.userAgent.util.extractVersionTuples(userAgentString);\n\n // Construct a map for easy lookup.\n var versionMap = {};\n goog.array.forEach(versionTuples, function(tuple) {\n // Note that the tuple is of length three, but we only care about the\n // first two.\n var key = tuple[0];\n var value = tuple[1];\n versionMap[key] = value;\n });\n\n var versionMapHasKey = goog.partial(goog.object.containsKey, versionMap);\n\n // Gives the value with the first key it finds, otherwise empty string.\n function lookUpValueWithKeys(keys) {\n var key = goog.array.find(keys, versionMapHasKey);\n return versionMap[key] || '';\n }\n\n // Check Opera before Chrome since Opera 15+ has \"Chrome\" in the string.\n // See\n // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond\n if (goog.labs.userAgent.browser.isOpera()) {\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\" first.\n // Opera uses 'OPR' for more recent UAs.\n return lookUpValueWithKeys(['Version', 'Opera']);\n }\n\n // Check Edge before Chrome since it has Chrome in the string.\n if (goog.labs.userAgent.browser.isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n }\n\n // Check Chromium Edge before Chrome since it has Chrome in the string.\n if (goog.labs.userAgent.browser.isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n\n if (goog.labs.userAgent.browser.isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n\n // Usually products browser versions are in the third tuple after \"Mozilla\"\n // and the engine.\n var tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n};\n\n\n/**\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the browser version is higher or the same as the\n * given version.\n */\ngoog.labs.userAgent.browser.isVersionOrHigher = function(version) {\n return goog.string.internal.compareVersions(\n goog.labs.userAgent.browser.getVersion(), version) >= 0;\n};\n\n\n/**\n * Determines IE version. More information:\n * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString\n * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx\n * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx\n * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx\n *\n * @param {string} userAgent the User-Agent.\n * @return {string}\n * @private\n */\ngoog.labs.userAgent.browser.getIEVersion_ = function(userAgent) {\n // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade\n // bug. Example UA:\n // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)\n // like Gecko.\n // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.\n var rv = /rv: *([\\d\\.]*)/.exec(userAgent);\n if (rv && rv[1]) {\n return rv[1];\n }\n\n var version = '';\n var msie = /MSIE +([\\d\\.]+)/.exec(userAgent);\n if (msie && msie[1]) {\n // IE in compatibility mode usually identifies itself as MSIE 7.0; in this\n // case, use the Trident version to determine the version of IE. For more\n // details, see the links above.\n var tridentVersion = /Trident\\/(\\d.\\d)/.exec(userAgent);\n if (msie[1] == '7.0') {\n if (tridentVersion && tridentVersion[1]) {\n switch (tridentVersion[1]) {\n case '4.0':\n version = '8.0';\n break;\n case '5.0':\n version = '9.0';\n break;\n case '6.0':\n version = '10.0';\n break;\n case '7.0':\n version = '11.0';\n break;\n }\n } else {\n version = '7.0';\n }\n } else {\n version = msie[1];\n }\n }\n return version;\n};\n","// Copyright 2013 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 Closure user agent detection.\n * @see http://en.wikipedia.org/wiki/User_agent\n * For more information on browser brand, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\n */\n\ngoog.provide('goog.labs.userAgent.engine');\n\ngoog.require('goog.array');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.string');\n\n\n/**\n * @return {boolean} Whether the rendering engine is Presto.\n */\ngoog.labs.userAgent.engine.isPresto = function() {\n return goog.labs.userAgent.util.matchUserAgent('Presto');\n};\n\n\n/**\n * @return {boolean} Whether the rendering engine is Trident.\n */\ngoog.labs.userAgent.engine.isTrident = function() {\n // IE only started including the Trident token in IE8.\n return goog.labs.userAgent.util.matchUserAgent('Trident') ||\n goog.labs.userAgent.util.matchUserAgent('MSIE');\n};\n\n\n/**\n * @return {boolean} Whether the rendering engine is EdgeHTML.\n */\ngoog.labs.userAgent.engine.isEdge = function() {\n return goog.labs.userAgent.util.matchUserAgent('Edge');\n};\n\n\n/**\n * @return {boolean} Whether the rendering engine is WebKit. This will return\n * true for Chrome, Blink-based Opera (15+), Edge Chromium and Safari.\n */\ngoog.labs.userAgent.engine.isWebKit = function() {\n return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') &&\n !goog.labs.userAgent.engine.isEdge();\n};\n\n\n/**\n * @return {boolean} Whether the rendering engine is Gecko.\n */\ngoog.labs.userAgent.engine.isGecko = function() {\n return goog.labs.userAgent.util.matchUserAgent('Gecko') &&\n !goog.labs.userAgent.engine.isWebKit() &&\n !goog.labs.userAgent.engine.isTrident() &&\n !goog.labs.userAgent.engine.isEdge();\n};\n\n\n/**\n * @return {string} The rendering engine's version or empty string if version\n * can't be determined.\n */\ngoog.labs.userAgent.engine.getVersion = function() {\n var userAgentString = goog.labs.userAgent.util.getUserAgent();\n if (userAgentString) {\n var tuples = goog.labs.userAgent.util.extractVersionTuples(userAgentString);\n\n var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples);\n if (engineTuple) {\n // In Gecko, the version string is either in the browser info or the\n // Firefox version. See Gecko user agent string reference:\n // http://goo.gl/mULqa\n if (engineTuple[0] == 'Gecko') {\n return goog.labs.userAgent.engine.getVersionForKey_(tuples, 'Firefox');\n }\n\n return engineTuple[1];\n }\n\n // MSIE has only one version identifier, and the Trident version is\n // specified in the parenthetical. IE Edge is covered in the engine tuple\n // detection.\n var browserTuple = tuples[0];\n var info;\n if (browserTuple && (info = browserTuple[2])) {\n var match = /Trident\\/([^\\s;]+)/.exec(info);\n if (match) {\n return match[1];\n }\n }\n }\n return '';\n};\n\n\n/**\n * @param {!Array<!Array<string>>} tuples Extracted version tuples.\n * @return {!Array<string>|undefined} The engine tuple or undefined if not\n * found.\n * @private\n */\ngoog.labs.userAgent.engine.getEngineTuple_ = function(tuples) {\n if (!goog.labs.userAgent.engine.isEdge()) {\n return tuples[1];\n }\n for (var i = 0; i < tuples.length; i++) {\n var tuple = tuples[i];\n if (tuple[0] == 'Edge') {\n return tuple;\n }\n }\n};\n\n\n/**\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the rendering engine version is higher or the same\n * as the given version.\n */\ngoog.labs.userAgent.engine.isVersionOrHigher = function(version) {\n return goog.string.compareVersions(\n goog.labs.userAgent.engine.getVersion(), version) >= 0;\n};\n\n\n/**\n * @param {!Array<!Array<string>>} tuples Version tuples.\n * @param {string} key The key to look for.\n * @return {string} The version string of the given key, if present.\n * Otherwise, the empty string.\n * @private\n */\ngoog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) {\n // TODO(nnaze): Move to util if useful elsewhere.\n\n var pair = goog.array.find(tuples, function(pair) { return key == pair[0]; });\n\n return pair && pair[1] || '';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Browser capability checks for the dom package.\n */\n\n\ngoog.provide('goog.dom.BrowserFeature');\n\ngoog.require('goog.userAgent');\n\n\n/**\n * @define {boolean} Whether we know at compile time that the browser doesn't\n * support OffscreenCanvas.\n */\ngoog.dom.BrowserFeature.ASSUME_NO_OFFSCREEN_CANVAS =\n goog.define('goog.dom.ASSUME_NO_OFFSCREEN_CANVAS', false);\n\n/**\n * @define {boolean} Whether we know at compile time that the browser supports\n * all OffscreenCanvas contexts.\n */\n// TODO(user): Eventually this should default to \"FEATURESET_YEAR >= 202X\".\ngoog.dom.BrowserFeature.ASSUME_OFFSCREEN_CANVAS =\n goog.define('goog.dom.ASSUME_OFFSCREEN_CANVAS', false);\n\n/**\n * Detects if a particular OffscreenCanvas context is supported.\n * @param {string} contextName name of the context to test.\n * @return {boolean} Whether the browser supports this OffscreenCanvas context.\n * @private\n */\ngoog.dom.BrowserFeature.detectOffscreenCanvas_ = function(contextName) {\n // This code only gets removed because we forced @nosideeffects on\n // the functions. See: b/138802376\n try {\n return Boolean(new self.OffscreenCanvas(0, 0).getContext(contextName));\n } catch (ex) {\n }\n return false;\n};\n\n/**\n * Whether the browser supports OffscreenCanvas 2D context.\n * @const {boolean}\n */\ngoog.dom.BrowserFeature.OFFSCREEN_CANVAS_2D =\n !goog.dom.BrowserFeature.ASSUME_NO_OFFSCREEN_CANVAS &&\n (goog.dom.BrowserFeature.ASSUME_OFFSCREEN_CANVAS ||\n goog.dom.BrowserFeature.detectOffscreenCanvas_('2d'));\n\n/**\n * Whether attributes 'name' and 'type' can be added to an element after it's\n * created. False in Internet Explorer prior to version 9.\n * @const {boolean}\n */\ngoog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES =\n !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9);\n\n/**\n * Whether we can use element.children to access an element's Element\n * children. Available since Gecko 1.9.1, IE 9. (IE<9 also includes comment\n * nodes in the collection.)\n * @const {boolean}\n */\ngoog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE =\n !goog.userAgent.GECKO && !goog.userAgent.IE ||\n goog.userAgent.IE && goog.userAgent.isDocumentModeOrHigher(9) ||\n goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9.1');\n\n/**\n * Opera, Safari 3, and Internet Explorer 9 all support innerText but they\n * include text nodes in script and style tags. Not document-mode-dependent.\n * @const {boolean}\n */\ngoog.dom.BrowserFeature.CAN_USE_INNER_TEXT =\n (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'));\n\n/**\n * MSIE, Opera, and Safari>=4 support element.parentElement to access an\n * element's parent if it is an Element.\n * @const {boolean}\n */\ngoog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY =\n goog.userAgent.IE || goog.userAgent.OPERA || goog.userAgent.WEBKIT;\n\n/**\n * Whether NoScope elements need a scoped element written before them in\n * innerHTML.\n * MSDN: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx#1\n * @const {boolean}\n */\ngoog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT = goog.userAgent.IE;\n\n/**\n * Whether we use legacy IE range API.\n * @const {boolean}\n */\ngoog.dom.BrowserFeature.LEGACY_IE_RANGES =\n goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9);\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating the browser's Document Object Model\n * Inspiration taken *heavily* from mochikit (http://mochikit.com/).\n *\n * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer\n * to a different document object. This is useful if you are working with\n * frames or multiple windows.\n *\n * @suppress {strictMissingProperties}\n */\n\n\n// TODO(arv): Rename/refactor getTextContent and getRawTextContent. The problem\n// is that getTextContent should mimic the DOM3 textContent. We should add a\n// getInnerText (or getText) which tries to return the visible text, innerText.\n\n\ngoog.provide('goog.dom');\ngoog.provide('goog.dom.Appendable');\ngoog.provide('goog.dom.DomHelper');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.dom.BrowserFeature');\ngoog.require('goog.dom.NodeType');\ngoog.require('goog.dom.TagName');\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.SafeHtml');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.math.Coordinate');\ngoog.require('goog.math.Size');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.string.Unicode');\ngoog.require('goog.userAgent');\n\n\n/**\n * @define {boolean} Whether we know at compile time that the browser is in\n * quirks mode.\n */\ngoog.dom.ASSUME_QUIRKS_MODE = goog.define('goog.dom.ASSUME_QUIRKS_MODE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile time that the browser is in\n * standards compliance mode.\n */\ngoog.dom.ASSUME_STANDARDS_MODE =\n goog.define('goog.dom.ASSUME_STANDARDS_MODE', false);\n\n\n/**\n * Whether we know the compatibility mode at compile time.\n * @type {boolean}\n * @private\n */\ngoog.dom.COMPAT_MODE_KNOWN_ =\n goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE;\n\n\n/**\n * Gets the DomHelper object for the document where the element resides.\n * @param {(Node|Window)=} opt_element If present, gets the DomHelper for this\n * element.\n * @return {!goog.dom.DomHelper} The DomHelper.\n */\ngoog.dom.getDomHelper = function(opt_element) {\n return opt_element ?\n new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) :\n (goog.dom.defaultDomHelper_ ||\n (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper()));\n};\n\n\n/**\n * Cached default DOM helper.\n * @type {!goog.dom.DomHelper|undefined}\n * @private\n */\ngoog.dom.defaultDomHelper_;\n\n\n/**\n * Gets the document object being used by the dom library.\n * @return {!Document} Document object.\n */\ngoog.dom.getDocument = function() {\n return document;\n};\n\n\n/**\n * Gets an element from the current document by element id.\n *\n * If an Element is passed in, it is returned.\n *\n * @param {string|Element} element Element ID or a DOM node.\n * @return {Element} The element with the given ID, or the node passed in.\n */\ngoog.dom.getElement = function(element) {\n return goog.dom.getElementHelper_(document, element);\n};\n\n\n/**\n * Gets an element by id from the given document (if present).\n * If an element is given, it is returned.\n * @param {!Document} doc\n * @param {string|Element} element Element ID or a DOM node.\n * @return {Element} The resulting element.\n * @private\n */\ngoog.dom.getElementHelper_ = function(doc, element) {\n return typeof element === 'string' ? doc.getElementById(element) : element;\n};\n\n\n/**\n * Gets an element by id, asserting that the element is found.\n *\n * This is used when an element is expected to exist, and should fail with\n * an assertion error if it does not (if assertions are enabled).\n *\n * @param {string} id Element ID.\n * @return {!Element} The element with the given ID, if it exists.\n */\ngoog.dom.getRequiredElement = function(id) {\n return goog.dom.getRequiredElementHelper_(document, id);\n};\n\n\n/**\n * Helper function for getRequiredElementHelper functions, both static and\n * on DomHelper. Asserts the element with the given id exists.\n * @param {!Document} doc\n * @param {string} id\n * @return {!Element} The element with the given ID, if it exists.\n * @private\n */\ngoog.dom.getRequiredElementHelper_ = function(doc, id) {\n // To prevent users passing in Elements as is permitted in getElement().\n goog.asserts.assertString(id);\n var element = goog.dom.getElementHelper_(doc, id);\n element =\n goog.asserts.assertElement(element, 'No element found with id: ' + id);\n return element;\n};\n\n\n/**\n * Alias for getElement.\n * @param {string|Element} element Element ID or a DOM node.\n * @return {Element} The element with the given ID, or the node passed in.\n * @deprecated Use {@link goog.dom.getElement} instead.\n */\ngoog.dom.$ = goog.dom.getElement;\n\n\n/**\n * Gets elements by tag name.\n * @param {!goog.dom.TagName<T>} tagName\n * @param {(!Document|!Element)=} opt_parent Parent element or document where to\n * look for elements. Defaults to document.\n * @return {!NodeList<R>} List of elements. The members of the list are\n * {!Element} if tagName is not a member of goog.dom.TagName or more\n * specific types if it is (e.g. {!HTMLAnchorElement} for\n * goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.getElementsByTagName = function(tagName, opt_parent) {\n var parent = opt_parent || document;\n return parent.getElementsByTagName(String(tagName));\n};\n\n\n/**\n * Looks up elements by both tag and class name, using browser native functions\n * (`querySelectorAll`, `getElementsByTagName` or\n * `getElementsByClassName`) where possible. This function\n * is a useful, if limited, way of collecting a list of DOM elements\n * with certain characteristics. `querySelectorAll` offers a\n * more powerful and general solution which allows matching on CSS3\n * selector expressions.\n *\n * Note that tag names are case sensitive in the SVG namespace, and this\n * function converts opt_tag to uppercase for comparisons. For queries in the\n * SVG namespace you should use querySelector or querySelectorAll instead.\n * https://bugzilla.mozilla.org/show_bug.cgi?id=963870\n * https://bugs.webkit.org/show_bug.cgi?id=83438\n *\n * @see {https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll}\n *\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.\n * @param {?string=} opt_class Optional class name.\n * @param {(Document|Element)=} opt_el Optional element to look in.\n * @return {!IArrayLike<R>} Array-like list of elements (only a length property\n * and numerical indices are guaranteed to exist). The members of the array\n * are {!Element} if opt_tag is not a member of goog.dom.TagName or more\n * specific types if it is (e.g. {!HTMLAnchorElement} for\n * goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) {\n return goog.dom.getElementsByTagNameAndClass_(\n document, opt_tag, opt_class, opt_el);\n};\n\n\n/**\n * Gets the first element matching the tag and the class.\n *\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.\n * @param {?string=} opt_class Optional class name.\n * @param {(Document|Element)=} opt_el Optional element to look in.\n * @return {?R} Reference to a DOM node. The return type is {?Element} if\n * tagName is a string or a more specific type if it is a member of\n * goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.getElementByTagNameAndClass = function(opt_tag, opt_class, opt_el) {\n return goog.dom.getElementByTagNameAndClass_(\n document, opt_tag, opt_class, opt_el);\n};\n\n\n/**\n * Returns a static, array-like list of the elements with the provided\n * className.\n *\n * @param {string} className the name of the class to look for.\n * @param {(Document|Element)=} opt_el Optional element to look in.\n * @return {!IArrayLike<!Element>} The items found with the class name provided.\n */\ngoog.dom.getElementsByClass = function(className, opt_el) {\n var parent = opt_el || document;\n if (goog.dom.canUseQuerySelector_(parent)) {\n return parent.querySelectorAll('.' + className);\n }\n return goog.dom.getElementsByTagNameAndClass_(\n document, '*', className, opt_el);\n};\n\n\n/**\n * Returns the first element with the provided className.\n *\n * @param {string} className the name of the class to look for.\n * @param {Element|Document=} opt_el Optional element to look in.\n * @return {Element} The first item with the class name provided.\n */\ngoog.dom.getElementByClass = function(className, opt_el) {\n var parent = opt_el || document;\n var retVal = null;\n if (parent.getElementsByClassName) {\n retVal = parent.getElementsByClassName(className)[0];\n } else {\n retVal =\n goog.dom.getElementByTagNameAndClass_(document, '*', className, opt_el);\n }\n return retVal || null;\n};\n\n\n/**\n * Ensures an element with the given className exists, and then returns the\n * first element with the provided className.\n *\n * @param {string} className the name of the class to look for.\n * @param {!Element|!Document=} opt_root Optional element or document to look\n * in.\n * @return {!Element} The first item with the class name provided.\n * @throws {goog.asserts.AssertionError} Thrown if no element is found.\n */\ngoog.dom.getRequiredElementByClass = function(className, opt_root) {\n var retValue = goog.dom.getElementByClass(className, opt_root);\n return goog.asserts.assert(\n retValue, 'No element found with className: ' + className);\n};\n\n\n/**\n * Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and\n * fast W3C Selectors API.\n * @param {!(Element|Document)} parent The parent document object.\n * @return {boolean} whether or not we can use parent.querySelector* APIs.\n * @private\n */\ngoog.dom.canUseQuerySelector_ = function(parent) {\n return !!(parent.querySelectorAll && parent.querySelector);\n};\n\n\n/**\n * Helper for `getElementsByTagNameAndClass`.\n * @param {!Document} doc The document to get the elements in.\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.\n * @param {?string=} opt_class Optional class name.\n * @param {(Document|Element)=} opt_el Optional element to look in.\n * @return {!IArrayLike<R>} Array-like list of elements (only a length property\n * and numerical indices are guaranteed to exist). The members of the array\n * are {!Element} if opt_tag is not a member of goog.dom.TagName or more\n * specific types if it is (e.g. {!HTMLAnchorElement} for\n * goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n * @private\n */\ngoog.dom.getElementsByTagNameAndClass_ = function(\n doc, opt_tag, opt_class, opt_el) {\n var parent = opt_el || doc;\n var tagName =\n (opt_tag && opt_tag != '*') ? String(opt_tag).toUpperCase() : '';\n\n if (goog.dom.canUseQuerySelector_(parent) && (tagName || opt_class)) {\n var query = tagName + (opt_class ? '.' + opt_class : '');\n return parent.querySelectorAll(query);\n }\n\n // Use the native getElementsByClassName if available, under the assumption\n // that even when the tag name is specified, there will be fewer elements to\n // filter through when going by class than by tag name\n if (opt_class && parent.getElementsByClassName) {\n var els = parent.getElementsByClassName(opt_class);\n\n if (tagName) {\n var arrayLike = {};\n var len = 0;\n\n // Filter for specific tags if requested.\n for (var i = 0, el; el = els[i]; i++) {\n if (tagName == el.nodeName) {\n arrayLike[len++] = el;\n }\n }\n arrayLike.length = len;\n\n return /** @type {!IArrayLike<!Element>} */ (arrayLike);\n } else {\n return els;\n }\n }\n\n var els = parent.getElementsByTagName(tagName || '*');\n\n if (opt_class) {\n var arrayLike = {};\n var len = 0;\n for (var i = 0, el; el = els[i]; i++) {\n var className = el.className;\n // Check if className has a split function since SVG className does not.\n if (typeof className.split == 'function' &&\n goog.array.contains(className.split(/\\s+/), opt_class)) {\n arrayLike[len++] = el;\n }\n }\n arrayLike.length = len;\n return /** @type {!IArrayLike<!Element>} */ (arrayLike);\n } else {\n return els;\n }\n};\n\n\n/**\n * Helper for goog.dom.getElementByTagNameAndClass.\n *\n * @param {!Document} doc The document to get the elements in.\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.\n * @param {?string=} opt_class Optional class name.\n * @param {(Document|Element)=} opt_el Optional element to look in.\n * @return {?R} Reference to a DOM node. The return type is {?Element} if\n * tagName is a string or a more specific type if it is a member of\n * goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n * @private\n */\ngoog.dom.getElementByTagNameAndClass_ = function(\n doc, opt_tag, opt_class, opt_el) {\n var parent = opt_el || doc;\n var tag = (opt_tag && opt_tag != '*') ? String(opt_tag).toUpperCase() : '';\n if (goog.dom.canUseQuerySelector_(parent) && (tag || opt_class)) {\n return parent.querySelector(tag + (opt_class ? '.' + opt_class : ''));\n }\n var elements =\n goog.dom.getElementsByTagNameAndClass_(doc, opt_tag, opt_class, opt_el);\n return elements[0] || null;\n};\n\n\n\n/**\n * Alias for `getElementsByTagNameAndClass`.\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.\n * @param {?string=} opt_class Optional class name.\n * @param {Element=} opt_el Optional element to look in.\n * @return {!IArrayLike<R>} Array-like list of elements (only a length property\n * and numerical indices are guaranteed to exist). The members of the array\n * are {!Element} if opt_tag is not a member of goog.dom.TagName or more\n * specific types if it is (e.g. {!HTMLAnchorElement} for\n * goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n * @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead.\n */\ngoog.dom.$$ = goog.dom.getElementsByTagNameAndClass;\n\n\n/**\n * Sets multiple properties, and sometimes attributes, on an element. Note that\n * properties are simply object properties on the element instance, while\n * attributes are visible in the DOM. Many properties map to attributes with the\n * same names, some with different names, and there are also unmappable cases.\n *\n * This method sets properties by default (which means that custom attributes\n * are not supported). These are the exeptions (some of which is legacy):\n * - \"style\": Even though this is an attribute name, it is translated to a\n * property, \"style.cssText\". Note that this property sanitizes and formats\n * its value, unlike the attribute.\n * - \"class\": This is an attribute name, it is translated to the \"className\"\n * property.\n * - \"for\": This is an attribute name, it is translated to the \"htmlFor\"\n * property.\n * - Entries in {@see goog.dom.DIRECT_ATTRIBUTE_MAP_} are set as attributes,\n * this is probably due to browser quirks.\n * - \"aria-*\", \"data-*\": Always set as attributes, they have no property\n * counterparts.\n *\n * @param {Element} element DOM node to set properties on.\n * @param {Object} properties Hash of property:value pairs.\n * Property values can be strings or goog.string.TypedString values (such as\n * goog.html.SafeUrl).\n */\ngoog.dom.setProperties = function(element, properties) {\n goog.object.forEach(properties, function(val, key) {\n if (val && typeof val == 'object' && val.implementsGoogStringTypedString) {\n val = val.getTypedStringValue();\n }\n if (key == 'style') {\n element.style.cssText = val;\n } else if (key == 'class') {\n element.className = val;\n } else if (key == 'for') {\n element.htmlFor = val;\n } else if (goog.dom.DIRECT_ATTRIBUTE_MAP_.hasOwnProperty(key)) {\n element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val);\n } else if (\n goog.string.startsWith(key, 'aria-') ||\n goog.string.startsWith(key, 'data-')) {\n element.setAttribute(key, val);\n } else {\n element[key] = val;\n }\n });\n};\n\n\n/**\n * Map of attributes that should be set using\n * element.setAttribute(key, val) instead of element[key] = val. Used\n * by goog.dom.setProperties.\n *\n * @private {!Object<string, string>}\n * @const\n */\ngoog.dom.DIRECT_ATTRIBUTE_MAP_ = {\n 'cellpadding': 'cellPadding',\n 'cellspacing': 'cellSpacing',\n 'colspan': 'colSpan',\n 'frameborder': 'frameBorder',\n 'height': 'height',\n 'maxlength': 'maxLength',\n 'nonce': 'nonce',\n 'role': 'role',\n 'rowspan': 'rowSpan',\n 'type': 'type',\n 'usemap': 'useMap',\n 'valign': 'vAlign',\n 'width': 'width'\n};\n\n\n/**\n * Gets the dimensions of the viewport.\n *\n * Gecko Standards mode:\n * docEl.clientWidth Width of viewport excluding scrollbar.\n * win.innerWidth Width of viewport including scrollbar.\n * body.clientWidth Width of body element.\n *\n * docEl.clientHeight Height of viewport excluding scrollbar.\n * win.innerHeight Height of viewport including scrollbar.\n * body.clientHeight Height of document.\n *\n * Gecko Backwards compatible mode:\n * docEl.clientWidth Width of viewport excluding scrollbar.\n * win.innerWidth Width of viewport including scrollbar.\n * body.clientWidth Width of viewport excluding scrollbar.\n *\n * docEl.clientHeight Height of document.\n * win.innerHeight Height of viewport including scrollbar.\n * body.clientHeight Height of viewport excluding scrollbar.\n *\n * IE6/7 Standards mode:\n * docEl.clientWidth Width of viewport excluding scrollbar.\n * win.innerWidth Undefined.\n * body.clientWidth Width of body element.\n *\n * docEl.clientHeight Height of viewport excluding scrollbar.\n * win.innerHeight Undefined.\n * body.clientHeight Height of document element.\n *\n * IE5 + IE6/7 Backwards compatible mode:\n * docEl.clientWidth 0.\n * win.innerWidth Undefined.\n * body.clientWidth Width of viewport excluding scrollbar.\n *\n * docEl.clientHeight 0.\n * win.innerHeight Undefined.\n * body.clientHeight Height of viewport excluding scrollbar.\n *\n * Opera 9 Standards and backwards compatible mode:\n * docEl.clientWidth Width of viewport excluding scrollbar.\n * win.innerWidth Width of viewport including scrollbar.\n * body.clientWidth Width of viewport excluding scrollbar.\n *\n * docEl.clientHeight Height of document.\n * win.innerHeight Height of viewport including scrollbar.\n * body.clientHeight Height of viewport excluding scrollbar.\n *\n * WebKit:\n * Safari 2\n * docEl.clientHeight Same as scrollHeight.\n * docEl.clientWidth Same as innerWidth.\n * win.innerWidth Width of viewport excluding scrollbar.\n * win.innerHeight Height of the viewport including scrollbar.\n * frame.innerHeight Height of the viewport exluding scrollbar.\n *\n * Safari 3 (tested in 522)\n *\n * docEl.clientWidth Width of viewport excluding scrollbar.\n * docEl.clientHeight Height of viewport excluding scrollbar in strict mode.\n * body.clientHeight Height of viewport excluding scrollbar in quirks mode.\n *\n * @param {Window=} opt_window Optional window element to test.\n * @return {!goog.math.Size} Object with values 'width' and 'height'.\n */\ngoog.dom.getViewportSize = function(opt_window) {\n // TODO(arv): This should not take an argument\n return goog.dom.getViewportSize_(opt_window || window);\n};\n\n\n/**\n * Helper for `getViewportSize`.\n * @param {Window} win The window to get the view port size for.\n * @return {!goog.math.Size} Object with values 'width' and 'height'.\n * @private\n */\ngoog.dom.getViewportSize_ = function(win) {\n var doc = win.document;\n var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body;\n return new goog.math.Size(el.clientWidth, el.clientHeight);\n};\n\n\n/**\n * Calculates the height of the document.\n *\n * @return {number} The height of the current document.\n */\ngoog.dom.getDocumentHeight = function() {\n return goog.dom.getDocumentHeight_(window);\n};\n\n/**\n * Calculates the height of the document of the given window.\n *\n * @param {!Window} win The window whose document height to retrieve.\n * @return {number} The height of the document of the given window.\n */\ngoog.dom.getDocumentHeightForWindow = function(win) {\n return goog.dom.getDocumentHeight_(win);\n};\n\n/**\n * Calculates the height of the document of the given window.\n *\n * Function code copied from the opensocial gadget api:\n * gadgets.window.adjustHeight(opt_height)\n *\n * @private\n * @param {!Window} win The window whose document height to retrieve.\n * @return {number} The height of the document of the given window.\n */\ngoog.dom.getDocumentHeight_ = function(win) {\n // NOTE(eae): This method will return the window size rather than the document\n // size in webkit quirks mode.\n var doc = win.document;\n var height = 0;\n\n if (doc) {\n // Calculating inner content height is hard and different between\n // browsers rendering in Strict vs. Quirks mode. We use a combination of\n // three properties within document.body and document.documentElement:\n // - scrollHeight\n // - offsetHeight\n // - clientHeight\n // These values differ significantly between browsers and rendering modes.\n // But there are patterns. It just takes a lot of time and persistence\n // to figure out.\n\n var body = doc.body;\n var docEl = /** @type {!HTMLElement} */ (doc.documentElement);\n if (!(docEl && body)) {\n return 0;\n }\n\n // Get the height of the viewport\n var vh = goog.dom.getViewportSize_(win).height;\n if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) {\n // In Strict mode:\n // The inner content height is contained in either:\n // document.documentElement.scrollHeight\n // document.documentElement.offsetHeight\n // Based on studying the values output by different browsers,\n // use the value that's NOT equal to the viewport height found above.\n height =\n docEl.scrollHeight != vh ? docEl.scrollHeight : docEl.offsetHeight;\n } else {\n // In Quirks mode:\n // documentElement.clientHeight is equal to documentElement.offsetHeight\n // except in IE. In most browsers, document.documentElement can be used\n // to calculate the inner content height.\n // However, in other browsers (e.g. IE), document.body must be used\n // instead. How do we know which one to use?\n // If document.documentElement.clientHeight does NOT equal\n // document.documentElement.offsetHeight, then use document.body.\n var sh = docEl.scrollHeight;\n var oh = docEl.offsetHeight;\n if (docEl.clientHeight != oh) {\n sh = body.scrollHeight;\n oh = body.offsetHeight;\n }\n\n // Detect whether the inner content height is bigger or smaller\n // than the bounding box (viewport). If bigger, take the larger\n // value. If smaller, take the smaller value.\n if (sh > vh) {\n // Content is larger\n height = sh > oh ? sh : oh;\n } else {\n // Content is smaller\n height = sh < oh ? sh : oh;\n }\n }\n }\n\n return height;\n};\n\n\n/**\n * Gets the page scroll distance as a coordinate object.\n *\n * @param {Window=} opt_window Optional window element to test.\n * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.\n * @deprecated Use {@link goog.dom.getDocumentScroll} instead.\n */\ngoog.dom.getPageScroll = function(opt_window) {\n var win = opt_window || goog.global || window;\n return goog.dom.getDomHelper(win.document).getDocumentScroll();\n};\n\n\n/**\n * Gets the document scroll distance as a coordinate object.\n *\n * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.\n */\ngoog.dom.getDocumentScroll = function() {\n return goog.dom.getDocumentScroll_(document);\n};\n\n\n/**\n * Helper for `getDocumentScroll`.\n *\n * @param {!Document} doc The document to get the scroll for.\n * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.\n * @private\n */\ngoog.dom.getDocumentScroll_ = function(doc) {\n var el = goog.dom.getDocumentScrollElement_(doc);\n var win = goog.dom.getWindow_(doc);\n if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('10') &&\n win.pageYOffset != el.scrollTop) {\n // The keyboard on IE10 touch devices shifts the page using the pageYOffset\n // without modifying scrollTop. For this case, we want the body scroll\n // offsets.\n return new goog.math.Coordinate(el.scrollLeft, el.scrollTop);\n }\n return new goog.math.Coordinate(\n win.pageXOffset || el.scrollLeft, win.pageYOffset || el.scrollTop);\n};\n\n\n/**\n * Gets the document scroll element.\n * @return {!Element} Scrolling element.\n */\ngoog.dom.getDocumentScrollElement = function() {\n return goog.dom.getDocumentScrollElement_(document);\n};\n\n\n/**\n * Helper for `getDocumentScrollElement`.\n * @param {!Document} doc The document to get the scroll element for.\n * @return {!Element} Scrolling element.\n * @private\n */\ngoog.dom.getDocumentScrollElement_ = function(doc) {\n // Old WebKit needs body.scrollLeft in both quirks mode and strict mode. We\n // also default to the documentElement if the document does not have a body\n // (e.g. a SVG document).\n // Uses http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement to\n // avoid trying to guess about browser behavior from the UA string.\n if (doc.scrollingElement) {\n return doc.scrollingElement;\n }\n if (!goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc)) {\n return doc.documentElement;\n }\n return doc.body || doc.documentElement;\n};\n\n\n/**\n * Gets the window object associated with the given document.\n *\n * @param {Document=} opt_doc Document object to get window for.\n * @return {!Window} The window associated with the given document.\n */\ngoog.dom.getWindow = function(opt_doc) {\n // TODO(arv): This should not take an argument.\n return opt_doc ? goog.dom.getWindow_(opt_doc) : window;\n};\n\n\n/**\n * Helper for `getWindow`.\n *\n * @param {!Document} doc Document object to get window for.\n * @return {!Window} The window associated with the given document.\n * @private\n */\ngoog.dom.getWindow_ = function(doc) {\n return /** @type {!Window} */ (doc.parentWindow || doc.defaultView);\n};\n\n\n/**\n * Returns a dom node with a set of attributes. This function accepts varargs\n * for subsequent nodes to be added. Subsequent nodes will be added to the\n * first node as childNodes.\n *\n * So:\n * <code>createDom(goog.dom.TagName.DIV, null, createDom(goog.dom.TagName.P),\n * createDom(goog.dom.TagName.P));</code> would return a div with two child\n * paragraphs\n *\n * This function uses {@link goog.dom.setProperties} to set attributes: the\n * `opt_attributes` parameter follows the same rules.\n *\n * @param {string|!goog.dom.TagName<T>} tagName Tag to create.\n * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map\n * of name-value pairs for attributes. If a string, then this is the\n * className of the new element. If an array, the elements will be joined\n * together as the className of the new element.\n * @param {...(Object|string|Array|NodeList|null|undefined)} var_args Further\n * DOM nodes or strings for text nodes. If one of the var_args is an array\n * or NodeList, its elements will be added as childNodes instead.\n * @return {R} Reference to a DOM node. The return type is {!Element} if tagName\n * is a string or a more specific type if it is a member of\n * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.createDom = function(tagName, opt_attributes, var_args) {\n return goog.dom.createDom_(document, arguments);\n};\n\n\n/**\n * Helper for `createDom`.\n * @param {!Document} doc The document to create the DOM in.\n * @param {!Arguments} args Argument object passed from the callers. See\n * `goog.dom.createDom` for details.\n * @return {!Element} Reference to a DOM node.\n * @private\n */\ngoog.dom.createDom_ = function(doc, args) {\n var tagName = String(args[0]);\n var attributes = args[1];\n\n // Internet Explorer is dumb:\n // name: https://msdn.microsoft.com/en-us/library/ms534184(v=vs.85).aspx\n // type: https://msdn.microsoft.com/en-us/library/ms534700(v=vs.85).aspx\n // Also does not allow setting of 'type' attribute on 'input' or 'button'.\n if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes &&\n (attributes.name || attributes.type)) {\n var tagNameArr = ['<', tagName];\n if (attributes.name) {\n tagNameArr.push(' name=\"', goog.string.htmlEscape(attributes.name), '\"');\n }\n if (attributes.type) {\n tagNameArr.push(' type=\"', goog.string.htmlEscape(attributes.type), '\"');\n\n // Clone attributes map to remove 'type' without mutating the input.\n var clone = {};\n goog.object.extend(clone, attributes);\n\n // JSCompiler can't see how goog.object.extend added this property,\n // because it was essentially added by reflection.\n // So it needs to be quoted.\n delete clone['type'];\n\n attributes = clone;\n }\n tagNameArr.push('>');\n tagName = tagNameArr.join('');\n }\n\n var element = goog.dom.createElement_(doc, tagName);\n\n if (attributes) {\n if (typeof attributes === 'string') {\n element.className = attributes;\n } else if (Array.isArray(attributes)) {\n element.className = attributes.join(' ');\n } else {\n goog.dom.setProperties(element, attributes);\n }\n }\n\n if (args.length > 2) {\n goog.dom.append_(doc, element, args, 2);\n }\n\n return element;\n};\n\n\n/**\n * Appends a node with text or other nodes.\n * @param {!Document} doc The document to create new nodes in.\n * @param {!Node} parent The node to append nodes to.\n * @param {!Arguments} args The values to add. See `goog.dom.append`.\n * @param {number} startIndex The index of the array to start from.\n * @private\n */\ngoog.dom.append_ = function(doc, parent, args, startIndex) {\n function childHandler(child) {\n // TODO(user): More coercion, ala MochiKit?\n if (child) {\n parent.appendChild(\n typeof child === 'string' ? doc.createTextNode(child) : child);\n }\n }\n\n for (var i = startIndex; i < args.length; i++) {\n var arg = args[i];\n // TODO(attila): Fix isArrayLike to return false for a text node.\n if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {\n // If the argument is a node list, not a real array, use a clone,\n // because forEach can't be used to mutate a NodeList.\n goog.array.forEach(\n goog.dom.isNodeList(arg) ? goog.array.toArray(arg) : arg,\n childHandler);\n } else {\n childHandler(arg);\n }\n }\n};\n\n\n/**\n * Alias for `createDom`.\n * @param {string|!goog.dom.TagName<T>} tagName Tag to create.\n * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map\n * of name-value pairs for attributes. If a string, then this is the\n * className of the new element. If an array, the elements will be joined\n * together as the className of the new element.\n * @param {...(Object|string|Array|NodeList|null|undefined)} var_args Further\n * DOM nodes or strings for text nodes. If one of the var_args is an array,\n * its children will be added as childNodes instead.\n * @return {R} Reference to a DOM node. The return type is {!Element} if tagName\n * is a string or a more specific type if it is a member of\n * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n * @deprecated Use {@link goog.dom.createDom} instead.\n */\ngoog.dom.$dom = goog.dom.createDom;\n\n\n/**\n * Creates a new element.\n * @param {string|!goog.dom.TagName<T>} name Tag to create.\n * @return {R} The new element. The return type is {!Element} if name is\n * a string or a more specific type if it is a member of goog.dom.TagName\n * (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.createElement = function(name) {\n return goog.dom.createElement_(document, name);\n};\n\n\n/**\n * Creates a new element.\n * @param {!Document} doc The document to create the element in.\n * @param {string|!goog.dom.TagName<T>} name Tag to create.\n * @return {R} The new element. The return type is {!Element} if name is\n * a string or a more specific type if it is a member of goog.dom.TagName\n * (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n * @private\n */\ngoog.dom.createElement_ = function(doc, name) {\n name = String(name);\n if (doc.contentType === 'application/xhtml+xml') name = name.toLowerCase();\n return doc.createElement(name);\n};\n\n\n/**\n * Creates a new text node.\n * @param {number|string} content Content.\n * @return {!Text} The new text node.\n */\ngoog.dom.createTextNode = function(content) {\n return document.createTextNode(String(content));\n};\n\n\n/**\n * Create a table.\n * @param {number} rows The number of rows in the table. Must be >= 1.\n * @param {number} columns The number of columns in the table. Must be >= 1.\n * @param {boolean=} opt_fillWithNbsp If true, fills table entries with\n * `goog.string.Unicode.NBSP` characters.\n * @return {!Element} The created table.\n */\ngoog.dom.createTable = function(rows, columns, opt_fillWithNbsp) {\n // TODO(mlourenco): Return HTMLTableElement, also in prototype function.\n // Callers need to be updated to e.g. not assign numbers to table.cellSpacing.\n return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp);\n};\n\n\n/**\n * Create a table.\n * @param {!Document} doc Document object to use to create the table.\n * @param {number} rows The number of rows in the table. Must be >= 1.\n * @param {number} columns The number of columns in the table. Must be >= 1.\n * @param {boolean} fillWithNbsp If true, fills table entries with\n * `goog.string.Unicode.NBSP` characters.\n * @return {!HTMLTableElement} The created table.\n * @private\n */\ngoog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) {\n var table = goog.dom.createElement_(doc, goog.dom.TagName.TABLE);\n var tbody =\n table.appendChild(goog.dom.createElement_(doc, goog.dom.TagName.TBODY));\n for (var i = 0; i < rows; i++) {\n var tr = goog.dom.createElement_(doc, goog.dom.TagName.TR);\n for (var j = 0; j < columns; j++) {\n var td = goog.dom.createElement_(doc, goog.dom.TagName.TD);\n // IE <= 9 will create a text node if we set text content to the empty\n // string, so we avoid doing it unless necessary. This ensures that the\n // same DOM tree is returned on all browsers.\n if (fillWithNbsp) {\n goog.dom.setTextContent(td, goog.string.Unicode.NBSP);\n }\n tr.appendChild(td);\n }\n tbody.appendChild(tr);\n }\n return table;\n};\n\n\n\n/**\n * Creates a new Node from constant strings of HTML markup.\n * @param {...!goog.string.Const} var_args The HTML strings to concatenate then\n * convert into a node.\n * @return {!Node}\n */\ngoog.dom.constHtmlToNode = function(var_args) {\n var stringArray = goog.array.map(arguments, goog.string.Const.unwrap);\n var safeHtml =\n goog.html.uncheckedconversions\n .safeHtmlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from(\n 'Constant HTML string, that gets turned into a ' +\n 'Node later, so it will be automatically balanced.'),\n stringArray.join(''));\n return goog.dom.safeHtmlToNode(safeHtml);\n};\n\n\n/**\n * Converts HTML markup into a node. This is a safe version of\n * `goog.dom.htmlToDocumentFragment` which is now deleted.\n * @param {!goog.html.SafeHtml} html The HTML markup to convert.\n * @return {!Node} The resulting node.\n */\ngoog.dom.safeHtmlToNode = function(html) {\n return goog.dom.safeHtmlToNode_(document, html);\n};\n\n\n/**\n * Helper for `safeHtmlToNode`.\n * @param {!Document} doc The document.\n * @param {!goog.html.SafeHtml} html The HTML markup to convert.\n * @return {!Node} The resulting node.\n * @private\n */\ngoog.dom.safeHtmlToNode_ = function(doc, html) {\n var tempDiv = goog.dom.createElement_(doc, goog.dom.TagName.DIV);\n if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {\n goog.dom.safe.setInnerHtml(\n tempDiv, goog.html.SafeHtml.concat(goog.html.SafeHtml.BR, html));\n tempDiv.removeChild(goog.asserts.assert(tempDiv.firstChild));\n } else {\n goog.dom.safe.setInnerHtml(tempDiv, html);\n }\n return goog.dom.childrenToNode_(doc, tempDiv);\n};\n\n\n/**\n * Helper for `safeHtmlToNode_`.\n * @param {!Document} doc The document.\n * @param {!Node} tempDiv The input node.\n * @return {!Node} The resulting node.\n * @private\n */\ngoog.dom.childrenToNode_ = function(doc, tempDiv) {\n if (tempDiv.childNodes.length == 1) {\n return tempDiv.removeChild(goog.asserts.assert(tempDiv.firstChild));\n } else {\n var fragment = doc.createDocumentFragment();\n while (tempDiv.firstChild) {\n fragment.appendChild(tempDiv.firstChild);\n }\n return fragment;\n }\n};\n\n\n/**\n * Returns true if the browser is in \"CSS1-compatible\" (standards-compliant)\n * mode, false otherwise.\n * @return {boolean} True if in CSS1-compatible mode.\n */\ngoog.dom.isCss1CompatMode = function() {\n return goog.dom.isCss1CompatMode_(document);\n};\n\n\n/**\n * Returns true if the browser is in \"CSS1-compatible\" (standards-compliant)\n * mode, false otherwise.\n * @param {!Document} doc The document to check.\n * @return {boolean} True if in CSS1-compatible mode.\n * @private\n */\ngoog.dom.isCss1CompatMode_ = function(doc) {\n if (goog.dom.COMPAT_MODE_KNOWN_) {\n return goog.dom.ASSUME_STANDARDS_MODE;\n }\n\n return doc.compatMode == 'CSS1Compat';\n};\n\n\n/**\n * Determines if the given node can contain children, intended to be used for\n * HTML generation.\n *\n * IE natively supports node.canHaveChildren but has inconsistent behavior.\n * Prior to IE8 the base tag allows children and in IE9 all nodes return true\n * for canHaveChildren.\n *\n * In practice all non-IE browsers allow you to add children to any node, but\n * the behavior is inconsistent:\n *\n * <pre>\n * var a = goog.dom.createElement(goog.dom.TagName.BR);\n * a.appendChild(document.createTextNode('foo'));\n * a.appendChild(document.createTextNode('bar'));\n * console.log(a.childNodes.length); // 2\n * console.log(a.innerHTML); // Chrome: \"\", IE9: \"foobar\", FF3.5: \"foobar\"\n * </pre>\n *\n * For more information, see:\n * http://dev.w3.org/html5/markup/syntax.html#syntax-elements\n *\n * TODO(user): Rename shouldAllowChildren() ?\n *\n * @param {Node} node The node to check.\n * @return {boolean} Whether the node can contain children.\n */\ngoog.dom.canHaveChildren = function(node) {\n if (node.nodeType != goog.dom.NodeType.ELEMENT) {\n return false;\n }\n switch (/** @type {!Element} */ (node).tagName) {\n case String(goog.dom.TagName.APPLET):\n case String(goog.dom.TagName.AREA):\n case String(goog.dom.TagName.BASE):\n case String(goog.dom.TagName.BR):\n case String(goog.dom.TagName.COL):\n case String(goog.dom.TagName.COMMAND):\n case String(goog.dom.TagName.EMBED):\n case String(goog.dom.TagName.FRAME):\n case String(goog.dom.TagName.HR):\n case String(goog.dom.TagName.IMG):\n case String(goog.dom.TagName.INPUT):\n case String(goog.dom.TagName.IFRAME):\n case String(goog.dom.TagName.ISINDEX):\n case String(goog.dom.TagName.KEYGEN):\n case String(goog.dom.TagName.LINK):\n case String(goog.dom.TagName.NOFRAMES):\n case String(goog.dom.TagName.NOSCRIPT):\n case String(goog.dom.TagName.META):\n case String(goog.dom.TagName.OBJECT):\n case String(goog.dom.TagName.PARAM):\n case String(goog.dom.TagName.SCRIPT):\n case String(goog.dom.TagName.SOURCE):\n case String(goog.dom.TagName.STYLE):\n case String(goog.dom.TagName.TRACK):\n case String(goog.dom.TagName.WBR):\n return false;\n }\n return true;\n};\n\n\n/**\n * Appends a child to a node.\n * @param {Node} parent Parent.\n * @param {Node} child Child.\n */\ngoog.dom.appendChild = function(parent, child) {\n goog.asserts.assert(\n parent != null && child != null,\n 'goog.dom.appendChild expects non-null arguments');\n parent.appendChild(child);\n};\n\n\n/**\n * Appends a node with text or other nodes.\n * @param {!Node} parent The node to append nodes to.\n * @param {...goog.dom.Appendable} var_args The things to append to the node.\n * If this is a Node it is appended as is.\n * If this is a string then a text node is appended.\n * If this is an array like object then fields 0 to length - 1 are appended.\n */\ngoog.dom.append = function(parent, var_args) {\n goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);\n};\n\n\n/**\n * Removes all the child nodes on a DOM node.\n * @param {Node} node Node to remove children from.\n */\ngoog.dom.removeChildren = function(node) {\n // Note: Iterations over live collections can be slow, this is the fastest\n // we could find. The double parenthesis are used to prevent JsCompiler and\n // strict warnings.\n var child;\n while ((child = node.firstChild)) {\n node.removeChild(child);\n }\n};\n\n\n/**\n * Inserts a new node before an existing reference node (i.e. as the previous\n * sibling). If the reference node has no parent, then does nothing.\n * @param {Node} newNode Node to insert.\n * @param {Node} refNode Reference node to insert before.\n */\ngoog.dom.insertSiblingBefore = function(newNode, refNode) {\n goog.asserts.assert(\n newNode != null && refNode != null,\n 'goog.dom.insertSiblingBefore expects non-null arguments');\n if (refNode.parentNode) {\n refNode.parentNode.insertBefore(newNode, refNode);\n }\n};\n\n\n/**\n * Inserts a new node after an existing reference node (i.e. as the next\n * sibling). If the reference node has no parent, then does nothing.\n * @param {Node} newNode Node to insert.\n * @param {Node} refNode Reference node to insert after.\n */\ngoog.dom.insertSiblingAfter = function(newNode, refNode) {\n goog.asserts.assert(\n newNode != null && refNode != null,\n 'goog.dom.insertSiblingAfter expects non-null arguments');\n if (refNode.parentNode) {\n refNode.parentNode.insertBefore(newNode, refNode.nextSibling);\n }\n};\n\n\n/**\n * Insert a child at a given index. If index is larger than the number of child\n * nodes that the parent currently has, the node is inserted as the last child\n * node.\n * @param {Element} parent The element into which to insert the child.\n * @param {Node} child The element to insert.\n * @param {number} index The index at which to insert the new child node. Must\n * not be negative.\n */\ngoog.dom.insertChildAt = function(parent, child, index) {\n // Note that if the second argument is null, insertBefore\n // will append the child at the end of the list of children.\n goog.asserts.assert(\n parent != null, 'goog.dom.insertChildAt expects a non-null parent');\n parent.insertBefore(\n /** @type {!Node} */ (child), parent.childNodes[index] || null);\n};\n\n\n/**\n * Removes a node from its parent.\n * @param {Node} node The node to remove.\n * @return {Node} The node removed if removed; else, null.\n */\ngoog.dom.removeNode = function(node) {\n return node && node.parentNode ? node.parentNode.removeChild(node) : null;\n};\n\n\n/**\n * Replaces a node in the DOM tree. Will do nothing if `oldNode` has no\n * parent.\n * @param {Node} newNode Node to insert.\n * @param {Node} oldNode Node to replace.\n */\ngoog.dom.replaceNode = function(newNode, oldNode) {\n goog.asserts.assert(\n newNode != null && oldNode != null,\n 'goog.dom.replaceNode expects non-null arguments');\n var parent = oldNode.parentNode;\n if (parent) {\n parent.replaceChild(newNode, oldNode);\n }\n};\n\n\n/**\n * Flattens an element. That is, removes it and replace it with its children.\n * Does nothing if the element is not in the document.\n * @param {Element} element The element to flatten.\n * @return {Element|undefined} The original element, detached from the document\n * tree, sans children; or undefined, if the element was not in the document\n * to begin with.\n */\ngoog.dom.flattenElement = function(element) {\n var child, parent = element.parentNode;\n if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {\n // Use IE DOM method (supported by Opera too) if available\n if (element.removeNode) {\n return /** @type {Element} */ (element.removeNode(false));\n } else {\n // Move all children of the original node up one level.\n while ((child = element.firstChild)) {\n parent.insertBefore(child, element);\n }\n\n // Detach the original element.\n return /** @type {Element} */ (goog.dom.removeNode(element));\n }\n }\n};\n\n\n/**\n * Returns an array containing just the element children of the given element.\n * @param {Element} element The element whose element children we want.\n * @return {!(Array<!Element>|NodeList<!Element>)} An array or array-like list\n * of just the element children of the given element.\n */\ngoog.dom.getChildren = function(element) {\n // We check if the children attribute is supported for child elements\n // since IE8 misuses the attribute by also including comments.\n if (goog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE &&\n element.children != undefined) {\n return element.children;\n }\n // Fall back to manually filtering the element's child nodes.\n return goog.array.filter(element.childNodes, function(node) {\n return node.nodeType == goog.dom.NodeType.ELEMENT;\n });\n};\n\n\n/**\n * Returns the first child node that is an element.\n * @param {Node} node The node to get the first child element of.\n * @return {Element} The first child node of `node` that is an element.\n */\ngoog.dom.getFirstElementChild = function(node) {\n if (node.firstElementChild !== undefined) {\n return /** @type {!Element} */ (node).firstElementChild;\n }\n return goog.dom.getNextElementNode_(node.firstChild, true);\n};\n\n\n/**\n * Returns the last child node that is an element.\n * @param {Node} node The node to get the last child element of.\n * @return {Element} The last child node of `node` that is an element.\n */\ngoog.dom.getLastElementChild = function(node) {\n if (node.lastElementChild !== undefined) {\n return /** @type {!Element} */ (node).lastElementChild;\n }\n return goog.dom.getNextElementNode_(node.lastChild, false);\n};\n\n\n/**\n * Returns the first next sibling that is an element.\n * @param {Node} node The node to get the next sibling element of.\n * @return {Element} The next sibling of `node` that is an element.\n */\ngoog.dom.getNextElementSibling = function(node) {\n if (node.nextElementSibling !== undefined) {\n return /** @type {!Element} */ (node).nextElementSibling;\n }\n return goog.dom.getNextElementNode_(node.nextSibling, true);\n};\n\n\n/**\n * Returns the first previous sibling that is an element.\n * @param {Node} node The node to get the previous sibling element of.\n * @return {Element} The first previous sibling of `node` that is\n * an element.\n */\ngoog.dom.getPreviousElementSibling = function(node) {\n if (node.previousElementSibling !== undefined) {\n return /** @type {!Element} */ (node).previousElementSibling;\n }\n return goog.dom.getNextElementNode_(node.previousSibling, false);\n};\n\n\n/**\n * Returns the first node that is an element in the specified direction,\n * starting with `node`.\n * @param {Node} node The node to get the next element from.\n * @param {boolean} forward Whether to look forwards or backwards.\n * @return {Element} The first element.\n * @private\n */\ngoog.dom.getNextElementNode_ = function(node, forward) {\n while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {\n node = forward ? node.nextSibling : node.previousSibling;\n }\n\n return /** @type {Element} */ (node);\n};\n\n\n/**\n * Returns the next node in source order from the given node.\n * @param {Node} node The node.\n * @return {Node} The next node in the DOM tree, or null if this was the last\n * node.\n */\ngoog.dom.getNextNode = function(node) {\n if (!node) {\n return null;\n }\n\n if (node.firstChild) {\n return node.firstChild;\n }\n\n while (node && !node.nextSibling) {\n node = node.parentNode;\n }\n\n return node ? node.nextSibling : null;\n};\n\n\n/**\n * Returns the previous node in source order from the given node.\n * @param {Node} node The node.\n * @return {Node} The previous node in the DOM tree, or null if this was the\n * first node.\n */\ngoog.dom.getPreviousNode = function(node) {\n if (!node) {\n return null;\n }\n\n if (!node.previousSibling) {\n return node.parentNode;\n }\n\n node = node.previousSibling;\n while (node && node.lastChild) {\n node = node.lastChild;\n }\n\n return node;\n};\n\n\n/**\n * Whether the object looks like a DOM node.\n * @param {?} obj The object being tested for node likeness.\n * @return {boolean} Whether the object looks like a DOM node.\n */\ngoog.dom.isNodeLike = function(obj) {\n return goog.isObject(obj) && obj.nodeType > 0;\n};\n\n\n/**\n * Whether the object looks like an Element.\n * @param {?} obj The object being tested for Element likeness.\n * @return {boolean} Whether the object looks like an Element.\n */\ngoog.dom.isElement = function(obj) {\n return goog.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT;\n};\n\n\n/**\n * Returns true if the specified value is a Window object. This includes the\n * global window for HTML pages, and iframe windows.\n * @param {?} obj Variable to test.\n * @return {boolean} Whether the variable is a window.\n */\ngoog.dom.isWindow = function(obj) {\n return goog.isObject(obj) && obj['window'] == obj;\n};\n\n\n/**\n * Returns an element's parent, if it's an Element.\n * @param {Element} element The DOM element.\n * @return {Element} The parent, or null if not an Element.\n */\ngoog.dom.getParentElement = function(element) {\n var parent;\n if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) {\n var isIe9 = goog.userAgent.IE && goog.userAgent.isVersionOrHigher('9') &&\n !goog.userAgent.isVersionOrHigher('10');\n // SVG elements in IE9 can't use the parentElement property.\n // goog.global['SVGElement'] is not defined in IE9 quirks mode.\n if (!(isIe9 && goog.global['SVGElement'] &&\n element instanceof goog.global['SVGElement'])) {\n parent = element.parentElement;\n if (parent) {\n return parent;\n }\n }\n }\n parent = element.parentNode;\n return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null;\n};\n\n\n/**\n * Whether a node contains another node.\n * @param {?Node|undefined} parent The node that should contain the other node.\n * @param {?Node|undefined} descendant The node to test presence of.\n * @return {boolean} Whether the parent node contains the descendant node.\n */\ngoog.dom.contains = function(parent, descendant) {\n if (!parent || !descendant) {\n return false;\n }\n // We use browser specific methods for this if available since it is faster\n // that way.\n\n // IE DOM\n if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {\n return parent == descendant || parent.contains(descendant);\n }\n\n // W3C DOM Level 3\n if (typeof parent.compareDocumentPosition != 'undefined') {\n return parent == descendant ||\n Boolean(parent.compareDocumentPosition(descendant) & 16);\n }\n\n // W3C DOM Level 1\n while (descendant && parent != descendant) {\n descendant = descendant.parentNode;\n }\n return descendant == parent;\n};\n\n\n/**\n * Compares the document order of two nodes, returning 0 if they are the same\n * node, a negative number if node1 is before node2, and a positive number if\n * node2 is before node1. Note that we compare the order the tags appear in the\n * document so in the tree <b><i>text</i></b> the B node is considered to be\n * before the I node.\n *\n * @param {Node} node1 The first node to compare.\n * @param {Node} node2 The second node to compare.\n * @return {number} 0 if the nodes are the same node, a negative number if node1\n * is before node2, and a positive number if node2 is before node1.\n */\ngoog.dom.compareNodeOrder = function(node1, node2) {\n // Fall out quickly for equality.\n if (node1 == node2) {\n return 0;\n }\n\n // Use compareDocumentPosition where available\n if (node1.compareDocumentPosition) {\n // 4 is the bitmask for FOLLOWS.\n return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;\n }\n\n // Special case for document nodes on IE 7 and 8.\n if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {\n if (node1.nodeType == goog.dom.NodeType.DOCUMENT) {\n return -1;\n }\n if (node2.nodeType == goog.dom.NodeType.DOCUMENT) {\n return 1;\n }\n }\n\n // Process in IE using sourceIndex - we check to see if the first node has\n // a source index or if its parent has one.\n if ('sourceIndex' in node1 ||\n (node1.parentNode && 'sourceIndex' in node1.parentNode)) {\n var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;\n var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;\n\n if (isElement1 && isElement2) {\n return node1.sourceIndex - node2.sourceIndex;\n } else {\n var parent1 = node1.parentNode;\n var parent2 = node2.parentNode;\n\n if (parent1 == parent2) {\n return goog.dom.compareSiblingOrder_(node1, node2);\n }\n\n if (!isElement1 && goog.dom.contains(parent1, node2)) {\n return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);\n }\n\n\n if (!isElement2 && goog.dom.contains(parent2, node1)) {\n return goog.dom.compareParentsDescendantNodeIe_(node2, node1);\n }\n\n return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -\n (isElement2 ? node2.sourceIndex : parent2.sourceIndex);\n }\n }\n\n // For Safari, we compare ranges.\n var doc = goog.dom.getOwnerDocument(node1);\n\n var range1, range2;\n range1 = doc.createRange();\n range1.selectNode(node1);\n range1.collapse(true);\n\n range2 = doc.createRange();\n range2.selectNode(node2);\n range2.collapse(true);\n\n return range1.compareBoundaryPoints(\n goog.global['Range'].START_TO_END, range2);\n};\n\n\n/**\n * Utility function to compare the position of two nodes, when\n * `textNode`'s parent is an ancestor of `node`. If this entry\n * condition is not met, this function will attempt to reference a null object.\n * @param {!Node} textNode The textNode to compare.\n * @param {Node} node The node to compare.\n * @return {number} -1 if node is before textNode, +1 otherwise.\n * @private\n */\ngoog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {\n var parent = textNode.parentNode;\n if (parent == node) {\n // If textNode is a child of node, then node comes first.\n return -1;\n }\n var sibling = node;\n while (sibling.parentNode != parent) {\n sibling = sibling.parentNode;\n }\n return goog.dom.compareSiblingOrder_(sibling, textNode);\n};\n\n\n/**\n * Utility function to compare the position of two nodes known to be non-equal\n * siblings.\n * @param {Node} node1 The first node to compare.\n * @param {!Node} node2 The second node to compare.\n * @return {number} -1 if node1 is before node2, +1 otherwise.\n * @private\n */\ngoog.dom.compareSiblingOrder_ = function(node1, node2) {\n var s = node2;\n while ((s = s.previousSibling)) {\n if (s == node1) {\n // We just found node1 before node2.\n return -1;\n }\n }\n\n // Since we didn't find it, node1 must be after node2.\n return 1;\n};\n\n\n/**\n * Find the deepest common ancestor of the given nodes.\n * @param {...Node} var_args The nodes to find a common ancestor of.\n * @return {Node} The common ancestor of the nodes, or null if there is none.\n * null will only be returned if two or more of the nodes are from different\n * documents.\n */\ngoog.dom.findCommonAncestor = function(var_args) {\n var i, count = arguments.length;\n if (!count) {\n return null;\n } else if (count == 1) {\n return arguments[0];\n }\n\n var paths = [];\n var minLength = Infinity;\n for (i = 0; i < count; i++) {\n // Compute the list of ancestors.\n var ancestors = [];\n var node = arguments[i];\n while (node) {\n ancestors.unshift(node);\n node = node.parentNode;\n }\n\n // Save the list for comparison.\n paths.push(ancestors);\n minLength = Math.min(minLength, ancestors.length);\n }\n var output = null;\n for (i = 0; i < minLength; i++) {\n var first = paths[0][i];\n for (var j = 1; j < count; j++) {\n if (first != paths[j][i]) {\n return output;\n }\n }\n output = first;\n }\n return output;\n};\n\n\n/**\n * Returns whether node is in a document or detached. Throws an error if node\n * itself is a document. This specifically handles two cases beyond naive use of\n * builtins: (1) it works correctly in IE, and (2) it works for elements from\n * different documents/iframes. If neither of these considerations are relevant\n * then a simple `document.contains(node)` may be used instead.\n * @param {!Node} node\n * @return {boolean}\n */\ngoog.dom.isInDocument = function(node) {\n return (node.ownerDocument.compareDocumentPosition(node) & 16) == 16;\n};\n\n\n/**\n * Returns the owner document for a node.\n * @param {Node|Window} node The node to get the document for.\n * @return {!Document} The document owning the node.\n */\ngoog.dom.getOwnerDocument = function(node) {\n // TODO(nnaze): Update param signature to be non-nullable.\n goog.asserts.assert(node, 'Node cannot be null or undefined.');\n return /** @type {!Document} */ (\n node.nodeType == goog.dom.NodeType.DOCUMENT ? node : node.ownerDocument ||\n node.document);\n};\n\n\n/**\n * Cross-browser function for getting the document element of a frame or iframe.\n * @param {Element} frame Frame element.\n * @return {!Document} The frame content document.\n */\ngoog.dom.getFrameContentDocument = function(frame) {\n return frame.contentDocument ||\n /** @type {!HTMLFrameElement} */ (frame).contentWindow.document;\n};\n\n\n/**\n * Cross-browser function for getting the window of a frame or iframe.\n * @param {Element} frame Frame element.\n * @return {Window} The window associated with the given frame, or null if none\n * exists.\n */\ngoog.dom.getFrameContentWindow = function(frame) {\n try {\n return frame.contentWindow ||\n (frame.contentDocument ? goog.dom.getWindow(frame.contentDocument) :\n null);\n } catch (e) {\n // NOTE(user): In IE8, checking the contentWindow or contentDocument\n // properties will throw a \"Unspecified Error\" exception if the iframe is\n // not inserted in the DOM. If we get this we can be sure that no window\n // exists, so return null.\n }\n return null;\n};\n\n\n/**\n * Sets the text content of a node, with cross-browser support.\n * @param {Node} node The node to change the text content of.\n * @param {string|number} text The value that should replace the node's content.\n */\ngoog.dom.setTextContent = function(node, text) {\n goog.asserts.assert(\n node != null,\n 'goog.dom.setTextContent expects a non-null value for node');\n\n if ('textContent' in node) {\n node.textContent = text;\n } else if (node.nodeType == goog.dom.NodeType.TEXT) {\n /** @type {!Text} */ (node).data = String(text);\n } else if (\n node.firstChild && node.firstChild.nodeType == goog.dom.NodeType.TEXT) {\n // If the first child is a text node we just change its data and remove the\n // rest of the children.\n while (node.lastChild != node.firstChild) {\n node.removeChild(goog.asserts.assert(node.lastChild));\n }\n /** @type {!Text} */ (node.firstChild).data = String(text);\n } else {\n goog.dom.removeChildren(node);\n var doc = goog.dom.getOwnerDocument(node);\n node.appendChild(doc.createTextNode(String(text)));\n }\n};\n\n\n/**\n * Gets the outerHTML of a node, which is like innerHTML, except that it\n * actually contains the HTML of the node itself.\n * @param {Element} element The element to get the HTML of.\n * @return {string} The outerHTML of the given element.\n */\ngoog.dom.getOuterHtml = function(element) {\n goog.asserts.assert(\n element !== null,\n 'goog.dom.getOuterHtml expects a non-null value for element');\n // IE, Opera and WebKit all have outerHTML.\n if ('outerHTML' in element) {\n return element.outerHTML;\n } else {\n var doc = goog.dom.getOwnerDocument(element);\n var div = goog.dom.createElement_(doc, goog.dom.TagName.DIV);\n div.appendChild(element.cloneNode(true));\n return div.innerHTML;\n }\n};\n\n\n/**\n * Finds the first descendant node that matches the filter function, using depth\n * first search. This function offers the most general purpose way of finding a\n * matching element.\n *\n * Prefer using `querySelector` if the matching criteria can be expressed as a\n * CSS selector, or `goog.dom.findElement` if you would filter for `nodeType ==\n * Node.ELEMENT_NODE`.\n *\n * @param {Node} root The root of the tree to search.\n * @param {function(Node) : boolean} p The filter function.\n * @return {Node|undefined} The found node or undefined if none is found.\n */\ngoog.dom.findNode = function(root, p) {\n var rv = [];\n var found = goog.dom.findNodes_(root, p, rv, true);\n return found ? rv[0] : undefined;\n};\n\n\n/**\n * Finds all the descendant nodes that match the filter function, using depth\n * first search. This function offers the most general-purpose way\n * of finding a set of matching elements.\n *\n * Prefer using `querySelectorAll` if the matching criteria can be expressed as\n * a CSS selector, or `goog.dom.findElements` if you would filter for\n * `nodeType == Node.ELEMENT_NODE`.\n *\n * @param {Node} root The root of the tree to search.\n * @param {function(Node) : boolean} p The filter function.\n * @return {!Array<!Node>} The found nodes or an empty array if none are found.\n */\ngoog.dom.findNodes = function(root, p) {\n var rv = [];\n goog.dom.findNodes_(root, p, rv, false);\n return rv;\n};\n\n\n/**\n * Finds the first or all the descendant nodes that match the filter function,\n * using a depth first search.\n * @param {Node} root The root of the tree to search.\n * @param {function(Node) : boolean} p The filter function.\n * @param {!Array<!Node>} rv The found nodes are added to this array.\n * @param {boolean} findOne If true we exit after the first found node.\n * @return {boolean} Whether the search is complete or not. True in case findOne\n * is true and the node is found. False otherwise.\n * @private\n */\ngoog.dom.findNodes_ = function(root, p, rv, findOne) {\n if (root != null) {\n var child = root.firstChild;\n while (child) {\n if (p(child)) {\n rv.push(child);\n if (findOne) {\n return true;\n }\n }\n if (goog.dom.findNodes_(child, p, rv, findOne)) {\n return true;\n }\n child = child.nextSibling;\n }\n }\n return false;\n};\n\n\n/**\n * Finds the first descendant element (excluding `root`) that matches the filter\n * function, using depth first search. Prefer using `querySelector` if the\n * matching criteria can be expressed as a CSS selector.\n *\n * @param {!Element | !Document} root\n * @param {function(!Element): boolean} pred Filter function.\n * @return {?Element} First matching element or null if there is none.\n */\ngoog.dom.findElement = function(root, pred) {\n var stack = goog.dom.getChildrenReverse_(root);\n while (stack.length > 0) {\n var next = stack.pop();\n if (pred(next)) return next;\n for (var c = next.lastElementChild; c; c = c.previousElementSibling) {\n stack.push(c);\n }\n }\n return null;\n};\n\n\n/**\n * Finds all the descendant elements (excluding `root`) that match the filter\n * function, using depth first search. Prefer using `querySelectorAll` if the\n * matching criteria can be expressed as a CSS selector.\n *\n * @param {!Element | !Document} root\n * @param {function(!Element): boolean} pred Filter function.\n * @return {!Array<!Element>}\n */\ngoog.dom.findElements = function(root, pred) {\n var result = [], stack = goog.dom.getChildrenReverse_(root);\n while (stack.length > 0) {\n var next = stack.pop();\n if (pred(next)) result.push(next);\n for (var c = next.lastElementChild; c; c = c.previousElementSibling) {\n stack.push(c);\n }\n }\n return result;\n};\n\n\n/**\n * @param {!Element | !Document} node\n * @return {!Array<!Element>} node's child elements in reverse order.\n * @private\n */\ngoog.dom.getChildrenReverse_ = function(node) {\n // document.lastElementChild doesn't exist in IE9; fall back to\n // documentElement.\n if (node.nodeType == goog.dom.NodeType.DOCUMENT) {\n return [node.documentElement];\n } else {\n var children = [];\n for (var c = node.lastElementChild; c; c = c.previousElementSibling) {\n children.push(c);\n }\n return children;\n }\n};\n\n\n/**\n * Map of tags whose content to ignore when calculating text length.\n * @private {!Object<string, number>}\n * @const\n */\ngoog.dom.TAGS_TO_IGNORE_ = {\n 'SCRIPT': 1,\n 'STYLE': 1,\n 'HEAD': 1,\n 'IFRAME': 1,\n 'OBJECT': 1\n};\n\n\n/**\n * Map of tags which have predefined values with regard to whitespace.\n * @private {!Object<string, string>}\n * @const\n */\ngoog.dom.PREDEFINED_TAG_VALUES_ = {\n 'IMG': ' ',\n 'BR': '\\n'\n};\n\n\n/**\n * Returns true if the element has a tab index that allows it to receive\n * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements\n * natively support keyboard focus, even if they have no tab index.\n * @param {!Element} element Element to check.\n * @return {boolean} Whether the element has a tab index that allows keyboard\n * focus.\n */\ngoog.dom.isFocusableTabIndex = function(element) {\n return goog.dom.hasSpecifiedTabIndex_(element) &&\n goog.dom.isTabIndexFocusable_(element);\n};\n\n\n/**\n * Enables or disables keyboard focus support on the element via its tab index.\n * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true\n * (or elements that natively support keyboard focus, like form elements) can\n * receive keyboard focus. See http://go/tabindex for more info.\n * @param {Element} element Element whose tab index is to be changed.\n * @param {boolean} enable Whether to set or remove a tab index on the element\n * that supports keyboard focus.\n */\ngoog.dom.setFocusableTabIndex = function(element, enable) {\n if (enable) {\n element.tabIndex = 0;\n } else {\n // Set tabIndex to -1 first, then remove it. This is a workaround for\n // Safari (confirmed in version 4 on Windows). When removing the attribute\n // without setting it to -1 first, the element remains keyboard focusable\n // despite not having a tabIndex attribute anymore.\n element.tabIndex = -1;\n element.removeAttribute('tabIndex'); // Must be camelCase!\n }\n};\n\n\n/**\n * Returns true if the element can be focused, i.e. it has a tab index that\n * allows it to receive keyboard focus (tabIndex >= 0), or it is an element\n * that natively supports keyboard focus.\n * @param {!Element} element Element to check.\n * @return {boolean} Whether the element allows keyboard focus.\n */\ngoog.dom.isFocusable = function(element) {\n var focusable;\n // Some elements can have unspecified tab index and still receive focus.\n if (goog.dom.nativelySupportsFocus_(element)) {\n // Make sure the element is not disabled ...\n focusable = !element.disabled &&\n // ... and if a tab index is specified, it allows focus.\n (!goog.dom.hasSpecifiedTabIndex_(element) ||\n goog.dom.isTabIndexFocusable_(element));\n } else {\n focusable = goog.dom.isFocusableTabIndex(element);\n }\n\n // IE requires elements to be visible in order to focus them.\n return focusable && goog.userAgent.IE ?\n goog.dom.hasNonZeroBoundingRect_(/** @type {!HTMLElement} */ (element)) :\n focusable;\n};\n\n\n/**\n * Returns true if the element has a specified tab index.\n * @param {!Element} element Element to check.\n * @return {boolean} Whether the element has a specified tab index.\n * @private\n */\ngoog.dom.hasSpecifiedTabIndex_ = function(element) {\n // IE8 and below don't support hasAttribute(), instead check whether the\n // 'tabindex' attributeNode is specified. Otherwise check hasAttribute().\n if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9')) {\n var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!\n return attrNode != null && attrNode.specified;\n } else {\n return element.hasAttribute('tabindex');\n }\n};\n\n\n/**\n * Returns true if the element's tab index allows the element to be focused.\n * @param {!Element} element Element to check.\n * @return {boolean} Whether the element's tab index allows focus.\n * @private\n */\ngoog.dom.isTabIndexFocusable_ = function(element) {\n var index = /** @type {!HTMLElement} */ (element).tabIndex;\n // NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534.\n return typeof (index) === 'number' && index >= 0 && index < 32768;\n};\n\n\n/**\n * Returns true if the element is focusable even when tabIndex is not set.\n * @param {!Element} element Element to check.\n * @return {boolean} Whether the element natively supports focus.\n * @private\n */\ngoog.dom.nativelySupportsFocus_ = function(element) {\n return (\n element.tagName == goog.dom.TagName.A && element.hasAttribute('href') ||\n element.tagName == goog.dom.TagName.INPUT ||\n element.tagName == goog.dom.TagName.TEXTAREA ||\n element.tagName == goog.dom.TagName.SELECT ||\n element.tagName == goog.dom.TagName.BUTTON);\n};\n\n\n/**\n * Returns true if the element has a bounding rectangle that would be visible\n * (i.e. its width and height are greater than zero).\n * @param {!HTMLElement} element Element to check.\n * @return {boolean} Whether the element has a non-zero bounding rectangle.\n * @private\n */\ngoog.dom.hasNonZeroBoundingRect_ = function(element) {\n var rect;\n if (!goog.isFunction(element['getBoundingClientRect']) ||\n // In IE, getBoundingClientRect throws on detached nodes.\n (goog.userAgent.IE && element.parentElement == null)) {\n rect = {'height': element.offsetHeight, 'width': element.offsetWidth};\n } else {\n rect = element.getBoundingClientRect();\n }\n return rect != null && rect.height > 0 && rect.width > 0;\n};\n\n\n/**\n * Returns the text content of the current node, without markup and invisible\n * symbols. New lines are stripped and whitespace is collapsed,\n * such that each character would be visible.\n *\n * In browsers that support it, innerText is used. Other browsers attempt to\n * simulate it via node traversal. Line breaks are canonicalized in IE.\n *\n * @param {Node} node The node from which we are getting content.\n * @return {string} The text content.\n */\ngoog.dom.getTextContent = function(node) {\n var textContent;\n // Note(arv): IE9, Opera, and Safari 3 support innerText but they include\n // text nodes in script tags. So we revert to use a user agent test here.\n if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && node !== null &&\n ('innerText' in node)) {\n textContent = goog.string.canonicalizeNewlines(node.innerText);\n // Unfortunately .innerText() returns text with &shy; symbols\n // We need to filter it out and then remove duplicate whitespaces\n } else {\n var buf = [];\n goog.dom.getTextContent_(node, buf, true);\n textContent = buf.join('');\n }\n\n // Strip &shy; entities. goog.format.insertWordBreaks inserts them in Opera.\n textContent = textContent.replace(/ \\xAD /g, ' ').replace(/\\xAD/g, '');\n // Strip &#8203; entities. goog.format.insertWordBreaks inserts them in IE8.\n textContent = textContent.replace(/\\u200B/g, '');\n\n // Skip this replacement on old browsers with working innerText, which\n // automatically turns &nbsp; into ' ' and / +/ into ' ' when reading\n // innerText.\n if (!goog.dom.BrowserFeature.CAN_USE_INNER_TEXT) {\n textContent = textContent.replace(/ +/g, ' ');\n }\n if (textContent != ' ') {\n textContent = textContent.replace(/^\\s*/, '');\n }\n\n return textContent;\n};\n\n\n/**\n * Returns the text content of the current node, without markup.\n *\n * Unlike `getTextContent` this method does not collapse whitespaces\n * or normalize lines breaks.\n *\n * @param {Node} node The node from which we are getting content.\n * @return {string} The raw text content.\n */\ngoog.dom.getRawTextContent = function(node) {\n var buf = [];\n goog.dom.getTextContent_(node, buf, false);\n\n return buf.join('');\n};\n\n\n/**\n * Recursive support function for text content retrieval.\n *\n * @param {Node} node The node from which we are getting content.\n * @param {Array<string>} buf string buffer.\n * @param {boolean} normalizeWhitespace Whether to normalize whitespace.\n * @private\n */\ngoog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {\n if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {\n // ignore certain tags\n } else if (node.nodeType == goog.dom.NodeType.TEXT) {\n if (normalizeWhitespace) {\n buf.push(String(node.nodeValue).replace(/(\\r\\n|\\r|\\n)/g, ''));\n } else {\n buf.push(node.nodeValue);\n }\n } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {\n buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);\n } else {\n var child = node.firstChild;\n while (child) {\n goog.dom.getTextContent_(child, buf, normalizeWhitespace);\n child = child.nextSibling;\n }\n }\n};\n\n\n/**\n * Returns the text length of the text contained in a node, without markup. This\n * is equivalent to the selection length if the node was selected, or the number\n * of cursor movements to traverse the node. Images & BRs take one space. New\n * lines are ignored.\n *\n * @param {Node} node The node whose text content length is being calculated.\n * @return {number} The length of `node`'s text content.\n */\ngoog.dom.getNodeTextLength = function(node) {\n return goog.dom.getTextContent(node).length;\n};\n\n\n/**\n * Returns the text offset of a node relative to one of its ancestors. The text\n * length is the same as the length calculated by goog.dom.getNodeTextLength.\n *\n * @param {Node} node The node whose offset is being calculated.\n * @param {Node=} opt_offsetParent The node relative to which the offset will\n * be calculated. Defaults to the node's owner document's body.\n * @return {number} The text offset.\n */\ngoog.dom.getNodeTextOffset = function(node, opt_offsetParent) {\n var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body;\n var buf = [];\n while (node && node != root) {\n var cur = node;\n while ((cur = cur.previousSibling)) {\n buf.unshift(goog.dom.getTextContent(cur));\n }\n node = node.parentNode;\n }\n // Trim left to deal with FF cases when there might be line breaks and empty\n // nodes at the front of the text\n return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length;\n};\n\n\n/**\n * Returns the node at a given offset in a parent node. If an object is\n * provided for the optional third parameter, the node and the remainder of the\n * offset will stored as properties of this object.\n * @param {Node} parent The parent node.\n * @param {number} offset The offset into the parent node.\n * @param {Object=} opt_result Object to be used to store the return value. The\n * return value will be stored in the form {node: Node, remainder: number}\n * if this object is provided.\n * @return {Node} The node at the given offset.\n */\ngoog.dom.getNodeAtOffset = function(parent, offset, opt_result) {\n var stack = [parent], pos = 0, cur = null;\n while (stack.length > 0 && pos < offset) {\n cur = stack.pop();\n if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) {\n // ignore certain tags\n } else if (cur.nodeType == goog.dom.NodeType.TEXT) {\n var text = cur.nodeValue.replace(/(\\r\\n|\\r|\\n)/g, '').replace(/ +/g, ' ');\n pos += text.length;\n } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {\n pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length;\n } else {\n for (var i = cur.childNodes.length - 1; i >= 0; i--) {\n stack.push(cur.childNodes[i]);\n }\n }\n }\n if (goog.isObject(opt_result)) {\n opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0;\n opt_result.node = cur;\n }\n\n return cur;\n};\n\n\n/**\n * Returns true if the object is a `NodeList`. To qualify as a NodeList,\n * the object must have a numeric length property and an item function (which\n * has type 'string' on IE for some reason).\n * @param {Object} val Object to test.\n * @return {boolean} Whether the object is a NodeList.\n */\ngoog.dom.isNodeList = function(val) {\n // TODO(attila): Now the isNodeList is part of goog.dom we can use\n // goog.userAgent to make this simpler.\n // A NodeList must have a length property of type 'number' on all platforms.\n if (val && typeof val.length == 'number') {\n // A NodeList is an object everywhere except Safari, where it's a function.\n if (goog.isObject(val)) {\n // A NodeList must have an item function (on non-IE platforms) or an item\n // property of type 'string' (on IE).\n return typeof val.item == 'function' || typeof val.item == 'string';\n } else if (goog.isFunction(val)) {\n // On Safari, a NodeList is a function with an item property that is also\n // a function.\n return typeof /** @type {?} */ (val.item) == 'function';\n }\n }\n\n // Not a NodeList.\n return false;\n};\n\n\n/**\n * Walks up the DOM hierarchy returning the first ancestor that has the passed\n * tag name and/or class name. If the passed element matches the specified\n * criteria, the element itself is returned.\n * @param {Node} element The DOM node to start with.\n * @param {?(goog.dom.TagName<T>|string)=} opt_tag The tag name to match (or\n * null/undefined to match only based on class name).\n * @param {?string=} opt_class The class name to match (or null/undefined to\n * match only based on tag name).\n * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the\n * dom.\n * @return {?R} The first ancestor that matches the passed criteria, or\n * null if no match is found. The return type is {?Element} if opt_tag is\n * not a member of goog.dom.TagName or a more specific type if it is (e.g.\n * {?HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.getAncestorByTagNameAndClass = function(\n element, opt_tag, opt_class, opt_maxSearchSteps) {\n if (!opt_tag && !opt_class) {\n return null;\n }\n var tagName = opt_tag ? String(opt_tag).toUpperCase() : null;\n return /** @type {Element} */ (goog.dom.getAncestor(element, function(node) {\n return (!tagName || node.nodeName == tagName) &&\n (!opt_class ||\n typeof node.className === 'string' &&\n goog.array.contains(node.className.split(/\\s+/), opt_class));\n }, true, opt_maxSearchSteps));\n};\n\n\n/**\n * Walks up the DOM hierarchy returning the first ancestor that has the passed\n * class name. If the passed element matches the specified criteria, the\n * element itself is returned.\n * @param {Node} element The DOM node to start with.\n * @param {string} className The class name to match.\n * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the\n * dom.\n * @return {Element} The first ancestor that matches the passed criteria, or\n * null if none match.\n */\ngoog.dom.getAncestorByClass = function(element, className, opt_maxSearchSteps) {\n return goog.dom.getAncestorByTagNameAndClass(\n element, null, className, opt_maxSearchSteps);\n};\n\n\n/**\n * Walks up the DOM hierarchy returning the first ancestor that passes the\n * matcher function.\n * @param {Node} element The DOM node to start with.\n * @param {function(Node) : boolean} matcher A function that returns true if the\n * passed node matches the desired criteria.\n * @param {boolean=} opt_includeNode If true, the node itself is included in\n * the search (the first call to the matcher will pass startElement as\n * the node to test).\n * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the\n * dom.\n * @return {Node} DOM node that matched the matcher, or null if there was\n * no match.\n */\ngoog.dom.getAncestor = function(\n element, matcher, opt_includeNode, opt_maxSearchSteps) {\n if (element && !opt_includeNode) {\n element = element.parentNode;\n }\n var steps = 0;\n while (element &&\n (opt_maxSearchSteps == null || steps <= opt_maxSearchSteps)) {\n goog.asserts.assert(element.name != 'parentNode');\n if (matcher(element)) {\n return element;\n }\n element = element.parentNode;\n steps++;\n }\n // Reached the root of the DOM without a match\n return null;\n};\n\n\n/**\n * Determines the active element in the given document.\n * @param {Document} doc The document to look in.\n * @return {Element} The active element.\n */\ngoog.dom.getActiveElement = function(doc) {\n // While in an iframe, IE9 will throw \"Unspecified error\" when accessing\n // activeElement.\n try {\n var activeElement = doc && doc.activeElement;\n // While not in an iframe, IE9-11 sometimes gives null.\n // While in an iframe, IE11 sometimes returns an empty object.\n return activeElement && activeElement.nodeName ? activeElement : null;\n } catch (e) {\n return null;\n }\n};\n\n\n/**\n * Gives the current devicePixelRatio.\n *\n * By default, this is the value of window.devicePixelRatio (which should be\n * preferred if present).\n *\n * If window.devicePixelRatio is not present, the ratio is calculated with\n * window.matchMedia, if present. Otherwise, gives 1.0.\n *\n * Some browsers (including Chrome) consider the browser zoom level in the pixel\n * ratio, so the value may change across multiple calls.\n *\n * @return {number} The number of actual pixels per virtual pixel.\n */\ngoog.dom.getPixelRatio = function() {\n var win = goog.dom.getWindow();\n if (win.devicePixelRatio !== undefined) {\n return win.devicePixelRatio;\n } else if (win.matchMedia) {\n // Should be for IE10 and FF6-17 (this basically clamps to lower)\n // Note that the order of these statements is important\n return goog.dom.matchesPixelRatio_(3) || goog.dom.matchesPixelRatio_(2) ||\n goog.dom.matchesPixelRatio_(1.5) || goog.dom.matchesPixelRatio_(1) ||\n .75;\n }\n return 1;\n};\n\n\n/**\n * Calculates a mediaQuery to check if the current device supports the\n * given actual to virtual pixel ratio.\n * @param {number} pixelRatio The ratio of actual pixels to virtual pixels.\n * @return {number} pixelRatio if applicable, otherwise 0.\n * @private\n */\ngoog.dom.matchesPixelRatio_ = function(pixelRatio) {\n var win = goog.dom.getWindow();\n /**\n * Due to the 1:96 fixed ratio of CSS in to CSS px, 1dppx is equivalent to\n * 96dpi.\n * @const {number}\n */\n var dpiPerDppx = 96;\n var query =\n // FF16-17\n '(min-resolution: ' + pixelRatio + 'dppx),' +\n // FF6-15\n '(min--moz-device-pixel-ratio: ' + pixelRatio + '),' +\n // IE10 (this works for the two browsers above too but I don't want to\n // trust the 1:96 fixed ratio magic)\n '(min-resolution: ' + (pixelRatio * dpiPerDppx) + 'dpi)';\n return win.matchMedia(query).matches ? pixelRatio : 0;\n};\n\n\n/**\n * Gets '2d' context of a canvas. Shortcut for canvas.getContext('2d') with a\n * type information.\n * @param {!HTMLCanvasElement|!OffscreenCanvas} canvas\n * @return {!CanvasRenderingContext2D}\n */\ngoog.dom.getCanvasContext2D = function(canvas) {\n return /** @type {!CanvasRenderingContext2D} */ (canvas.getContext('2d'));\n};\n\n\n\n/**\n * Create an instance of a DOM helper with a new document object.\n * @param {Document=} opt_document Document object to associate with this\n * DOM helper.\n * @constructor\n */\ngoog.dom.DomHelper = function(opt_document) {\n /**\n * Reference to the document object to use\n * @type {!Document}\n * @private\n */\n this.document_ = opt_document || goog.global.document || document;\n};\n\n\n/**\n * Gets the dom helper object for the document where the element resides.\n * @param {Node=} opt_node If present, gets the DomHelper for this node.\n * @return {!goog.dom.DomHelper} The DomHelper.\n */\ngoog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;\n\n\n/**\n * Sets the document object.\n * @param {!Document} document Document object.\n */\ngoog.dom.DomHelper.prototype.setDocument = function(document) {\n this.document_ = document;\n};\n\n\n/**\n * Gets the document object being used by the dom library.\n * @return {!Document} Document object.\n */\ngoog.dom.DomHelper.prototype.getDocument = function() {\n return this.document_;\n};\n\n\n/**\n * Alias for `getElementById`. If a DOM node is passed in then we just\n * return that.\n * @param {string|Element} element Element ID or a DOM node.\n * @return {Element} The element with the given ID, or the node passed in.\n */\ngoog.dom.DomHelper.prototype.getElement = function(element) {\n return goog.dom.getElementHelper_(this.document_, element);\n};\n\n\n/**\n * Gets an element by id, asserting that the element is found.\n *\n * This is used when an element is expected to exist, and should fail with\n * an assertion error if it does not (if assertions are enabled).\n *\n * @param {string} id Element ID.\n * @return {!Element} The element with the given ID, if it exists.\n */\ngoog.dom.DomHelper.prototype.getRequiredElement = function(id) {\n return goog.dom.getRequiredElementHelper_(this.document_, id);\n};\n\n\n/**\n * Alias for `getElement`.\n * @param {string|Element} element Element ID or a DOM node.\n * @return {Element} The element with the given ID, or the node passed in.\n * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.\n */\ngoog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;\n\n\n/**\n * Gets elements by tag name.\n * @param {!goog.dom.TagName<T>} tagName\n * @param {(!Document|!Element)=} opt_parent Parent element or document where to\n * look for elements. Defaults to document of this DomHelper.\n * @return {!NodeList<R>} List of elements. The members of the list are\n * {!Element} if tagName is not a member of goog.dom.TagName or more\n * specific types if it is (e.g. {!HTMLAnchorElement} for\n * goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.DomHelper.prototype.getElementsByTagName =\n function(tagName, opt_parent) {\n var parent = opt_parent || this.document_;\n return parent.getElementsByTagName(String(tagName));\n};\n\n\n/**\n * Looks up elements by both tag and class name, using browser native functions\n * (`querySelectorAll`, `getElementsByTagName` or\n * `getElementsByClassName`) where possible. The returned array is a live\n * NodeList or a static list depending on the code path taken.\n *\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name or * for all\n * tags.\n * @param {?string=} opt_class Optional class name.\n * @param {(Document|Element)=} opt_el Optional element to look in.\n * @return {!IArrayLike<R>} Array-like list of elements (only a length property\n * and numerical indices are guaranteed to exist). The members of the array\n * are {!Element} if opt_tag is not a member of goog.dom.TagName or more\n * specific types if it is (e.g. {!HTMLAnchorElement} for\n * goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(\n opt_tag, opt_class, opt_el) {\n return goog.dom.getElementsByTagNameAndClass_(\n this.document_, opt_tag, opt_class, opt_el);\n};\n\n\n/**\n * Gets the first element matching the tag and the class.\n *\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.\n * @param {?string=} opt_class Optional class name.\n * @param {(Document|Element)=} opt_el Optional element to look in.\n * @return {?R} Reference to a DOM node. The return type is {?Element} if\n * tagName is a string or a more specific type if it is a member of\n * goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.DomHelper.prototype.getElementByTagNameAndClass = function(\n opt_tag, opt_class, opt_el) {\n return goog.dom.getElementByTagNameAndClass_(\n this.document_, opt_tag, opt_class, opt_el);\n};\n\n\n/**\n * Returns an array of all the elements with the provided className.\n * @param {string} className the name of the class to look for.\n * @param {Element|Document=} opt_el Optional element to look in.\n * @return {!IArrayLike<!Element>} The items found with the class name provided.\n */\ngoog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {\n var doc = opt_el || this.document_;\n return goog.dom.getElementsByClass(className, doc);\n};\n\n\n/**\n * Returns the first element we find matching the provided class name.\n * @param {string} className the name of the class to look for.\n * @param {(Element|Document)=} opt_el Optional element to look in.\n * @return {Element} The first item found with the class name provided.\n */\ngoog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {\n var doc = opt_el || this.document_;\n return goog.dom.getElementByClass(className, doc);\n};\n\n\n/**\n * Ensures an element with the given className exists, and then returns the\n * first element with the provided className.\n * @param {string} className the name of the class to look for.\n * @param {(!Element|!Document)=} opt_root Optional element or document to look\n * in.\n * @return {!Element} The first item found with the class name provided.\n * @throws {goog.asserts.AssertionError} Thrown if no element is found.\n */\ngoog.dom.DomHelper.prototype.getRequiredElementByClass = function(\n className, opt_root) {\n var root = opt_root || this.document_;\n return goog.dom.getRequiredElementByClass(className, root);\n};\n\n\n/**\n * Alias for `getElementsByTagNameAndClass`.\n * @deprecated Use DomHelper getElementsByTagNameAndClass.\n *\n * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.\n * @param {?string=} opt_class Optional class name.\n * @param {Element=} opt_el Optional element to look in.\n * @return {!IArrayLike<R>} Array-like list of elements (only a length property\n * and numerical indices are guaranteed to exist). The members of the array\n * are {!Element} if opt_tag is a string or more specific types if it is\n * a member of goog.dom.TagName (e.g. {!HTMLAnchorElement} for\n * goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.DomHelper.prototype.$$ =\n goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;\n\n\n/**\n * Sets a number of properties on a node.\n * @param {Element} element DOM node to set properties on.\n * @param {Object} properties Hash of property:value pairs.\n */\ngoog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;\n\n\n/**\n * Gets the dimensions of the viewport.\n * @param {Window=} opt_window Optional window element to test. Defaults to\n * the window of the Dom Helper.\n * @return {!goog.math.Size} Object with values 'width' and 'height'.\n */\ngoog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {\n // TODO(arv): This should not take an argument. That breaks the rule of a\n // a DomHelper representing a single frame/window/document.\n return goog.dom.getViewportSize(opt_window || this.getWindow());\n};\n\n\n/**\n * Calculates the height of the document.\n *\n * @return {number} The height of the document.\n */\ngoog.dom.DomHelper.prototype.getDocumentHeight = function() {\n return goog.dom.getDocumentHeight_(this.getWindow());\n};\n\n\n/**\n * Typedef for use with goog.dom.createDom and goog.dom.append.\n * @typedef {Object|string|Array|NodeList}\n */\ngoog.dom.Appendable;\n\n\n/**\n * Returns a dom node with a set of attributes. This function accepts varargs\n * for subsequent nodes to be added. Subsequent nodes will be added to the\n * first node as childNodes.\n *\n * So:\n * <code>createDom(goog.dom.TagName.DIV, null, createDom(goog.dom.TagName.P),\n * createDom(goog.dom.TagName.P));</code> would return a div with two child\n * paragraphs\n *\n * An easy way to move all child nodes of an existing element to a new parent\n * element is:\n * <code>createDom(goog.dom.TagName.DIV, null, oldElement.childNodes);</code>\n * which will remove all child nodes from the old element and add them as\n * child nodes of the new DIV.\n *\n * @param {string|!goog.dom.TagName<T>} tagName Tag to create.\n * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map\n * of name-value pairs for attributes. If a string, then this is the\n * className of the new element. If an array, the elements will be joined\n * together as the className of the new element.\n * @param {...(goog.dom.Appendable|undefined)} var_args Further DOM nodes or\n * strings for text nodes. If one of the var_args is an array or\n * NodeList, its elements will be added as childNodes instead.\n * @return {R} Reference to a DOM node. The return type is {!Element} if tagName\n * is a string or a more specific type if it is a member of\n * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.DomHelper.prototype.createDom = function(\n tagName, opt_attributes, var_args) {\n return goog.dom.createDom_(this.document_, arguments);\n};\n\n\n/**\n * Alias for `createDom`.\n * @param {string|!goog.dom.TagName<T>} tagName Tag to create.\n * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map\n * of name-value pairs for attributes. If a string, then this is the\n * className of the new element. If an array, the elements will be joined\n * together as the className of the new element.\n * @param {...(goog.dom.Appendable|undefined)} var_args Further DOM nodes or\n * strings for text nodes. If one of the var_args is an array, its children\n * will be added as childNodes instead.\n * @return {R} Reference to a DOM node. The return type is {!Element} if tagName\n * is a string or a more specific type if it is a member of\n * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.\n */\ngoog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;\n\n\n/**\n * Creates a new element.\n * @param {string|!goog.dom.TagName<T>} name Tag to create.\n * @return {R} The new element. The return type is {!Element} if name is\n * a string or a more specific type if it is a member of goog.dom.TagName\n * (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.DomHelper.prototype.createElement = function(name) {\n return goog.dom.createElement_(this.document_, name);\n};\n\n\n/**\n * Creates a new text node.\n * @param {number|string} content Content.\n * @return {!Text} The new text node.\n */\ngoog.dom.DomHelper.prototype.createTextNode = function(content) {\n return this.document_.createTextNode(String(content));\n};\n\n\n/**\n * Create a table.\n * @param {number} rows The number of rows in the table. Must be >= 1.\n * @param {number} columns The number of columns in the table. Must be >= 1.\n * @param {boolean=} opt_fillWithNbsp If true, fills table entries with\n * `goog.string.Unicode.NBSP` characters.\n * @return {!HTMLElement} The created table.\n */\ngoog.dom.DomHelper.prototype.createTable = function(\n rows, columns, opt_fillWithNbsp) {\n return goog.dom.createTable_(\n this.document_, rows, columns, !!opt_fillWithNbsp);\n};\n\n\n/**\n * Converts an HTML into a node or a document fragment. A single Node is used if\n * `html` only generates a single node. If `html` generates multiple\n * nodes then these are put inside a `DocumentFragment`. This is a safe\n * version of `goog.dom.DomHelper#htmlToDocumentFragment` which is now\n * deleted.\n * @param {!goog.html.SafeHtml} html The HTML markup to convert.\n * @return {!Node} The resulting node.\n */\ngoog.dom.DomHelper.prototype.safeHtmlToNode = function(html) {\n return goog.dom.safeHtmlToNode_(this.document_, html);\n};\n\n\n/**\n * Returns true if the browser is in \"CSS1-compatible\" (standards-compliant)\n * mode, false otherwise.\n * @return {boolean} True if in CSS1-compatible mode.\n */\ngoog.dom.DomHelper.prototype.isCss1CompatMode = function() {\n return goog.dom.isCss1CompatMode_(this.document_);\n};\n\n\n/**\n * Gets the window object associated with the document.\n * @return {!Window} The window associated with the given document.\n */\ngoog.dom.DomHelper.prototype.getWindow = function() {\n return goog.dom.getWindow_(this.document_);\n};\n\n\n/**\n * Gets the document scroll element.\n * @return {!Element} Scrolling element.\n */\ngoog.dom.DomHelper.prototype.getDocumentScrollElement = function() {\n return goog.dom.getDocumentScrollElement_(this.document_);\n};\n\n\n/**\n * Gets the document scroll distance as a coordinate object.\n * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'.\n */\ngoog.dom.DomHelper.prototype.getDocumentScroll = function() {\n return goog.dom.getDocumentScroll_(this.document_);\n};\n\n\n/**\n * Determines the active element in the given document.\n * @param {Document=} opt_doc The document to look in.\n * @return {Element} The active element.\n */\ngoog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) {\n return goog.dom.getActiveElement(opt_doc || this.document_);\n};\n\n\n/**\n * Appends a child to a node.\n * @param {Node} parent Parent.\n * @param {Node} child Child.\n */\ngoog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;\n\n\n/**\n * Appends a node with text or other nodes.\n * @param {!Node} parent The node to append nodes to.\n * @param {...goog.dom.Appendable} var_args The things to append to the node.\n * If this is a Node it is appended as is.\n * If this is a string then a text node is appended.\n * If this is an array like object then fields 0 to length - 1 are appended.\n */\ngoog.dom.DomHelper.prototype.append = goog.dom.append;\n\n\n/**\n * Determines if the given node can contain children, intended to be used for\n * HTML generation.\n *\n * @param {Node} node The node to check.\n * @return {boolean} Whether the node can contain children.\n */\ngoog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren;\n\n\n/**\n * Removes all the child nodes on a DOM node.\n * @param {Node} node Node to remove children from.\n */\ngoog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;\n\n\n/**\n * Inserts a new node before an existing reference node (i.e., as the previous\n * sibling). If the reference node has no parent, then does nothing.\n * @param {Node} newNode Node to insert.\n * @param {Node} refNode Reference node to insert before.\n */\ngoog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;\n\n\n/**\n * Inserts a new node after an existing reference node (i.e., as the next\n * sibling). If the reference node has no parent, then does nothing.\n * @param {Node} newNode Node to insert.\n * @param {Node} refNode Reference node to insert after.\n */\ngoog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;\n\n\n/**\n * Insert a child at a given index. If index is larger than the number of child\n * nodes that the parent currently has, the node is inserted as the last child\n * node.\n * @param {Element} parent The element into which to insert the child.\n * @param {Node} child The element to insert.\n * @param {number} index The index at which to insert the new child node. Must\n * not be negative.\n */\ngoog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt;\n\n\n/**\n * Removes a node from its parent.\n * @param {Node} node The node to remove.\n * @return {Node} The node removed if removed; else, null.\n */\ngoog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;\n\n\n/**\n * Replaces a node in the DOM tree. Will do nothing if `oldNode` has no\n * parent.\n * @param {Node} newNode Node to insert.\n * @param {Node} oldNode Node to replace.\n */\ngoog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;\n\n\n/**\n * Flattens an element. That is, removes it and replace it with its children.\n * @param {Element} element The element to flatten.\n * @return {Element|undefined} The original element, detached from the document\n * tree, sans children, or undefined if the element was already not in the\n * document.\n */\ngoog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;\n\n\n/**\n * Returns an array containing just the element children of the given element.\n * @param {Element} element The element whose element children we want.\n * @return {!(Array<!Element>|NodeList<!Element>)} An array or array-like list\n * of just the element children of the given element.\n */\ngoog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren;\n\n\n/**\n * Returns the first child node that is an element.\n * @param {Node} node The node to get the first child element of.\n * @return {Element} The first child node of `node` that is an element.\n */\ngoog.dom.DomHelper.prototype.getFirstElementChild =\n goog.dom.getFirstElementChild;\n\n\n/**\n * Returns the last child node that is an element.\n * @param {Node} node The node to get the last child element of.\n * @return {Element} The last child node of `node` that is an element.\n */\ngoog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild;\n\n\n/**\n * Returns the first next sibling that is an element.\n * @param {Node} node The node to get the next sibling element of.\n * @return {Element} The next sibling of `node` that is an element.\n */\ngoog.dom.DomHelper.prototype.getNextElementSibling =\n goog.dom.getNextElementSibling;\n\n\n/**\n * Returns the first previous sibling that is an element.\n * @param {Node} node The node to get the previous sibling element of.\n * @return {Element} The first previous sibling of `node` that is\n * an element.\n */\ngoog.dom.DomHelper.prototype.getPreviousElementSibling =\n goog.dom.getPreviousElementSibling;\n\n\n/**\n * Returns the next node in source order from the given node.\n * @param {Node} node The node.\n * @return {Node} The next node in the DOM tree, or null if this was the last\n * node.\n */\ngoog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode;\n\n\n/**\n * Returns the previous node in source order from the given node.\n * @param {Node} node The node.\n * @return {Node} The previous node in the DOM tree, or null if this was the\n * first node.\n */\ngoog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode;\n\n\n/**\n * Whether the object looks like a DOM node.\n * @param {?} obj The object being tested for node likeness.\n * @return {boolean} Whether the object looks like a DOM node.\n */\ngoog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;\n\n\n/**\n * Whether the object looks like an Element.\n * @param {?} obj The object being tested for Element likeness.\n * @return {boolean} Whether the object looks like an Element.\n */\ngoog.dom.DomHelper.prototype.isElement = goog.dom.isElement;\n\n\n/**\n * Returns true if the specified value is a Window object. This includes the\n * global window for HTML pages, and iframe windows.\n * @param {?} obj Variable to test.\n * @return {boolean} Whether the variable is a window.\n */\ngoog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow;\n\n\n/**\n * Returns an element's parent, if it's an Element.\n * @param {Element} element The DOM element.\n * @return {Element} The parent, or null if not an Element.\n */\ngoog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement;\n\n\n/**\n * Whether a node contains another node.\n * @param {Node} parent The node that should contain the other node.\n * @param {Node} descendant The node to test presence of.\n * @return {boolean} Whether the parent node contains the descendant node.\n */\ngoog.dom.DomHelper.prototype.contains = goog.dom.contains;\n\n\n/**\n * Compares the document order of two nodes, returning 0 if they are the same\n * node, a negative number if node1 is before node2, and a positive number if\n * node2 is before node1. Note that we compare the order the tags appear in the\n * document so in the tree <b><i>text</i></b> the B node is considered to be\n * before the I node.\n *\n * @param {Node} node1 The first node to compare.\n * @param {Node} node2 The second node to compare.\n * @return {number} 0 if the nodes are the same node, a negative number if node1\n * is before node2, and a positive number if node2 is before node1.\n */\ngoog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder;\n\n\n/**\n * Find the deepest common ancestor of the given nodes.\n * @param {...Node} var_args The nodes to find a common ancestor of.\n * @return {Node} The common ancestor of the nodes, or null if there is none.\n * null will only be returned if two or more of the nodes are from different\n * documents.\n */\ngoog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor;\n\n\n/**\n * Returns the owner document for a node.\n * @param {Node} node The node to get the document for.\n * @return {!Document} The document owning the node.\n */\ngoog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;\n\n\n/**\n * Cross browser function for getting the document element of an iframe.\n * @param {Element} iframe Iframe element.\n * @return {!Document} The frame content document.\n */\ngoog.dom.DomHelper.prototype.getFrameContentDocument =\n goog.dom.getFrameContentDocument;\n\n\n/**\n * Cross browser function for getting the window of a frame or iframe.\n * @param {Element} frame Frame element.\n * @return {Window} The window associated with the given frame.\n */\ngoog.dom.DomHelper.prototype.getFrameContentWindow =\n goog.dom.getFrameContentWindow;\n\n\n/**\n * Sets the text content of a node, with cross-browser support.\n * @param {Node} node The node to change the text content of.\n * @param {string|number} text The value that should replace the node's content.\n */\ngoog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent;\n\n\n/**\n * Gets the outerHTML of a node, which islike innerHTML, except that it\n * actually contains the HTML of the node itself.\n * @param {Element} element The element to get the HTML of.\n * @return {string} The outerHTML of the given element.\n */\ngoog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml;\n\n\n/**\n * Finds the first descendant node that matches the filter function. This does\n * a depth first search.\n * @param {Node} root The root of the tree to search.\n * @param {function(Node) : boolean} p The filter function.\n * @return {Node|undefined} The found node or undefined if none is found.\n */\ngoog.dom.DomHelper.prototype.findNode = goog.dom.findNode;\n\n\n/**\n * Finds all the descendant nodes that matches the filter function. This does a\n * depth first search.\n * @param {Node} root The root of the tree to search.\n * @param {function(Node) : boolean} p The filter function.\n * @return {Array<Node>} The found nodes or an empty array if none are found.\n */\ngoog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes;\n\n\n/**\n * Returns true if the element has a tab index that allows it to receive\n * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements\n * natively support keyboard focus, even if they have no tab index.\n * @param {!Element} element Element to check.\n * @return {boolean} Whether the element has a tab index that allows keyboard\n * focus.\n */\ngoog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex;\n\n\n/**\n * Enables or disables keyboard focus support on the element via its tab index.\n * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true\n * (or elements that natively support keyboard focus, like form elements) can\n * receive keyboard focus. See http://go/tabindex for more info.\n * @param {Element} element Element whose tab index is to be changed.\n * @param {boolean} enable Whether to set or remove a tab index on the element\n * that supports keyboard focus.\n */\ngoog.dom.DomHelper.prototype.setFocusableTabIndex =\n goog.dom.setFocusableTabIndex;\n\n\n/**\n * Returns true if the element can be focused, i.e. it has a tab index that\n * allows it to receive keyboard focus (tabIndex >= 0), or it is an element\n * that natively supports keyboard focus.\n * @param {!Element} element Element to check.\n * @return {boolean} Whether the element allows keyboard focus.\n */\ngoog.dom.DomHelper.prototype.isFocusable = goog.dom.isFocusable;\n\n\n/**\n * Returns the text contents of the current node, without markup. New lines are\n * stripped and whitespace is collapsed, such that each character would be\n * visible.\n *\n * In browsers that support it, innerText is used. Other browsers attempt to\n * simulate it via node traversal. Line breaks are canonicalized in IE.\n *\n * @param {Node} node The node from which we are getting content.\n * @return {string} The text content.\n */\ngoog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;\n\n\n/**\n * Returns the text length of the text contained in a node, without markup. This\n * is equivalent to the selection length if the node was selected, or the number\n * of cursor movements to traverse the node. Images & BRs take one space. New\n * lines are ignored.\n *\n * @param {Node} node The node whose text content length is being calculated.\n * @return {number} The length of `node`'s text content.\n */\ngoog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength;\n\n\n/**\n * Returns the text offset of a node relative to one of its ancestors. The text\n * length is the same as the length calculated by\n * `goog.dom.getNodeTextLength`.\n *\n * @param {Node} node The node whose offset is being calculated.\n * @param {Node=} opt_offsetParent Defaults to the node's owner document's body.\n * @return {number} The text offset.\n */\ngoog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset;\n\n\n/**\n * Returns the node at a given offset in a parent node. If an object is\n * provided for the optional third parameter, the node and the remainder of the\n * offset will stored as properties of this object.\n * @param {Node} parent The parent node.\n * @param {number} offset The offset into the parent node.\n * @param {Object=} opt_result Object to be used to store the return value. The\n * return value will be stored in the form {node: Node, remainder: number}\n * if this object is provided.\n * @return {Node} The node at the given offset.\n */\ngoog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset;\n\n\n/**\n * Returns true if the object is a `NodeList`. To qualify as a NodeList,\n * the object must have a numeric length property and an item function (which\n * has type 'string' on IE for some reason).\n * @param {Object} val Object to test.\n * @return {boolean} Whether the object is a NodeList.\n */\ngoog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList;\n\n\n/**\n * Walks up the DOM hierarchy returning the first ancestor that has the passed\n * tag name and/or class name. If the passed element matches the specified\n * criteria, the element itself is returned.\n * @param {Node} element The DOM node to start with.\n * @param {?(goog.dom.TagName<T>|string)=} opt_tag The tag name to match (or\n * null/undefined to match only based on class name).\n * @param {?string=} opt_class The class name to match (or null/undefined to\n * match only based on tag name).\n * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the\n * dom.\n * @return {?R} The first ancestor that matches the passed criteria, or\n * null if no match is found. The return type is {?Element} if opt_tag is\n * not a member of goog.dom.TagName or a more specific type if it is (e.g.\n * {?HTMLAnchorElement} for goog.dom.TagName.A).\n * @template T\n * @template R := cond(isUnknown(T), 'Element', T) =:\n */\ngoog.dom.DomHelper.prototype.getAncestorByTagNameAndClass =\n goog.dom.getAncestorByTagNameAndClass;\n\n\n/**\n * Walks up the DOM hierarchy returning the first ancestor that has the passed\n * class name. If the passed element matches the specified criteria, the\n * element itself is returned.\n * @param {Node} element The DOM node to start with.\n * @param {string} class The class name to match.\n * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the\n * dom.\n * @return {Element} The first ancestor that matches the passed criteria, or\n * null if none match.\n */\ngoog.dom.DomHelper.prototype.getAncestorByClass = goog.dom.getAncestorByClass;\n\n\n/**\n * Walks up the DOM hierarchy returning the first ancestor that passes the\n * matcher function.\n * @param {Node} element The DOM node to start with.\n * @param {function(Node) : boolean} matcher A function that returns true if the\n * passed node matches the desired criteria.\n * @param {boolean=} opt_includeNode If true, the node itself is included in\n * the search (the first call to the matcher will pass startElement as\n * the node to test).\n * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the\n * dom.\n * @return {Node} DOM node that matched the matcher, or null if there was\n * no match.\n */\ngoog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;\n\n\n/**\n * Gets '2d' context of a canvas. Shortcut for canvas.getContext('2d') with a\n * type information.\n * @param {!HTMLCanvasElement} canvas\n * @return {!CanvasRenderingContext2D}\n */\ngoog.dom.DomHelper.prototype.getCanvasContext2D = goog.dom.getCanvasContext2D;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a function to schedule running a function as soon\n * as possible after the current JS execution stops and yields to the event\n * loop.\n */\n\ngoog.provide('goog.async.nextTick');\ngoog.provide('goog.async.throwException');\n\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.dom');\ngoog.require('goog.dom.TagName');\ngoog.require('goog.dom.safe');\ngoog.require('goog.functions');\ngoog.require('goog.html.SafeHtml');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.labs.userAgent.engine');\ngoog.require('goog.string.Const');\n\n\n/**\n * Throw an item without interrupting the current execution context. For\n * example, if processing a group of items in a loop, sometimes it is useful\n * to report an error while still allowing the rest of the batch to be\n * processed.\n * @param {*} exception\n */\ngoog.async.throwException = function(exception) {\n // Each throw needs to be in its own context.\n goog.global.setTimeout(function() { throw exception; }, 0);\n};\n\n\n/**\n * Fires the provided callbacks as soon as possible after the current JS\n * execution context. setTimeout(…, 0) takes at least 4ms when called from\n * within another setTimeout(…, 0) for legacy reasons.\n *\n * This will not schedule the callback as a microtask (i.e. a task that can\n * preempt user input or networking callbacks). It is meant to emulate what\n * setTimeout(_, 0) would do if it were not throttled. If you desire microtask\n * behavior, use {@see goog.Promise} instead.\n *\n * @param {function(this:SCOPE)} callback Callback function to fire as soon as\n * possible.\n * @param {SCOPE=} opt_context Object in whose scope to call the listener.\n * @param {boolean=} opt_useSetImmediate Avoid the IE workaround that\n * ensures correctness at the cost of speed. See comments for details.\n * @template SCOPE\n */\ngoog.async.nextTick = function(callback, opt_context, opt_useSetImmediate) {\n var cb = callback;\n if (opt_context) {\n cb = goog.bind(callback, opt_context);\n }\n cb = goog.async.nextTick.wrapCallback_(cb);\n // Note we do allow callers to also request setImmediate if they are willing\n // to accept the possible tradeoffs of incorrectness in exchange for speed.\n // The IE fallback of readystate change is much slower. See useSetImmediate_\n // for details.\n if (goog.isFunction(goog.global.setImmediate) &&\n (opt_useSetImmediate || goog.async.nextTick.useSetImmediate_())) {\n goog.global.setImmediate(cb);\n return;\n }\n\n // Look for and cache the custom fallback version of setImmediate.\n if (!goog.async.nextTick.setImmediate_) {\n goog.async.nextTick.setImmediate_ =\n goog.async.nextTick.getSetImmediateEmulator_();\n }\n goog.async.nextTick.setImmediate_(cb);\n};\n\n\n/**\n * Returns whether should use setImmediate implementation currently on window.\n *\n * window.setImmediate was introduced and currently only supported by IE10+,\n * but due to a bug in the implementation it is not guaranteed that\n * setImmediate is faster than setTimeout nor that setImmediate N is before\n * setImmediate N+1. That is why we do not use the native version if\n * available. We do, however, call setImmediate if it is a non-native function\n * because that indicates that it has been replaced by goog.testing.MockClock\n * which we do want to support.\n * See\n * http://connect.microsoft.com/IE/feedback/details/801823/setimmediate-and-messagechannel-are-broken-in-ie10\n *\n * @return {boolean} Whether to use the implementation of setImmediate defined\n * on Window.\n * @private\n * @suppress {missingProperties} For \"Window.prototype.setImmediate\"\n */\ngoog.async.nextTick.useSetImmediate_ = function() {\n // Not a browser environment.\n if (!goog.global.Window || !goog.global.Window.prototype) {\n return true;\n }\n\n // MS Edge has window.setImmediate natively, but it's not on Window.prototype.\n // Also, there's no clean way to detect if the goog.global.setImmediate has\n // been replaced by mockClock as its replacement also shows up as \"[native\n // code]\" when using toString. Therefore, just always use\n // goog.global.setImmediate for Edge. It's unclear if it suffers the same\n // issues as IE10/11, but based on\n // https://dev.modern.ie/testdrive/demos/setimmediatesorting/\n // it seems they've been working to ensure it's WAI.\n if (goog.labs.userAgent.browser.isEdge() ||\n goog.global.Window.prototype.setImmediate != goog.global.setImmediate) {\n // Something redefined setImmediate in which case we decide to use it (This\n // is so that we use the mockClock setImmediate).\n return true;\n }\n\n return false;\n};\n\n\n/**\n * Cache for the setImmediate implementation.\n * @type {function(function())}\n * @private\n */\ngoog.async.nextTick.setImmediate_;\n\n\n/**\n * Determines the best possible implementation to run a function as soon as\n * the JS event loop is idle.\n * @return {function(function())} The \"setImmediate\" implementation.\n * @private\n */\ngoog.async.nextTick.getSetImmediateEmulator_ = function() {\n // Create a private message channel and use it to postMessage empty messages\n // to ourselves.\n /** @type {!Function|undefined} */\n var Channel = goog.global['MessageChannel'];\n // If MessageChannel is not available and we are in a browser, implement\n // an iframe based polyfill in browsers that have postMessage and\n // document.addEventListener. The latter excludes IE8 because it has a\n // synchronous postMessage implementation.\n if (typeof Channel === 'undefined' && typeof window !== 'undefined' &&\n window.postMessage && window.addEventListener &&\n // Presto (The old pre-blink Opera engine) has problems with iframes\n // and contentWindow.\n !goog.labs.userAgent.engine.isPresto()) {\n /** @constructor */\n Channel = function() {\n // Make an empty, invisible iframe.\n var iframe = goog.dom.createElement(goog.dom.TagName.IFRAME);\n iframe.style.display = 'none';\n goog.dom.safe.setIframeSrc(\n iframe,\n goog.html.TrustedResourceUrl.fromConstant(goog.string.Const.EMPTY));\n document.documentElement.appendChild(iframe);\n var win = iframe.contentWindow;\n var doc = win.document;\n doc.open();\n goog.dom.safe.documentWrite(doc, goog.html.SafeHtml.EMPTY);\n doc.close();\n // Do not post anything sensitive over this channel, as the workaround for\n // pages with file: origin could allow that information to be modified or\n // intercepted.\n var message = 'callImmediate' + Math.random();\n // The same origin policy rejects attempts to postMessage from file: urls\n // unless the origin is '*'.\n var origin = win.location.protocol == 'file:' ?\n '*' :\n win.location.protocol + '//' + win.location.host;\n var onmessage = goog.bind(function(e) {\n // Validate origin and message to make sure that this message was\n // intended for us. If the origin is set to '*' (see above) only the\n // message needs to match since, for example, '*' != 'file://'. Allowing\n // the wildcard is ok, as we are not concerned with security here.\n if ((origin != '*' && e.origin != origin) || e.data != message) {\n return;\n }\n this['port1'].onmessage();\n }, this);\n win.addEventListener('message', onmessage, false);\n this['port1'] = {};\n this['port2'] = {\n postMessage: function() { win.postMessage(message, origin); }\n };\n };\n }\n if (typeof Channel !== 'undefined' && !goog.labs.userAgent.browser.isIE()) {\n // Exclude all of IE due to\n // http://codeforhire.com/2013/09/21/setimmediate-and-messagechannel-broken-on-internet-explorer-10/\n // which allows starving postMessage with a busy setTimeout loop.\n // This currently affects IE10 and IE11 which would otherwise be able\n // to use the postMessage based fallbacks.\n var channel = new Channel();\n // Use a fifo linked list to call callbacks in the right order.\n var head = {};\n var tail = head;\n channel['port1'].onmessage = function() {\n if (head.next !== undefined) {\n head = head.next;\n var cb = head.cb;\n head.cb = null;\n cb();\n }\n };\n return function(cb) {\n tail.next = {cb: cb};\n tail = tail.next;\n channel['port2'].postMessage(0);\n };\n }\n // Fall back to setTimeout with 0. In browsers this creates a delay of 5ms\n // or more.\n // NOTE(user): This fallback is used for IE.\n return function(cb) {\n goog.global.setTimeout(/** @type {function()} */ (cb), 0);\n };\n};\n\n\n/**\n * Helper function that is overrided to protect callbacks with entry point\n * monitor if the application monitors entry points.\n * @param {function()} callback Callback function to fire as soon as possible.\n * @return {function()} The wrapped callback.\n * @private\n */\ngoog.async.nextTick.wrapCallback_ = goog.functions.identity;\n\n\n// Register the callback function as an entry point, so that it can be\n// monitored for exception handling, etc. This has to be done in this file\n// since it requires special code to handle all browsers.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) { goog.async.nextTick.wrapCallback_ = transformer; });\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.async.run');\n\ngoog.require('goog.async.WorkQueue');\ngoog.require('goog.async.nextTick');\ngoog.require('goog.async.throwException');\n\n/**\n * @define {boolean} If true, use the global Promise to implement goog.async.run\n * assuming either the native, or polyfill version will be used. Does still\n * permit tests to use forceNextTick.\n */\ngoog.ASSUME_NATIVE_PROMISE = goog.define('goog.ASSUME_NATIVE_PROMISE', false);\n\n/**\n * Fires the provided callback just before the current callstack unwinds, or as\n * soon as possible after the current JS execution context.\n * @param {function(this:THIS)} callback\n * @param {THIS=} opt_context Object to use as the \"this value\" when calling\n * the provided function.\n * @template THIS\n */\ngoog.async.run = function(callback, opt_context) {\n if (!goog.async.run.schedule_) {\n goog.async.run.initializeRunner_();\n }\n if (!goog.async.run.workQueueScheduled_) {\n // Nothing is currently scheduled, schedule it now.\n goog.async.run.schedule_();\n goog.async.run.workQueueScheduled_ = true;\n }\n\n goog.async.run.workQueue_.add(callback, opt_context);\n};\n\n\n/**\n * Initializes the function to use to process the work queue.\n * @private\n */\ngoog.async.run.initializeRunner_ = function() {\n if (goog.ASSUME_NATIVE_PROMISE ||\n (goog.global.Promise && goog.global.Promise.resolve)) {\n // Use goog.global.Promise instead of just Promise because the relevant\n // externs may be missing, and don't alias it because this could confuse the\n // compiler into thinking the polyfill is required when it should be treated\n // as optional.\n var promise = goog.global.Promise.resolve(undefined);\n goog.async.run.schedule_ = function() {\n promise.then(goog.async.run.processWorkQueue);\n };\n } else {\n goog.async.run.schedule_ = function() {\n goog.async.nextTick(goog.async.run.processWorkQueue);\n };\n }\n};\n\n\n/**\n * Forces goog.async.run to use nextTick instead of Promise.\n *\n * This should only be done in unit tests. It's useful because MockClock\n * replaces nextTick, but not the browser Promise implementation, so it allows\n * Promise-based code to be tested with MockClock.\n *\n * However, we also want to run promises if the MockClock is no longer in\n * control so we schedule a backup \"setTimeout\" to the unmocked timeout if\n * provided.\n *\n * @param {function(function())=} opt_realSetTimeout\n */\ngoog.async.run.forceNextTick = function(opt_realSetTimeout) {\n goog.async.run.schedule_ = function() {\n goog.async.nextTick(goog.async.run.processWorkQueue);\n if (opt_realSetTimeout) {\n opt_realSetTimeout(goog.async.run.processWorkQueue);\n }\n };\n};\n\n\n/**\n * The function used to schedule work asynchronousely.\n * @private {function()}\n */\ngoog.async.run.schedule_;\n\n\n/** @private {boolean} */\ngoog.async.run.workQueueScheduled_ = false;\n\n\n/** @private {!goog.async.WorkQueue} */\ngoog.async.run.workQueue_ = new goog.async.WorkQueue();\n\n\nif (goog.DEBUG) {\n /**\n * Reset the work queue. Only available for tests in debug mode.\n */\n goog.async.run.resetQueue = function() {\n goog.async.run.workQueueScheduled_ = false;\n goog.async.run.workQueue_ = new goog.async.WorkQueue();\n };\n}\n\n\n/**\n * Run any pending goog.async.run work items. This function is not intended\n * for general use, but for use by entry point handlers to run items ahead of\n * goog.async.nextTick.\n */\ngoog.async.run.processWorkQueue = function() {\n // NOTE: additional work queue items may be added while processing.\n var item = null;\n while (item = goog.async.run.workQueue_.remove()) {\n try {\n item.fn.call(item.scope);\n } catch (e) {\n goog.async.throwException(e);\n }\n goog.async.run.workQueue_.returnUnused(item);\n }\n\n // There are no more work items, allow processing to be scheduled again.\n goog.async.run.workQueueScheduled_ = false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Type-safe wrappers for unsafe DOM APIs.\n *\n * This file provides type-safe wrappers for DOM APIs that can result in\n * cross-site scripting (XSS) vulnerabilities, if the API is supplied with\n * untrusted (attacker-controlled) input. Instead of plain strings, the type\n * safe wrappers consume values of types from the goog.html package whose\n * contract promises that values are safe to use in the corresponding context.\n *\n * Hence, a program that exclusively uses the wrappers in this file (i.e., whose\n * only reference to security-sensitive raw DOM APIs are in this file) is\n * guaranteed to be free of XSS due to incorrect use of such DOM APIs (modulo\n * correctness of code that produces values of the respective goog.html types,\n * and absent code that violates type safety).\n *\n * For example, assigning to an element's .innerHTML property a string that is\n * derived (even partially) from untrusted input typically results in an XSS\n * vulnerability. The type-safe wrapper goog.dom.safe.setInnerHtml consumes a\n * value of type goog.html.SafeHtml, whose contract states that using its values\n * in a HTML context will not result in XSS. Hence a program that is free of\n * direct assignments to any element's innerHTML property (with the exception of\n * the assignment to .innerHTML in this file) is guaranteed to be free of XSS\n * due to assignment of untrusted strings to the innerHTML property.\n */\n\ngoog.provide('goog.dom.safe');\ngoog.provide('goog.dom.safe.InsertAdjacentHtmlPosition');\n\ngoog.require('goog.asserts');\ngoog.require('goog.dom.asserts');\ngoog.require('goog.functions');\ngoog.require('goog.html.SafeHtml');\ngoog.require('goog.html.SafeScript');\ngoog.require('goog.html.SafeStyle');\ngoog.require('goog.html.SafeUrl');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.internal');\n\n\n/** @enum {string} */\ngoog.dom.safe.InsertAdjacentHtmlPosition = {\n AFTERBEGIN: 'afterbegin',\n AFTEREND: 'afterend',\n BEFOREBEGIN: 'beforebegin',\n BEFOREEND: 'beforeend'\n};\n\n\n/**\n * Inserts known-safe HTML into a Node, at the specified position.\n * @param {!Node} node The node on which to call insertAdjacentHTML.\n * @param {!goog.dom.safe.InsertAdjacentHtmlPosition} position Position where\n * to insert the HTML.\n * @param {!goog.html.SafeHtml} html The known-safe HTML to insert.\n */\ngoog.dom.safe.insertAdjacentHtml = function(node, position, html) {\n node.insertAdjacentHTML(position, goog.html.SafeHtml.unwrapTrustedHTML(html));\n};\n\n\n/**\n * Tags not allowed in goog.dom.safe.setInnerHtml.\n * @private @const {!Object<string, boolean>}\n */\ngoog.dom.safe.SET_INNER_HTML_DISALLOWED_TAGS_ = {\n 'MATH': true,\n 'SCRIPT': true,\n 'STYLE': true,\n 'SVG': true,\n 'TEMPLATE': true\n};\n\n\n/**\n * Whether assigning to innerHTML results in a non-spec-compliant clean-up. Used\n * to define goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse.\n *\n * <p>As mentioned in https://stackoverflow.com/questions/28741528, re-rendering\n * an element in IE by setting innerHTML causes IE to recursively disconnect all\n * parent/children connections that were in the previous contents of the\n * element. Unfortunately, this can unexpectedly result in confusing cases where\n * a function is run (typically asynchronously) on element that has since\n * disconnected from the DOM but assumes the presence of its children. A simple\n * workaround is to remove all children first. Testing on IE11 via\n * https://jsperf.com/innerhtml-vs-removechild/239, removeChild seems to be\n * ~10x faster than innerHTML='' for a large number of children (perhaps due\n * to the latter's recursive behavior), implying that this workaround would\n * not hurt performance and might actually improve it.\n * @return {boolean}\n * @private\n */\ngoog.dom.safe.isInnerHtmlCleanupRecursive_ =\n goog.functions.cacheReturnValue(function() {\n // `document` missing in some test frameworks.\n if (goog.DEBUG && typeof document === 'undefined') {\n return false;\n }\n // Create 3 nested <div>s without using innerHTML.\n // We're not chaining the appendChilds in one call, as this breaks\n // in a DocumentFragment.\n var div = document.createElement('div');\n var childDiv = document.createElement('div');\n childDiv.appendChild(document.createElement('div'));\n div.appendChild(childDiv);\n // `firstChild` is null in Google Js Test.\n if (goog.DEBUG && !div.firstChild) {\n return false;\n }\n var innerChild = div.firstChild.firstChild;\n div.innerHTML =\n goog.html.SafeHtml.unwrapTrustedHTML(goog.html.SafeHtml.EMPTY);\n return !innerChild.parentElement;\n });\n\n\n/**\n * Assigns HTML to an element's innerHTML property. Helper to use only here and\n * in soy.js.\n * @param {?Element} elem The element whose innerHTML is to be assigned to.\n * @param {!goog.html.SafeHtml} html\n */\ngoog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse = function(elem, html) {\n // See comment above goog.dom.safe.isInnerHtmlCleanupRecursive_.\n if (goog.dom.safe.isInnerHtmlCleanupRecursive_()) {\n while (elem.lastChild) {\n elem.removeChild(elem.lastChild);\n }\n }\n elem.innerHTML = goog.html.SafeHtml.unwrapTrustedHTML(html);\n};\n\n\n/**\n * Assigns known-safe HTML to an element's innerHTML property.\n * @param {!Element} elem The element whose innerHTML is to be assigned to.\n * @param {!goog.html.SafeHtml} html The known-safe HTML to assign.\n * @throws {Error} If called with one of these tags: math, script, style, svg,\n * template.\n */\ngoog.dom.safe.setInnerHtml = function(elem, html) {\n if (goog.asserts.ENABLE_ASSERTS) {\n var tagName = elem.tagName.toUpperCase();\n if (goog.dom.safe.SET_INNER_HTML_DISALLOWED_TAGS_[tagName]) {\n throw new Error(\n 'goog.dom.safe.setInnerHtml cannot be used to set content of ' +\n elem.tagName + '.');\n }\n }\n\n goog.dom.safe.unsafeSetInnerHtmlDoNotUseOrElse(elem, html);\n};\n\n\n/**\n * Assigns known-safe HTML to an element's outerHTML property.\n * @param {!Element} elem The element whose outerHTML is to be assigned to.\n * @param {!goog.html.SafeHtml} html The known-safe HTML to assign.\n */\ngoog.dom.safe.setOuterHtml = function(elem, html) {\n elem.outerHTML = goog.html.SafeHtml.unwrapTrustedHTML(html);\n};\n\n\n/**\n * Safely assigns a URL a form element's action property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * form's action property. If url is of type string however, it is first\n * sanitized using goog.html.SafeUrl.sanitize.\n *\n * Example usage:\n * goog.dom.safe.setFormElementAction(formEl, url);\n * which is a safe alternative to\n * formEl.action = url;\n * The latter can result in XSS vulnerabilities if url is a\n * user-/attacker-controlled value.\n *\n * @param {!Element} form The form element whose action property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setFormElementAction = function(form, url) {\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n goog.dom.asserts.assertIsHTMLFormElement(form).action =\n goog.html.SafeUrl.unwrap(safeUrl);\n};\n\n/**\n * Safely assigns a URL to a button element's formaction property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * button's formaction property. If url is of type string however, it is first\n * sanitized using goog.html.SafeUrl.sanitize.\n *\n * Example usage:\n * goog.dom.safe.setButtonFormAction(buttonEl, url);\n * which is a safe alternative to\n * buttonEl.action = url;\n * The latter can result in XSS vulnerabilities if url is a\n * user-/attacker-controlled value.\n *\n * @param {!Element} button The button element whose action property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setButtonFormAction = function(button, url) {\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n goog.dom.asserts.assertIsHTMLButtonElement(button).formAction =\n goog.html.SafeUrl.unwrap(safeUrl);\n};\n/**\n * Safely assigns a URL to an input element's formaction property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * input's formaction property. If url is of type string however, it is first\n * sanitized using goog.html.SafeUrl.sanitize.\n *\n * Example usage:\n * goog.dom.safe.setInputFormAction(inputEl, url);\n * which is a safe alternative to\n * inputEl.action = url;\n * The latter can result in XSS vulnerabilities if url is a\n * user-/attacker-controlled value.\n *\n * @param {!Element} input The input element whose action property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setInputFormAction = function(input, url) {\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n goog.dom.asserts.assertIsHTMLInputElement(input).formAction =\n goog.html.SafeUrl.unwrap(safeUrl);\n};\n\n/**\n * Sets the given element's style property to the contents of the provided\n * SafeStyle object.\n * @param {!Element} elem\n * @param {!goog.html.SafeStyle} style\n */\ngoog.dom.safe.setStyle = function(elem, style) {\n elem.style.cssText = goog.html.SafeStyle.unwrap(style);\n};\n\n\n/**\n * Writes known-safe HTML to a document.\n * @param {!Document} doc The document to be written to.\n * @param {!goog.html.SafeHtml} html The known-safe HTML to assign.\n */\ngoog.dom.safe.documentWrite = function(doc, html) {\n doc.write(goog.html.SafeHtml.unwrapTrustedHTML(html));\n};\n\n\n/**\n * Safely assigns a URL to an anchor element's href property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * anchor's href property. If url is of type string however, it is first\n * sanitized using goog.html.SafeUrl.sanitize.\n *\n * Example usage:\n * goog.dom.safe.setAnchorHref(anchorEl, url);\n * which is a safe alternative to\n * anchorEl.href = url;\n * The latter can result in XSS vulnerabilities if url is a\n * user-/attacker-controlled value.\n *\n * @param {!HTMLAnchorElement} anchor The anchor element whose href property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setAnchorHref = function(anchor, url) {\n goog.dom.asserts.assertIsHTMLAnchorElement(anchor);\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n anchor.href = goog.html.SafeUrl.unwrap(safeUrl);\n};\n\n\n/**\n * Safely assigns a URL to an image element's src property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * image's src property. If url is of type string however, it is first\n * sanitized using goog.html.SafeUrl.sanitize.\n *\n * @param {!HTMLImageElement} imageElement The image element whose src property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setImageSrc = function(imageElement, url) {\n goog.dom.asserts.assertIsHTMLImageElement(imageElement);\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n var allowDataUrl = /^data:image\\//i.test(url);\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url, allowDataUrl);\n }\n imageElement.src = goog.html.SafeUrl.unwrap(safeUrl);\n};\n\n/**\n * Safely assigns a URL to a audio element's src property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * audio's src property. If url is of type string however, it is first\n * sanitized using goog.html.SafeUrl.sanitize.\n *\n * @param {!HTMLAudioElement} audioElement The audio element whose src property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setAudioSrc = function(audioElement, url) {\n goog.dom.asserts.assertIsHTMLAudioElement(audioElement);\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n var allowDataUrl = /^data:audio\\//i.test(url);\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url, allowDataUrl);\n }\n audioElement.src = goog.html.SafeUrl.unwrap(safeUrl);\n};\n\n/**\n * Safely assigns a URL to a video element's src property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * video's src property. If url is of type string however, it is first\n * sanitized using goog.html.SafeUrl.sanitize.\n *\n * @param {!HTMLVideoElement} videoElement The video element whose src property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setVideoSrc = function(videoElement, url) {\n goog.dom.asserts.assertIsHTMLVideoElement(videoElement);\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n var allowDataUrl = /^data:video\\//i.test(url);\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url, allowDataUrl);\n }\n videoElement.src = goog.html.SafeUrl.unwrap(safeUrl);\n};\n\n/**\n * Safely assigns a URL to an embed element's src property.\n *\n * Example usage:\n * goog.dom.safe.setEmbedSrc(embedEl, url);\n * which is a safe alternative to\n * embedEl.src = url;\n * The latter can result in loading untrusted code unless it is ensured that\n * the URL refers to a trustworthy resource.\n *\n * @param {!HTMLEmbedElement} embed The embed element whose src property\n * is to be assigned to.\n * @param {!goog.html.TrustedResourceUrl} url The URL to assign.\n */\ngoog.dom.safe.setEmbedSrc = function(embed, url) {\n goog.dom.asserts.assertIsHTMLEmbedElement(embed);\n embed.src = goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(url);\n};\n\n\n/**\n * Safely assigns a URL to a frame element's src property.\n *\n * Example usage:\n * goog.dom.safe.setFrameSrc(frameEl, url);\n * which is a safe alternative to\n * frameEl.src = url;\n * The latter can result in loading untrusted code unless it is ensured that\n * the URL refers to a trustworthy resource.\n *\n * @param {!HTMLFrameElement} frame The frame element whose src property\n * is to be assigned to.\n * @param {!goog.html.TrustedResourceUrl} url The URL to assign.\n */\ngoog.dom.safe.setFrameSrc = function(frame, url) {\n goog.dom.asserts.assertIsHTMLFrameElement(frame);\n frame.src = goog.html.TrustedResourceUrl.unwrap(url);\n};\n\n\n/**\n * Safely assigns a URL to an iframe element's src property.\n *\n * Example usage:\n * goog.dom.safe.setIframeSrc(iframeEl, url);\n * which is a safe alternative to\n * iframeEl.src = url;\n * The latter can result in loading untrusted code unless it is ensured that\n * the URL refers to a trustworthy resource.\n *\n * @param {!HTMLIFrameElement} iframe The iframe element whose src property\n * is to be assigned to.\n * @param {!goog.html.TrustedResourceUrl} url The URL to assign.\n */\ngoog.dom.safe.setIframeSrc = function(iframe, url) {\n goog.dom.asserts.assertIsHTMLIFrameElement(iframe);\n iframe.src = goog.html.TrustedResourceUrl.unwrap(url);\n};\n\n\n/**\n * Safely assigns HTML to an iframe element's srcdoc property.\n *\n * Example usage:\n * goog.dom.safe.setIframeSrcdoc(iframeEl, safeHtml);\n * which is a safe alternative to\n * iframeEl.srcdoc = html;\n * The latter can result in loading untrusted code.\n *\n * @param {!HTMLIFrameElement} iframe The iframe element whose srcdoc property\n * is to be assigned to.\n * @param {!goog.html.SafeHtml} html The HTML to assign.\n */\ngoog.dom.safe.setIframeSrcdoc = function(iframe, html) {\n goog.dom.asserts.assertIsHTMLIFrameElement(iframe);\n iframe.srcdoc = goog.html.SafeHtml.unwrapTrustedHTML(html);\n};\n\n\n/**\n * Safely sets a link element's href and rel properties. Whether or not\n * the URL assigned to href has to be a goog.html.TrustedResourceUrl\n * depends on the value of the rel property. If rel contains \"stylesheet\"\n * then a TrustedResourceUrl is required.\n *\n * Example usage:\n * goog.dom.safe.setLinkHrefAndRel(linkEl, url, 'stylesheet');\n * which is a safe alternative to\n * linkEl.rel = 'stylesheet';\n * linkEl.href = url;\n * The latter can result in loading untrusted code unless it is ensured that\n * the URL refers to a trustworthy resource.\n *\n * @param {!HTMLLinkElement} link The link element whose href property\n * is to be assigned to.\n * @param {string|!goog.html.SafeUrl|!goog.html.TrustedResourceUrl} url The URL\n * to assign to the href property. Must be a TrustedResourceUrl if the\n * value assigned to rel contains \"stylesheet\". A string value is\n * sanitized with goog.html.SafeUrl.sanitize.\n * @param {string} rel The value to assign to the rel property.\n * @throws {Error} if rel contains \"stylesheet\" and url is not a\n * TrustedResourceUrl\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setLinkHrefAndRel = function(link, url, rel) {\n goog.dom.asserts.assertIsHTMLLinkElement(link);\n link.rel = rel;\n if (goog.string.internal.caseInsensitiveContains(rel, 'stylesheet')) {\n goog.asserts.assert(\n url instanceof goog.html.TrustedResourceUrl,\n 'URL must be TrustedResourceUrl because \"rel\" contains \"stylesheet\"');\n link.href = goog.html.TrustedResourceUrl.unwrap(url);\n } else if (url instanceof goog.html.TrustedResourceUrl) {\n link.href = goog.html.TrustedResourceUrl.unwrap(url);\n } else if (url instanceof goog.html.SafeUrl) {\n link.href = goog.html.SafeUrl.unwrap(url);\n } else { // string\n // SafeUrl.sanitize must return legitimate SafeUrl when passed a string.\n link.href = goog.html.SafeUrl.unwrap(\n goog.html.SafeUrl.sanitizeAssertUnchanged(url));\n }\n};\n\n\n/**\n * Safely assigns a URL to an object element's data property.\n *\n * Example usage:\n * goog.dom.safe.setObjectData(objectEl, url);\n * which is a safe alternative to\n * objectEl.data = url;\n * The latter can result in loading untrusted code unless setit is ensured that\n * the URL refers to a trustworthy resource.\n *\n * @param {!HTMLObjectElement} object The object element whose data property\n * is to be assigned to.\n * @param {!goog.html.TrustedResourceUrl} url The URL to assign.\n */\ngoog.dom.safe.setObjectData = function(object, url) {\n goog.dom.asserts.assertIsHTMLObjectElement(object);\n object.data = goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(url);\n};\n\n\n/**\n * Safely assigns a URL to a script element's src property.\n *\n * Example usage:\n * goog.dom.safe.setScriptSrc(scriptEl, url);\n * which is a safe alternative to\n * scriptEl.src = url;\n * The latter can result in loading untrusted code unless it is ensured that\n * the URL refers to a trustworthy resource.\n *\n * @param {!HTMLScriptElement} script The script element whose src property\n * is to be assigned to.\n * @param {!goog.html.TrustedResourceUrl} url The URL to assign.\n */\ngoog.dom.safe.setScriptSrc = function(script, url) {\n goog.dom.asserts.assertIsHTMLScriptElement(script);\n script.src = goog.html.TrustedResourceUrl.unwrapTrustedScriptURL(url);\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce();\n if (nonce) {\n script.setAttribute('nonce', nonce);\n }\n};\n\n\n/**\n * Safely assigns a value to a script element's content.\n *\n * Example usage:\n * goog.dom.safe.setScriptContent(scriptEl, content);\n * which is a safe alternative to\n * scriptEl.text = content;\n * The latter can result in executing untrusted code unless it is ensured that\n * the code is loaded from a trustworthy resource.\n *\n * @param {!HTMLScriptElement} script The script element whose content is being\n * set.\n * @param {!goog.html.SafeScript} content The content to assign.\n */\ngoog.dom.safe.setScriptContent = function(script, content) {\n goog.dom.asserts.assertIsHTMLScriptElement(script);\n script.text = goog.html.SafeScript.unwrapTrustedScript(content);\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce();\n if (nonce) {\n script.setAttribute('nonce', nonce);\n }\n};\n\n\n/**\n * Safely assigns a URL to a Location object's href property.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and assigned to\n * loc's href property. If url is of type string however, it is first sanitized\n * using goog.html.SafeUrl.sanitize.\n *\n * Example usage:\n * goog.dom.safe.setLocationHref(document.location, redirectUrl);\n * which is a safe alternative to\n * document.location.href = redirectUrl;\n * The latter can result in XSS vulnerabilities if redirectUrl is a\n * user-/attacker-controlled value.\n *\n * @param {!Location} loc The Location object whose href property is to be\n * assigned to.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.setLocationHref = function(loc, url) {\n goog.dom.asserts.assertIsLocation(loc);\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n loc.href = goog.html.SafeUrl.unwrap(safeUrl);\n};\n\n/**\n * Safely assigns the URL of a Location object.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and\n * passed to Location#assign. If url is of type string however, it is\n * first sanitized using goog.html.SafeUrl.sanitize.\n *\n * Example usage:\n * goog.dom.safe.assignLocation(document.location, newUrl);\n * which is a safe alternative to\n * document.location.assign(newUrl);\n * The latter can result in XSS vulnerabilities if newUrl is a\n * user-/attacker-controlled value.\n *\n * This has the same behaviour as setLocationHref, however some test\n * mock Location.assign instead of a property assignment.\n *\n * @param {!Location} loc The Location object which is to be assigned.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.assignLocation = function(loc, url) {\n goog.dom.asserts.assertIsLocation(loc);\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n loc.assign(goog.html.SafeUrl.unwrap(safeUrl));\n};\n\n\n/**\n * Safely replaces the URL of a Location object.\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and\n * passed to Location#replace. If url is of type string however, it is\n * first sanitized using goog.html.SafeUrl.sanitize.\n *\n * Example usage:\n * goog.dom.safe.replaceLocation(document.location, newUrl);\n * which is a safe alternative to\n * document.location.replace(newUrl);\n * The latter can result in XSS vulnerabilities if newUrl is a\n * user-/attacker-controlled value.\n *\n * @param {!Location} loc The Location object which is to be replaced.\n * @param {string|!goog.html.SafeUrl} url The URL to assign.\n * @see goog.html.SafeUrl#sanitize\n */\ngoog.dom.safe.replaceLocation = function(loc, url) {\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n loc.replace(goog.html.SafeUrl.unwrap(safeUrl));\n};\n\n\n/**\n * Safely opens a URL in a new window (via window.open).\n *\n * If url is of type goog.html.SafeUrl, its value is unwrapped and passed in to\n * window.open. If url is of type string however, it is first sanitized\n * using goog.html.SafeUrl.sanitize.\n *\n * Note that this function does not prevent leakages via the referer that is\n * sent by window.open. It is advised to only use this to open 1st party URLs.\n *\n * Example usage:\n * goog.dom.safe.openInWindow(url);\n * which is a safe alternative to\n * window.open(url);\n * The latter can result in XSS vulnerabilities if redirectUrl is a\n * user-/attacker-controlled value.\n *\n * @param {string|!goog.html.SafeUrl} url The URL to open.\n * @param {Window=} opt_openerWin Window of which to call the .open() method.\n * Defaults to the global window.\n * @param {!goog.string.Const=} opt_name Name of the window to open in. Can be\n * _top, etc as allowed by window.open().\n * @param {string=} opt_specs Comma-separated list of specifications, same as\n * in window.open().\n * @param {boolean=} opt_replace Whether to replace the current entry in browser\n * history, same as in window.open().\n * @return {Window} Window the url was opened in.\n */\ngoog.dom.safe.openInWindow = function(\n url, opt_openerWin, opt_name, opt_specs, opt_replace) {\n /** @type {!goog.html.SafeUrl} */\n var safeUrl;\n if (url instanceof goog.html.SafeUrl) {\n safeUrl = url;\n } else {\n safeUrl = goog.html.SafeUrl.sanitizeAssertUnchanged(url);\n }\n var win = opt_openerWin || goog.global;\n return win.open(\n goog.html.SafeUrl.unwrap(safeUrl),\n // If opt_name is undefined, simply passing that in to open() causes IE to\n // reuse the current window instead of opening a new one. Thus we pass ''\n // in instead, which according to spec opens a new window. See\n // https://html.spec.whatwg.org/multipage/browsers.html#dom-open .\n opt_name ? goog.string.Const.unwrap(opt_name) : '', opt_specs,\n opt_replace);\n};\n\n\n/**\n * Parses the HTML as 'text/html'.\n * @param {!DOMParser} parser\n * @param {!goog.html.SafeHtml} html The HTML to be parsed.\n * @return {?Document}\n */\ngoog.dom.safe.parseFromStringHtml = function(parser, html) {\n return goog.dom.safe.parseFromString(parser, html, 'text/html');\n};\n\n\n/**\n * Parses the string.\n * @param {!DOMParser} parser\n * @param {!goog.html.SafeHtml} content Note: We don't have a special type for\n * XML od SVG supported by this function so we use SafeHtml.\n * @param {string} type\n * @return {?Document}\n */\ngoog.dom.safe.parseFromString = function(parser, content, type) {\n return parser.parseFromString(\n goog.html.SafeHtml.unwrapTrustedHTML(content), type);\n};\n\n\n/**\n * Safely creates an HTMLImageElement from a Blob.\n *\n * Example usage:\n * goog.dom.safe.createImageFromBlob(blob);\n * which is a safe alternative to\n * image.src = createObjectUrl(blob)\n * The latter can result in executing malicious same-origin scripts from a bad\n * Blob.\n * @param {!Blob} blob The blob to create the image from.\n * @return {!HTMLImageElement} The image element created from the blob.\n * @throws {!Error} If called with a Blob with a MIME type other than image/.*.\n */\ngoog.dom.safe.createImageFromBlob = function(blob) {\n // Any image/* MIME type is accepted as safe.\n if (!/^image\\/.*/g.test(blob.type)) {\n throw new Error(\n 'goog.dom.safe.createImageFromBlob only accepts MIME type image/.*.');\n }\n var objectUrl = goog.global.URL.createObjectURL(blob);\n var image = new goog.global.Image();\n image.onload = function() {\n goog.global.URL.revokeObjectURL(objectUrl);\n };\n goog.dom.safe.setImageSrc(\n image,\n goog.html.uncheckedconversions\n .safeUrlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from('Image blob URL.'), objectUrl));\n return image;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.Promise');\n\ngoog.require('goog.Thenable');\ngoog.require('goog.asserts');\ngoog.require('goog.async.FreeList');\ngoog.require('goog.async.run');\ngoog.require('goog.async.throwException');\ngoog.require('goog.debug.Error');\ngoog.require('goog.promise.Resolver');\n\n\n\n/**\n * NOTE: This class was created in anticipation of the built-in Promise type\n * being standardized and implemented across browsers. Now that Promise is\n * available in modern browsers, and is automatically polyfilled by the Closure\n * Compiler, by default, most new code should use native `Promise`\n * instead of `goog.Promise`. However, `goog.Promise` has the\n * concept of cancellation which native Promises do not yet have. So code\n * needing cancellation may still want to use `goog.Promise`.\n *\n * Promises provide a result that may be resolved asynchronously. A Promise may\n * be resolved by being fulfilled with a fulfillment value, rejected with a\n * rejection reason, or blocked by another Promise. A Promise is said to be\n * settled if it is either fulfilled or rejected. Once settled, the Promise\n * result is immutable.\n *\n * Promises may represent results of any type, including undefined. Rejection\n * reasons are typically Errors, but may also be of any type. Closure Promises\n * allow for optional type annotations that enforce that fulfillment values are\n * of the appropriate types at compile time.\n *\n * The result of a Promise is accessible by calling `then` and registering\n * `onFulfilled` and `onRejected` callbacks. Once the Promise\n * is settled, the relevant callbacks are invoked with the fulfillment value or\n * rejection reason as argument. Callbacks are always invoked in the order they\n * were registered, even when additional `then` calls are made from inside\n * another callback. A callback is always run asynchronously sometime after the\n * scope containing the registering `then` invocation has returned.\n *\n * If a Promise is resolved with another Promise, the first Promise will block\n * until the second is settled, and then assumes the same result as the second\n * Promise. This allows Promises to depend on the results of other Promises,\n * linking together multiple asynchronous operations.\n *\n * This implementation is compatible with the Promises/A+ specification and\n * passes that specification's conformance test suite. A Closure Promise may be\n * resolved with a Promise instance (or sufficiently compatible Promise-like\n * object) created by other Promise implementations. From the specification,\n * Promise-like objects are known as \"Thenables\".\n *\n * @see http://promisesaplus.com/\n *\n * @param {function(\n * this:RESOLVER_CONTEXT,\n * function((TYPE|IThenable<TYPE>|Thenable)=),\n * function(*=)): void} resolver\n * Initialization function that is invoked immediately with `resolve`\n * and `reject` functions as arguments. The Promise is resolved or\n * rejected with the first argument passed to either function.\n * @param {RESOLVER_CONTEXT=} opt_context An optional context for executing the\n * resolver function. If unspecified, the resolver function will be executed\n * in the default scope.\n * @constructor\n * @struct\n * @final\n * @implements {goog.Thenable<TYPE>}\n * @template TYPE,RESOLVER_CONTEXT\n */\ngoog.Promise = function(resolver, opt_context) {\n /**\n * The internal state of this Promise. Either PENDING, FULFILLED, REJECTED, or\n * BLOCKED.\n * @private {goog.Promise.State_}\n */\n this.state_ = goog.Promise.State_.PENDING;\n\n /**\n * The settled result of the Promise. Immutable once set with either a\n * fulfillment value or rejection reason.\n * @private {*}\n */\n this.result_ = undefined;\n\n /**\n * For Promises created by calling `then()`, the originating parent.\n * @private {?goog.Promise}\n */\n this.parent_ = null;\n\n /**\n * The linked list of `onFulfilled` and `onRejected` callbacks\n * added to this Promise by calls to `then()`.\n * @private {?goog.Promise.CallbackEntry_}\n */\n this.callbackEntries_ = null;\n\n /**\n * The tail of the linked list of `onFulfilled` and `onRejected`\n * callbacks added to this Promise by calls to `then()`.\n * @private {?goog.Promise.CallbackEntry_}\n */\n this.callbackEntriesTail_ = null;\n\n /**\n * Whether the Promise is in the queue of Promises to execute.\n * @private {boolean}\n */\n this.executing_ = false;\n\n if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {\n /**\n * A timeout ID used when the `UNHANDLED_REJECTION_DELAY` is greater\n * than 0 milliseconds. The ID is set when the Promise is rejected, and\n * cleared only if an `onRejected` callback is invoked for the\n * Promise (or one of its descendants) before the delay is exceeded.\n *\n * If the rejection is not handled before the timeout completes, the\n * rejection reason is passed to the unhandled rejection handler.\n * @private {number}\n */\n this.unhandledRejectionId_ = 0;\n } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {\n /**\n * When the `UNHANDLED_REJECTION_DELAY` is set to 0 milliseconds, a\n * boolean that is set if the Promise is rejected, and reset to false if an\n * `onRejected` callback is invoked for the Promise (or one of its\n * descendants). If the rejection is not handled before the next timestep,\n * the rejection reason is passed to the unhandled rejection handler.\n * @private {boolean}\n */\n this.hadUnhandledRejection_ = false;\n }\n\n if (goog.Promise.LONG_STACK_TRACES) {\n /**\n * A list of stack trace frames pointing to the locations where this Promise\n * was created or had callbacks added to it. Saved to add additional context\n * to stack traces when an exception is thrown.\n * @private {!Array<string>}\n */\n this.stack_ = [];\n this.addStackTrace_(new Error('created'));\n\n /**\n * Index of the most recently executed stack frame entry.\n * @private {number}\n */\n this.currentStep_ = 0;\n }\n\n // As an optimization, we can skip this if resolver is goog.nullFunction.\n // This value is passed internally when creating a promise which will be\n // resolved through a more optimized path.\n if (resolver != goog.nullFunction) {\n try {\n var self = this;\n resolver.call(\n opt_context,\n function(value) {\n self.resolve_(goog.Promise.State_.FULFILLED, value);\n },\n function(reason) {\n if (goog.DEBUG &&\n !(reason instanceof goog.Promise.CancellationError)) {\n try {\n // Promise was rejected. Step up one call frame to see why.\n if (reason instanceof Error) {\n throw reason;\n } else {\n throw new Error('Promise rejected.');\n }\n } catch (e) {\n // Only thrown so browser dev tools can catch rejections of\n // promises when the option to break on caught exceptions is\n // activated.\n }\n }\n self.resolve_(goog.Promise.State_.REJECTED, reason);\n });\n } catch (e) {\n this.resolve_(goog.Promise.State_.REJECTED, e);\n }\n }\n};\n\n\n/**\n * @define {boolean} Whether traces of `then` calls should be included in\n * exceptions thrown\n */\ngoog.Promise.LONG_STACK_TRACES =\n goog.define('goog.Promise.LONG_STACK_TRACES', false);\n\n\n/**\n * @define {number} The delay in milliseconds before a rejected Promise's reason\n * is passed to the rejection handler. By default, the rejection handler\n * rethrows the rejection reason so that it appears in the developer console or\n * `window.onerror` handler.\n *\n * Rejections are rethrown as quickly as possible by default. A negative value\n * disables rejection handling entirely.\n */\ngoog.Promise.UNHANDLED_REJECTION_DELAY =\n goog.define('goog.Promise.UNHANDLED_REJECTION_DELAY', 0);\n\n\n/**\n * The possible internal states for a Promise. These states are not directly\n * observable to external callers.\n * @enum {number}\n * @private\n */\ngoog.Promise.State_ = {\n /** The Promise is waiting for resolution. */\n PENDING: 0,\n\n /** The Promise is blocked waiting for the result of another Thenable. */\n BLOCKED: 1,\n\n /** The Promise has been resolved with a fulfillment value. */\n FULFILLED: 2,\n\n /** The Promise has been resolved with a rejection reason. */\n REJECTED: 3\n};\n\n\n\n/**\n * Entries in the callback chain. Each call to `then`,\n * `thenCatch`, or `thenAlways` creates an entry containing the\n * functions that may be invoked once the Promise is settled.\n *\n * @private @final @struct @constructor\n */\ngoog.Promise.CallbackEntry_ = function() {\n /** @type {?goog.Promise} */\n this.child = null;\n /** @type {?Function} */\n this.onFulfilled = null;\n /** @type {?Function} */\n this.onRejected = null;\n /** @type {?} */\n this.context = null;\n /** @type {?goog.Promise.CallbackEntry_} */\n this.next = null;\n\n /**\n * A boolean value to indicate this is a \"thenAlways\" callback entry.\n * Unlike a normal \"then/thenVoid\" a \"thenAlways doesn't participate\n * in \"cancel\" considerations but is simply an observer and requires\n * special handling.\n * @type {boolean}\n */\n this.always = false;\n};\n\n\n/** clear the object prior to reuse */\ngoog.Promise.CallbackEntry_.prototype.reset = function() {\n this.child = null;\n this.onFulfilled = null;\n this.onRejected = null;\n this.context = null;\n this.always = false;\n};\n\n\n/**\n * @define {number} The number of currently unused objects to keep around for\n * reuse.\n */\ngoog.Promise.DEFAULT_MAX_UNUSED =\n goog.define('goog.Promise.DEFAULT_MAX_UNUSED', 100);\n\n\n/** @const @private {goog.async.FreeList<!goog.Promise.CallbackEntry_>} */\ngoog.Promise.freelist_ = new goog.async.FreeList(\n function() { return new goog.Promise.CallbackEntry_(); },\n function(item) { item.reset(); }, goog.Promise.DEFAULT_MAX_UNUSED);\n\n\n/**\n * @param {Function} onFulfilled\n * @param {Function} onRejected\n * @param {?} context\n * @return {!goog.Promise.CallbackEntry_}\n * @private\n */\ngoog.Promise.getCallbackEntry_ = function(onFulfilled, onRejected, context) {\n var entry = goog.Promise.freelist_.get();\n entry.onFulfilled = onFulfilled;\n entry.onRejected = onRejected;\n entry.context = context;\n return entry;\n};\n\n\n/**\n * @param {!goog.Promise.CallbackEntry_} entry\n * @private\n */\ngoog.Promise.returnEntry_ = function(entry) {\n goog.Promise.freelist_.put(entry);\n};\n\n\n// NOTE: this is the same template expression as is used for\n// goog.IThenable.prototype.then\n\n\n/**\n * @param {VALUE=} opt_value\n * @return {RESULT} A new Promise that is immediately resolved\n * with the given value. If the input value is already a goog.Promise, it\n * will be returned immediately without creating a new instance.\n * @template VALUE\n * @template RESULT := type('goog.Promise',\n * cond(isUnknown(VALUE), unknown(),\n * mapunion(VALUE, (V) =>\n * cond(isTemplatized(V) && sub(rawTypeOf(V), 'IThenable'),\n * templateTypeOf(V, 0),\n * cond(sub(V, 'Thenable'),\n * unknown(),\n * V)))))\n * =:\n */\ngoog.Promise.resolve = function(opt_value) {\n if (opt_value instanceof goog.Promise) {\n // Avoid creating a new object if we already have a promise object\n // of the correct type.\n return opt_value;\n }\n\n // Passing goog.nullFunction will cause the constructor to take an optimized\n // path that skips calling the resolver function.\n var promise = new goog.Promise(goog.nullFunction);\n promise.resolve_(goog.Promise.State_.FULFILLED, opt_value);\n return promise;\n};\n\n\n/**\n * @param {*=} opt_reason\n * @return {!goog.Promise} A new Promise that is immediately rejected with the\n * given reason.\n */\ngoog.Promise.reject = function(opt_reason) {\n return new goog.Promise(function(resolve, reject) { reject(opt_reason); });\n};\n\n\n/**\n * This is identical to\n * {@code goog.Promise.resolve(value).then(onFulfilled, onRejected)}, but it\n * avoids creating an unnecessary wrapper Promise when `value` is already\n * thenable.\n *\n * @param {?(goog.Thenable<TYPE>|Thenable|TYPE)} value\n * @param {function(TYPE): ?} onFulfilled\n * @param {function(*): *} onRejected\n * @template TYPE\n * @private\n */\ngoog.Promise.resolveThen_ = function(value, onFulfilled, onRejected) {\n var isThenable =\n goog.Promise.maybeThen_(value, onFulfilled, onRejected, null);\n if (!isThenable) {\n goog.async.run(goog.partial(onFulfilled, value));\n }\n};\n\n\n/**\n * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}\n * promises\n * @return {!goog.Promise<TYPE>} A Promise that receives the result of the\n * first Promise (or Promise-like) input to settle immediately after it\n * settles.\n * @template TYPE\n */\ngoog.Promise.race = function(promises) {\n return new goog.Promise(function(resolve, reject) {\n if (!promises.length) {\n resolve(undefined);\n }\n for (var i = 0, promise; i < promises.length; i++) {\n promise = promises[i];\n goog.Promise.resolveThen_(promise, resolve, reject);\n }\n });\n};\n\n\n/**\n * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}\n * promises\n * @return {!goog.Promise<!Array<TYPE>>} A Promise that receives a list of\n * every fulfilled value once every input Promise (or Promise-like) is\n * successfully fulfilled, or is rejected with the first rejection reason\n * immediately after it is rejected.\n * @template TYPE\n */\ngoog.Promise.all = function(promises) {\n return new goog.Promise(function(resolve, reject) {\n var toFulfill = promises.length;\n var values = [];\n\n if (!toFulfill) {\n resolve(values);\n return;\n }\n\n var onFulfill = function(index, value) {\n toFulfill--;\n values[index] = value;\n if (toFulfill == 0) {\n resolve(values);\n }\n };\n\n var onReject = function(reason) { reject(reason); };\n\n for (var i = 0, promise; i < promises.length; i++) {\n promise = promises[i];\n goog.Promise.resolveThen_(promise, goog.partial(onFulfill, i), onReject);\n }\n });\n};\n\n\n/**\n * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}\n * promises\n * @return {!goog.Promise<!Array<{\n * fulfilled: boolean,\n * value: (TYPE|undefined),\n * reason: (*|undefined)}>>} A Promise that resolves with a list of\n * result objects once all input Promises (or Promise-like) have\n * settled. Each result object contains a 'fulfilled' boolean indicating\n * whether an input Promise was fulfilled or rejected. For fulfilled\n * Promises, the resulting value is stored in the 'value' field. For\n * rejected Promises, the rejection reason is stored in the 'reason'\n * field.\n * @template TYPE\n */\ngoog.Promise.allSettled = function(promises) {\n return new goog.Promise(function(resolve, reject) {\n var toSettle = promises.length;\n var results = [];\n\n if (!toSettle) {\n resolve(results);\n return;\n }\n\n var onSettled = function(index, fulfilled, result) {\n toSettle--;\n results[index] = fulfilled ? {fulfilled: true, value: result} :\n {fulfilled: false, reason: result};\n if (toSettle == 0) {\n resolve(results);\n }\n };\n\n for (var i = 0, promise; i < promises.length; i++) {\n promise = promises[i];\n goog.Promise.resolveThen_(\n promise, goog.partial(onSettled, i, true /* fulfilled */),\n goog.partial(onSettled, i, false /* fulfilled */));\n }\n });\n};\n\n\n/**\n * @param {!Array<?(goog.Promise<TYPE>|goog.Thenable<TYPE>|Thenable|*)>}\n * promises\n * @return {!goog.Promise<TYPE>} A Promise that receives the value of the first\n * input to be fulfilled, or is rejected with a list of every rejection\n * reason if all inputs are rejected.\n * @template TYPE\n */\ngoog.Promise.firstFulfilled = function(promises) {\n return new goog.Promise(function(resolve, reject) {\n var toReject = promises.length;\n var reasons = [];\n\n if (!toReject) {\n resolve(undefined);\n return;\n }\n\n var onFulfill = function(value) { resolve(value); };\n\n var onReject = function(index, reason) {\n toReject--;\n reasons[index] = reason;\n if (toReject == 0) {\n reject(reasons);\n }\n };\n\n for (var i = 0, promise; i < promises.length; i++) {\n promise = promises[i];\n goog.Promise.resolveThen_(promise, onFulfill, goog.partial(onReject, i));\n }\n });\n};\n\n\n/**\n * @return {!goog.promise.Resolver<TYPE>} Resolver wrapping the promise and its\n * resolve / reject functions. Resolving or rejecting the resolver\n * resolves or rejects the promise.\n * @template TYPE\n */\ngoog.Promise.withResolver = function() {\n var resolve, reject;\n var promise = new goog.Promise(function(rs, rj) {\n resolve = rs;\n reject = rj;\n });\n return new goog.Promise.Resolver_(promise, resolve, reject);\n};\n\n\n/**\n * Adds callbacks that will operate on the result of the Promise, returning a\n * new child Promise.\n *\n * If the Promise is fulfilled, the `onFulfilled` callback will be invoked\n * with the fulfillment value as argument, and the child Promise will be\n * fulfilled with the return value of the callback. If the callback throws an\n * exception, the child Promise will be rejected with the thrown value instead.\n *\n * If the Promise is rejected, the `onRejected` callback will be invoked\n * with the rejection reason as argument, and the child Promise will be resolved\n * with the return value or rejected with the thrown value of the callback.\n *\n * @override\n */\ngoog.Promise.prototype.then = function(\n opt_onFulfilled, opt_onRejected, opt_context) {\n\n if (opt_onFulfilled != null) {\n goog.asserts.assertFunction(\n opt_onFulfilled, 'opt_onFulfilled should be a function.');\n }\n if (opt_onRejected != null) {\n goog.asserts.assertFunction(\n opt_onRejected,\n 'opt_onRejected should be a function. Did you pass opt_context ' +\n 'as the second argument instead of the third?');\n }\n\n if (goog.Promise.LONG_STACK_TRACES) {\n this.addStackTrace_(new Error('then'));\n }\n\n return this.addChildPromise_(\n goog.isFunction(opt_onFulfilled) ? opt_onFulfilled : null,\n goog.isFunction(opt_onRejected) ? opt_onRejected : null, opt_context);\n};\ngoog.Thenable.addImplementation(goog.Promise);\n\n\n/**\n * Adds callbacks that will operate on the result of the Promise without\n * returning a child Promise (unlike \"then\").\n *\n * If the Promise is fulfilled, the `onFulfilled` callback will be invoked\n * with the fulfillment value as argument.\n *\n * If the Promise is rejected, the `onRejected` callback will be invoked\n * with the rejection reason as argument.\n *\n * @param {?(function(this:THIS, TYPE):?)=} opt_onFulfilled A\n * function that will be invoked with the fulfillment value if the Promise\n * is fulfilled.\n * @param {?(function(this:THIS, *): *)=} opt_onRejected A function that will\n * be invoked with the rejection reason if the Promise is rejected.\n * @param {THIS=} opt_context An optional context object that will be the\n * execution context for the callbacks. By default, functions are executed\n * with the default this.\n * @package\n * @template THIS\n */\ngoog.Promise.prototype.thenVoid = function(\n opt_onFulfilled, opt_onRejected, opt_context) {\n\n if (opt_onFulfilled != null) {\n goog.asserts.assertFunction(\n opt_onFulfilled, 'opt_onFulfilled should be a function.');\n }\n if (opt_onRejected != null) {\n goog.asserts.assertFunction(\n opt_onRejected,\n 'opt_onRejected should be a function. Did you pass opt_context ' +\n 'as the second argument instead of the third?');\n }\n\n if (goog.Promise.LONG_STACK_TRACES) {\n this.addStackTrace_(new Error('then'));\n }\n\n // Note: no default rejection handler is provided here as we need to\n // distinguish unhandled rejections.\n this.addCallbackEntry_(\n goog.Promise.getCallbackEntry_(\n opt_onFulfilled || goog.nullFunction, opt_onRejected || null,\n opt_context));\n};\n\n\n/**\n * Adds a callback that will be invoked when the Promise is settled (fulfilled\n * or rejected). The callback receives no argument, and no new child Promise is\n * created. This is useful for ensuring that cleanup takes place after certain\n * asynchronous operations. Callbacks added with `thenAlways` will be\n * executed in the same order with other calls to `then`,\n * `thenAlways`, or `thenCatch`.\n *\n * Since it does not produce a new child Promise, cancellation propagation is\n * not prevented by adding callbacks with `thenAlways`. A Promise that has\n * a cleanup handler added with `thenAlways` will be canceled if all of\n * its children created by `then` (or `thenCatch`) are canceled.\n * Additionally, since any rejections are not passed to the callback, it does\n * not stop the unhandled rejection handler from running.\n *\n * @param {function(this:THIS): void} onSettled A function that will be invoked\n * when the Promise is settled (fulfilled or rejected).\n * @param {THIS=} opt_context An optional context object that will be the\n * execution context for the callbacks. By default, functions are executed\n * in the global scope.\n * @return {!goog.Promise<TYPE>} This Promise, for chaining additional calls.\n * @template THIS\n */\ngoog.Promise.prototype.thenAlways = function(onSettled, opt_context) {\n if (goog.Promise.LONG_STACK_TRACES) {\n this.addStackTrace_(new Error('thenAlways'));\n }\n\n var entry = goog.Promise.getCallbackEntry_(onSettled, onSettled, opt_context);\n entry.always = true;\n this.addCallbackEntry_(entry);\n return this;\n};\n\n\n/**\n * Adds a callback that will be invoked only if the Promise is rejected. This\n * is equivalent to `then(null, onRejected)`.\n *\n * @param {function(this:THIS, *): *} onRejected A function that will be\n * invoked with the rejection reason if this Promise is rejected.\n * @param {THIS=} opt_context An optional context object that will be the\n * execution context for the callbacks. By default, functions are executed\n * in the global scope.\n * @return {!goog.Promise} A new Promise that will resolve either to the\n * value of this promise, or if this promise is rejected, the result of\n * `onRejected`. The returned Promise will reject if `onRejected` throws.\n * @template THIS\n */\ngoog.Promise.prototype.thenCatch = function(onRejected, opt_context) {\n if (goog.Promise.LONG_STACK_TRACES) {\n this.addStackTrace_(new Error('thenCatch'));\n }\n return this.addChildPromise_(null, onRejected, opt_context);\n};\n\n\n/**\n * Cancels the Promise if it is still pending by rejecting it with a cancel\n * Error. No action is performed if the Promise is already resolved.\n *\n * All child Promises of the canceled Promise will be rejected with the same\n * cancel error, as with normal Promise rejection. If the Promise to be canceled\n * is the only child of a pending Promise, the parent Promise will also be\n * canceled. Cancellation may propagate upward through multiple generations.\n *\n * @param {string=} opt_message An optional debugging message for describing the\n * cancellation reason.\n */\ngoog.Promise.prototype.cancel = function(opt_message) {\n if (this.state_ == goog.Promise.State_.PENDING) {\n // Instantiate Error object synchronously. This ensures Error::stack points\n // to the cancel() callsite.\n var err = new goog.Promise.CancellationError(opt_message);\n goog.async.run(function() {\n this.cancelInternal_(err);\n }, this);\n }\n};\n\n\n/**\n * Cancels this Promise with the given error.\n *\n * @param {!Error} err The cancellation error.\n * @private\n */\ngoog.Promise.prototype.cancelInternal_ = function(err) {\n if (this.state_ == goog.Promise.State_.PENDING) {\n if (this.parent_) {\n // Cancel the Promise and remove it from the parent's child list.\n this.parent_.cancelChild_(this, err);\n this.parent_ = null;\n } else {\n this.resolve_(goog.Promise.State_.REJECTED, err);\n }\n }\n};\n\n\n/**\n * Cancels a child Promise from the list of callback entries. If the Promise has\n * not already been resolved, reject it with a cancel error. If there are no\n * other children in the list of callback entries, propagate the cancellation\n * by canceling this Promise as well.\n *\n * @param {!goog.Promise} childPromise The Promise to cancel.\n * @param {!Error} err The cancel error to use for rejecting the Promise.\n * @private\n */\ngoog.Promise.prototype.cancelChild_ = function(childPromise, err) {\n if (!this.callbackEntries_) {\n return;\n }\n var childCount = 0;\n var childEntry = null;\n var beforeChildEntry = null;\n\n // Find the callback entry for the childPromise, and count whether there are\n // additional child Promises.\n for (var entry = this.callbackEntries_; entry; entry = entry.next) {\n if (!entry.always) {\n childCount++;\n if (entry.child == childPromise) {\n childEntry = entry;\n }\n if (childEntry && childCount > 1) {\n break;\n }\n }\n if (!childEntry) {\n beforeChildEntry = entry;\n }\n }\n\n // Can a child entry be missing?\n\n // If the child Promise was the only child, cancel this Promise as well.\n // Otherwise, reject only the child Promise with the cancel error.\n if (childEntry) {\n if (this.state_ == goog.Promise.State_.PENDING && childCount == 1) {\n this.cancelInternal_(err);\n } else {\n if (beforeChildEntry) {\n this.removeEntryAfter_(beforeChildEntry);\n } else {\n this.popEntry_();\n }\n\n this.executeCallback_(childEntry, goog.Promise.State_.REJECTED, err);\n }\n }\n};\n\n\n/**\n * Adds a callback entry to the current Promise, and schedules callback\n * execution if the Promise has already been settled.\n *\n * @param {goog.Promise.CallbackEntry_} callbackEntry Record containing\n * `onFulfilled` and `onRejected` callbacks to execute after\n * the Promise is settled.\n * @private\n */\ngoog.Promise.prototype.addCallbackEntry_ = function(callbackEntry) {\n if (!this.hasEntry_() && (this.state_ == goog.Promise.State_.FULFILLED ||\n this.state_ == goog.Promise.State_.REJECTED)) {\n this.scheduleCallbacks_();\n }\n this.queueEntry_(callbackEntry);\n};\n\n\n/**\n * Creates a child Promise and adds it to the callback entry list. The result of\n * the child Promise is determined by the state of the parent Promise and the\n * result of the `onFulfilled` or `onRejected` callbacks as\n * specified in the Promise resolution procedure.\n *\n * @see http://promisesaplus.com/#the__method\n *\n * @param {?function(this:THIS, TYPE):\n * (RESULT|goog.Promise<RESULT>|Thenable)} onFulfilled A callback that\n * will be invoked if the Promise is fulfilled, or null.\n * @param {?function(this:THIS, *): *} onRejected A callback that will be\n * invoked if the Promise is rejected, or null.\n * @param {THIS=} opt_context An optional execution context for the callbacks.\n * in the default calling context.\n * @return {!goog.Promise} The child Promise.\n * @template RESULT,THIS\n * @private\n */\ngoog.Promise.prototype.addChildPromise_ = function(\n onFulfilled, onRejected, opt_context) {\n\n /** @type {goog.Promise.CallbackEntry_} */\n var callbackEntry = goog.Promise.getCallbackEntry_(null, null, null);\n\n callbackEntry.child = new goog.Promise(function(resolve, reject) {\n // Invoke onFulfilled, or resolve with the parent's value if absent.\n callbackEntry.onFulfilled = onFulfilled ? function(value) {\n try {\n var result = onFulfilled.call(opt_context, value);\n resolve(result);\n } catch (err) {\n reject(err);\n }\n } : resolve;\n\n // Invoke onRejected, or reject with the parent's reason if absent.\n callbackEntry.onRejected = onRejected ? function(reason) {\n try {\n var result = onRejected.call(opt_context, reason);\n if (result === undefined &&\n reason instanceof goog.Promise.CancellationError) {\n // Propagate cancellation to children if no other result is returned.\n reject(reason);\n } else {\n resolve(result);\n }\n } catch (err) {\n reject(err);\n }\n } : reject;\n });\n\n callbackEntry.child.parent_ = this;\n this.addCallbackEntry_(callbackEntry);\n return callbackEntry.child;\n};\n\n\n/**\n * Unblocks the Promise and fulfills it with the given value.\n *\n * @param {TYPE} value\n * @private\n */\ngoog.Promise.prototype.unblockAndFulfill_ = function(value) {\n goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);\n this.state_ = goog.Promise.State_.PENDING;\n this.resolve_(goog.Promise.State_.FULFILLED, value);\n};\n\n\n/**\n * Unblocks the Promise and rejects it with the given rejection reason.\n *\n * @param {*} reason\n * @private\n */\ngoog.Promise.prototype.unblockAndReject_ = function(reason) {\n goog.asserts.assert(this.state_ == goog.Promise.State_.BLOCKED);\n this.state_ = goog.Promise.State_.PENDING;\n this.resolve_(goog.Promise.State_.REJECTED, reason);\n};\n\n\n/**\n * Attempts to resolve a Promise with a given resolution state and value. This\n * is a no-op if the given Promise has already been resolved.\n *\n * If the given result is a Thenable (such as another Promise), the Promise will\n * be settled with the same state and result as the Thenable once it is itself\n * settled.\n *\n * If the given result is not a Thenable, the Promise will be settled (fulfilled\n * or rejected) with that result based on the given state.\n *\n * @see http://promisesaplus.com/#the_promise_resolution_procedure\n *\n * @param {goog.Promise.State_} state\n * @param {*} x The result to apply to the Promise.\n * @private\n */\ngoog.Promise.prototype.resolve_ = function(state, x) {\n if (this.state_ != goog.Promise.State_.PENDING) {\n return;\n }\n\n if (this === x) {\n state = goog.Promise.State_.REJECTED;\n x = new TypeError('Promise cannot resolve to itself');\n }\n\n this.state_ = goog.Promise.State_.BLOCKED;\n var isThenable = goog.Promise.maybeThen_(\n x, this.unblockAndFulfill_, this.unblockAndReject_, this);\n if (isThenable) {\n return;\n }\n\n this.result_ = x;\n this.state_ = state;\n // Since we can no longer be canceled, remove link to parent, so that the\n // child promise does not keep the parent promise alive.\n this.parent_ = null;\n this.scheduleCallbacks_();\n\n if (state == goog.Promise.State_.REJECTED &&\n !(x instanceof goog.Promise.CancellationError)) {\n goog.Promise.addUnhandledRejection_(this, x);\n }\n};\n\n\n/**\n * Invokes the \"then\" method of an input value if that value is a Thenable. This\n * is a no-op if the value is not thenable.\n *\n * @param {?} value A potentially thenable value.\n * @param {!Function} onFulfilled\n * @param {!Function} onRejected\n * @param {?} context\n * @return {boolean} Whether the input value was thenable.\n * @private\n */\ngoog.Promise.maybeThen_ = function(value, onFulfilled, onRejected, context) {\n if (value instanceof goog.Promise) {\n value.thenVoid(onFulfilled, onRejected, context);\n return true;\n } else if (goog.Thenable.isImplementedBy(value)) {\n value = /** @type {!goog.Thenable} */ (value);\n value.then(onFulfilled, onRejected, context);\n return true;\n } else if (goog.isObject(value)) {\n const thenable = /** @type {!Thenable} */ (value);\n try {\n var then = thenable.then;\n if (goog.isFunction(then)) {\n goog.Promise.tryThen_(thenable, then, onFulfilled, onRejected, context);\n return true;\n }\n } catch (e) {\n onRejected.call(context, e);\n return true;\n }\n }\n\n return false;\n};\n\n\n/**\n * Attempts to call the `then` method on an object in the hopes that it is\n * a Promise-compatible instance. This allows interoperation between different\n * Promise implementations, however a non-compliant object may cause a Promise\n * to hang indefinitely. If the `then` method throws an exception, the\n * dependent Promise will be rejected with the thrown value.\n *\n * @see http://promisesaplus.com/#point-70\n *\n * @param {Thenable} thenable An object with a `then` method that may be\n * compatible with the Promise/A+ specification.\n * @param {!Function} then The `then` method of the Thenable object.\n * @param {!Function} onFulfilled\n * @param {!Function} onRejected\n * @param {*} context\n * @private\n */\ngoog.Promise.tryThen_ = function(\n thenable, then, onFulfilled, onRejected, context) {\n\n var called = false;\n var resolve = function(value) {\n if (!called) {\n called = true;\n onFulfilled.call(context, value);\n }\n };\n\n var reject = function(reason) {\n if (!called) {\n called = true;\n onRejected.call(context, reason);\n }\n };\n\n try {\n then.call(thenable, resolve, reject);\n } catch (e) {\n reject(e);\n }\n};\n\n\n/**\n * Executes the pending callbacks of a settled Promise after a timeout.\n *\n * Section 2.2.4 of the Promises/A+ specification requires that Promise\n * callbacks must only be invoked from a call stack that only contains Promise\n * implementation code, which we accomplish by invoking callback execution after\n * a timeout. If `startExecution_` is called multiple times for the same\n * Promise, the callback chain will be evaluated only once. Additional callbacks\n * may be added during the evaluation phase, and will be executed in the same\n * event loop.\n *\n * All Promises added to the waiting list during the same browser event loop\n * will be executed in one batch to avoid using a separate timeout per Promise.\n *\n * @private\n */\ngoog.Promise.prototype.scheduleCallbacks_ = function() {\n if (!this.executing_) {\n this.executing_ = true;\n goog.async.run(this.executeCallbacks_, this);\n }\n};\n\n\n/**\n * @return {boolean} Whether there are any pending callbacks queued.\n * @private\n */\ngoog.Promise.prototype.hasEntry_ = function() {\n return !!this.callbackEntries_;\n};\n\n\n/**\n * @param {goog.Promise.CallbackEntry_} entry\n * @private\n */\ngoog.Promise.prototype.queueEntry_ = function(entry) {\n goog.asserts.assert(entry.onFulfilled != null);\n\n if (this.callbackEntriesTail_) {\n this.callbackEntriesTail_.next = entry;\n this.callbackEntriesTail_ = entry;\n } else {\n // It the work queue was empty set the head too.\n this.callbackEntries_ = entry;\n this.callbackEntriesTail_ = entry;\n }\n};\n\n\n/**\n * @return {goog.Promise.CallbackEntry_} entry\n * @private\n */\ngoog.Promise.prototype.popEntry_ = function() {\n var entry = null;\n if (this.callbackEntries_) {\n entry = this.callbackEntries_;\n this.callbackEntries_ = entry.next;\n entry.next = null;\n }\n // It the work queue is empty clear the tail too.\n if (!this.callbackEntries_) {\n this.callbackEntriesTail_ = null;\n }\n\n if (entry != null) {\n goog.asserts.assert(entry.onFulfilled != null);\n }\n return entry;\n};\n\n\n/**\n * @param {goog.Promise.CallbackEntry_} previous\n * @private\n */\ngoog.Promise.prototype.removeEntryAfter_ = function(previous) {\n goog.asserts.assert(this.callbackEntries_);\n goog.asserts.assert(previous != null);\n // If the last entry is being removed, update the tail\n if (previous.next == this.callbackEntriesTail_) {\n this.callbackEntriesTail_ = previous;\n }\n\n previous.next = previous.next.next;\n};\n\n\n/**\n * Executes all pending callbacks for this Promise.\n *\n * @private\n */\ngoog.Promise.prototype.executeCallbacks_ = function() {\n var entry = null;\n while (entry = this.popEntry_()) {\n if (goog.Promise.LONG_STACK_TRACES) {\n this.currentStep_++;\n }\n this.executeCallback_(entry, this.state_, this.result_);\n }\n this.executing_ = false;\n};\n\n\n/**\n * Executes a pending callback for this Promise. Invokes an `onFulfilled`\n * or `onRejected` callback based on the settled state of the Promise.\n *\n * @param {!goog.Promise.CallbackEntry_} callbackEntry An entry containing the\n * onFulfilled and/or onRejected callbacks for this step.\n * @param {goog.Promise.State_} state The resolution status of the Promise,\n * either FULFILLED or REJECTED.\n * @param {*} result The settled result of the Promise.\n * @private\n */\ngoog.Promise.prototype.executeCallback_ = function(\n callbackEntry, state, result) {\n // Cancel an unhandled rejection if the then/thenVoid call had an onRejected.\n if (state == goog.Promise.State_.REJECTED && callbackEntry.onRejected &&\n !callbackEntry.always) {\n this.removeUnhandledRejection_();\n }\n\n if (callbackEntry.child) {\n // When the parent is settled, the child no longer needs to hold on to it,\n // as the parent can no longer be canceled.\n callbackEntry.child.parent_ = null;\n goog.Promise.invokeCallback_(callbackEntry, state, result);\n } else {\n // Callbacks created with thenAlways or thenVoid do not have the rejection\n // handling code normally set up in the child Promise.\n try {\n callbackEntry.always ?\n callbackEntry.onFulfilled.call(callbackEntry.context) :\n goog.Promise.invokeCallback_(callbackEntry, state, result);\n } catch (err) {\n goog.Promise.handleRejection_.call(null, err);\n }\n }\n goog.Promise.returnEntry_(callbackEntry);\n};\n\n\n/**\n * Executes the onFulfilled or onRejected callback for a callbackEntry.\n *\n * @param {!goog.Promise.CallbackEntry_} callbackEntry\n * @param {goog.Promise.State_} state\n * @param {*} result\n * @private\n */\ngoog.Promise.invokeCallback_ = function(callbackEntry, state, result) {\n if (state == goog.Promise.State_.FULFILLED) {\n callbackEntry.onFulfilled.call(callbackEntry.context, result);\n } else if (callbackEntry.onRejected) {\n callbackEntry.onRejected.call(callbackEntry.context, result);\n }\n};\n\n\n/**\n * Records a stack trace entry for functions that call `then` or the\n * Promise constructor. May be disabled by unsetting `LONG_STACK_TRACES`.\n *\n * @param {!Error} err An Error object created by the calling function for\n * providing a stack trace.\n * @private\n */\ngoog.Promise.prototype.addStackTrace_ = function(err) {\n if (goog.Promise.LONG_STACK_TRACES && typeof err.stack === 'string') {\n // Extract the third line of the stack trace, which is the entry for the\n // user function that called into Promise code.\n var trace = err.stack.split('\\n', 4)[3];\n var message = err.message;\n\n // Pad the message to align the traces.\n message += Array(11 - message.length).join(' ');\n this.stack_.push(message + trace);\n }\n};\n\n\n/**\n * Adds extra stack trace information to an exception for the list of\n * asynchronous `then` calls that have been run for this Promise. Stack\n * trace information is recorded in {@see #addStackTrace_}, and appended to\n * rethrown errors when `LONG_STACK_TRACES` is enabled.\n *\n * @param {?} err An unhandled exception captured during callback execution.\n * @private\n */\ngoog.Promise.prototype.appendLongStack_ = function(err) {\n if (goog.Promise.LONG_STACK_TRACES && err && typeof err.stack === 'string' &&\n this.stack_.length) {\n var longTrace = ['Promise trace:'];\n\n for (var promise = this; promise; promise = promise.parent_) {\n for (var i = this.currentStep_; i >= 0; i--) {\n longTrace.push(promise.stack_[i]);\n }\n longTrace.push(\n 'Value: ' +\n '[' + (promise.state_ == goog.Promise.State_.REJECTED ? 'REJECTED' :\n 'FULFILLED') +\n '] ' +\n '<' + String(promise.result_) + '>');\n }\n err.stack += '\\n\\n' + longTrace.join('\\n');\n }\n};\n\n\n/**\n * Marks this rejected Promise as having being handled. Also marks any parent\n * Promises in the rejected state as handled. The rejection handler will no\n * longer be invoked for this Promise (if it has not been called already).\n *\n * @private\n */\ngoog.Promise.prototype.removeUnhandledRejection_ = function() {\n if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {\n for (var p = this; p && p.unhandledRejectionId_; p = p.parent_) {\n goog.global.clearTimeout(p.unhandledRejectionId_);\n p.unhandledRejectionId_ = 0;\n }\n } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {\n for (var p = this; p && p.hadUnhandledRejection_; p = p.parent_) {\n p.hadUnhandledRejection_ = false;\n }\n }\n};\n\n\n/**\n * Marks this rejected Promise as unhandled. If no `onRejected` callback\n * is called for this Promise before the `UNHANDLED_REJECTION_DELAY`\n * expires, the reason will be passed to the unhandled rejection handler. The\n * handler typically rethrows the rejection reason so that it becomes visible in\n * the developer console.\n *\n * @param {!goog.Promise} promise The rejected Promise.\n * @param {*} reason The Promise rejection reason.\n * @private\n */\ngoog.Promise.addUnhandledRejection_ = function(promise, reason) {\n if (goog.Promise.UNHANDLED_REJECTION_DELAY > 0) {\n promise.unhandledRejectionId_ = goog.global.setTimeout(function() {\n promise.appendLongStack_(reason);\n goog.Promise.handleRejection_.call(null, reason);\n }, goog.Promise.UNHANDLED_REJECTION_DELAY);\n\n } else if (goog.Promise.UNHANDLED_REJECTION_DELAY == 0) {\n promise.hadUnhandledRejection_ = true;\n goog.async.run(function() {\n if (promise.hadUnhandledRejection_) {\n promise.appendLongStack_(reason);\n goog.Promise.handleRejection_.call(null, reason);\n }\n });\n }\n};\n\n\n/**\n * A method that is invoked with the rejection reasons for Promises that are\n * rejected but have no `onRejected` callbacks registered yet.\n * @type {function(*)}\n * @private\n */\ngoog.Promise.handleRejection_ = goog.async.throwException;\n\n\n/**\n * Sets a handler that will be called with reasons from unhandled rejected\n * Promises. If the rejected Promise (or one of its descendants) has an\n * `onRejected` callback registered, the rejection will be considered\n * handled, and the rejection handler will not be called.\n *\n * By default, unhandled rejections are rethrown so that the error may be\n * captured by the developer console or a `window.onerror` handler.\n *\n * @param {function(*)} handler A function that will be called with reasons from\n * rejected Promises. Defaults to `goog.async.throwException`.\n */\ngoog.Promise.setUnhandledRejectionHandler = function(handler) {\n goog.Promise.handleRejection_ = handler;\n};\n\n\n\n/**\n * Error used as a rejection reason for canceled Promises.\n *\n * @param {string=} opt_message\n * @constructor\n * @extends {goog.debug.Error}\n * @final\n */\ngoog.Promise.CancellationError = function(opt_message) {\n goog.Promise.CancellationError.base(this, 'constructor', opt_message);\n};\ngoog.inherits(goog.Promise.CancellationError, goog.debug.Error);\n\n\n/** @override */\ngoog.Promise.CancellationError.prototype.name = 'cancel';\n\n\n\n/**\n * Internal implementation of the resolver interface.\n *\n * @param {!goog.Promise<TYPE>} promise\n * @param {function((TYPE|goog.Promise<TYPE>|Thenable)=)} resolve\n * @param {function(*=): void} reject\n * @implements {goog.promise.Resolver<TYPE>}\n * @final @struct\n * @constructor\n * @private\n * @template TYPE\n */\ngoog.Promise.Resolver_ = function(promise, resolve, reject) {\n /** @const */\n this.promise = promise;\n\n /** @const */\n this.resolve = resolve;\n\n /** @const */\n this.reject = reject;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implements the disposable interface. The dispose method is used\n * to clean up references and resources.\n */\n\n\ngoog.provide('goog.Disposable');\ngoog.provide('goog.dispose');\ngoog.provide('goog.disposeAll');\n\ngoog.require('goog.disposable.IDisposable');\n\n\n\n/**\n * Class that provides the basic implementation for disposable objects. If your\n * class holds references or resources that can't be collected by standard GC,\n * it should extend this class or implement the disposable interface (defined\n * in goog.disposable.IDisposable). See description of\n * goog.disposable.IDisposable for examples of cleanup.\n * @constructor\n * @implements {goog.disposable.IDisposable}\n */\ngoog.Disposable = function() {\n /**\n * If monitoring the goog.Disposable instances is enabled, stores the creation\n * stack trace of the Disposable instance.\n * @type {string|undefined}\n */\n this.creationStack;\n\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {\n this.creationStack = new Error().stack;\n }\n goog.Disposable.instances_[goog.getUid(this)] = this;\n }\n // Support sealing\n this.disposed_ = this.disposed_;\n this.onDisposeCallbacks_ = this.onDisposeCallbacks_;\n};\n\n\n/**\n * @enum {number} Different monitoring modes for Disposable.\n */\ngoog.Disposable.MonitoringMode = {\n /**\n * No monitoring.\n */\n OFF: 0,\n /**\n * Creating and disposing the goog.Disposable instances is monitored. All\n * disposable objects need to call the `goog.Disposable` base\n * constructor. The PERMANENT mode must be switched on before creating any\n * goog.Disposable instances.\n */\n PERMANENT: 1,\n /**\n * INTERACTIVE mode can be switched on and off on the fly without producing\n * errors. It also doesn't warn if the disposable objects don't call the\n * `goog.Disposable` base constructor.\n */\n INTERACTIVE: 2\n};\n\n\n/**\n * @define {number} The monitoring mode of the goog.Disposable\n * instances. Default is OFF. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.Disposable.MONITORING_MODE =\n goog.define('goog.Disposable.MONITORING_MODE', 0);\n\n\n/**\n * @define {boolean} Whether to attach creation stack to each created disposable\n * instance; This is only relevant for when MonitoringMode != OFF.\n */\ngoog.Disposable.INCLUDE_STACK_ON_CREATION =\n goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);\n\n\n/**\n * Maps the unique ID of every undisposed `goog.Disposable` object to\n * the object itself.\n * @type {!Object<number, !goog.Disposable>}\n * @private\n */\ngoog.Disposable.instances_ = {};\n\n\n/**\n * @return {!Array<!goog.Disposable>} All `goog.Disposable` objects that\n * haven't been disposed of.\n */\ngoog.Disposable.getUndisposedObjects = function() {\n var ret = [];\n for (var id in goog.Disposable.instances_) {\n if (goog.Disposable.instances_.hasOwnProperty(id)) {\n ret.push(goog.Disposable.instances_[Number(id)]);\n }\n }\n return ret;\n};\n\n\n/**\n * Clears the registry of undisposed objects but doesn't dispose of them.\n */\ngoog.Disposable.clearUndisposedObjects = function() {\n goog.Disposable.instances_ = {};\n};\n\n\n/**\n * Whether the object has been disposed of.\n * @type {boolean}\n * @private\n */\ngoog.Disposable.prototype.disposed_ = false;\n\n\n/**\n * Callbacks to invoke when this object is disposed.\n * @type {Array<!Function>}\n * @private\n */\ngoog.Disposable.prototype.onDisposeCallbacks_;\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @override\n */\ngoog.Disposable.prototype.isDisposed = function() {\n return this.disposed_;\n};\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @deprecated Use {@link #isDisposed} instead.\n */\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\n\n\n/**\n * Disposes of the object. If the object hasn't already been disposed of, calls\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\n * override {@link #disposeInternal} in order to cleanup references, resources\n * and other disposable objects. Reentrant.\n *\n * @return {void} Nothing.\n * @override\n */\ngoog.Disposable.prototype.dispose = function() {\n if (!this.disposed_) {\n // Set disposed_ to true first, in case during the chain of disposal this\n // gets disposed recursively.\n this.disposed_ = true;\n this.disposeInternal();\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n var uid = goog.getUid(this);\n if (goog.Disposable.MONITORING_MODE ==\n goog.Disposable.MonitoringMode.PERMANENT &&\n !goog.Disposable.instances_.hasOwnProperty(uid)) {\n throw new Error(\n this + ' did not call the goog.Disposable base ' +\n 'constructor or was disposed of after a clearUndisposedObjects ' +\n 'call');\n }\n if (goog.Disposable.MONITORING_MODE !=\n goog.Disposable.MonitoringMode.OFF &&\n this.onDisposeCallbacks_ && this.onDisposeCallbacks_.length > 0) {\n throw new Error(\n this + ' did not empty its onDisposeCallbacks queue. This ' +\n 'probably means it overrode dispose() or disposeInternal() ' +\n 'without calling the superclass\\' method.');\n }\n delete goog.Disposable.instances_[uid];\n }\n }\n};\n\n\n/**\n * Associates a disposable object with this object so that they will be disposed\n * together.\n * @param {goog.disposable.IDisposable} disposable that will be disposed when\n * this object is disposed.\n */\ngoog.Disposable.prototype.registerDisposable = function(disposable) {\n this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));\n};\n\n\n/**\n * Invokes a callback function when this object is disposed. Callbacks are\n * invoked in the order in which they were added. If a callback is added to\n * an already disposed Disposable, it will be called immediately.\n * @param {function(this:T):?} callback The callback function.\n * @param {T=} opt_scope An optional scope to call the callback in.\n * @template T\n */\ngoog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {\n if (this.disposed_) {\n opt_scope !== undefined ? callback.call(opt_scope) : callback();\n return;\n }\n if (!this.onDisposeCallbacks_) {\n this.onDisposeCallbacks_ = [];\n }\n\n this.onDisposeCallbacks_.push(\n opt_scope !== undefined ? goog.bind(callback, opt_scope) : callback);\n};\n\n\n/**\n * Performs appropriate cleanup. See description of goog.disposable.IDisposable\n * for examples. Classes that extend `goog.Disposable` should override this\n * method. Not reentrant. To avoid calling it twice, it must only be called from\n * the subclass' `disposeInternal` method. Everywhere else the public `dispose`\n * method must be used. For example:\n *\n * <pre>\n * mypackage.MyClass = function() {\n * mypackage.MyClass.base(this, 'constructor');\n * // Constructor logic specific to MyClass.\n * ...\n * };\n * goog.inherits(mypackage.MyClass, goog.Disposable);\n *\n * mypackage.MyClass.prototype.disposeInternal = function() {\n * // Dispose logic specific to MyClass.\n * ...\n * // Call superclass's disposeInternal at the end of the subclass's, like\n * // in C++, to avoid hard-to-catch issues.\n * mypackage.MyClass.base(this, 'disposeInternal');\n * };\n * </pre>\n *\n * @protected\n */\ngoog.Disposable.prototype.disposeInternal = function() {\n if (this.onDisposeCallbacks_) {\n while (this.onDisposeCallbacks_.length) {\n this.onDisposeCallbacks_.shift()();\n }\n }\n};\n\n\n/**\n * Returns True if we can verify the object is disposed.\n * Calls `isDisposed` on the argument if it supports it. If obj\n * is not an object with an isDisposed() method, return false.\n * @param {*} obj The object to investigate.\n * @return {boolean} True if we can verify the object is disposed.\n */\ngoog.Disposable.isDisposed = function(obj) {\n if (obj && typeof obj.isDisposed == 'function') {\n return obj.isDisposed();\n }\n return false;\n};\n\n\n/**\n * Calls `dispose` on the argument if it supports it. If obj is not an\n * object with a dispose() method, this is a no-op.\n * @param {*} obj The object to dispose of.\n */\ngoog.dispose = function(obj) {\n if (obj && typeof obj.dispose == 'function') {\n obj.dispose();\n }\n};\n\n\n/**\n * Calls `dispose` on each member of the list that supports it. (If the\n * member is an ArrayLike, then `goog.disposeAll()` will be called\n * recursively on each of its members.) If the member is not an object with a\n * `dispose()` method, then it is ignored.\n * @param {...*} var_args The list.\n */\ngoog.disposeAll = function(var_args) {\n for (var i = 0, len = arguments.length; i < len; ++i) {\n var disposable = arguments[i];\n if (goog.isArrayLike(disposable)) {\n goog.disposeAll.apply(null, disposable);\n } else {\n goog.dispose(disposable);\n }\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Logging and debugging utilities.\n *\n * @see ../demos/debug.html\n */\n\ngoog.provide('goog.debug');\n\ngoog.require('goog.array');\ngoog.require('goog.debug.errorcontext');\ngoog.require('goog.userAgent');\n\n\n/** @define {boolean} Whether logging should be enabled. */\ngoog.debug.LOGGING_ENABLED =\n goog.define('goog.debug.LOGGING_ENABLED', goog.DEBUG);\n\n\n/** @define {boolean} Whether to force \"sloppy\" stack building. */\ngoog.debug.FORCE_SLOPPY_STACKS =\n goog.define('goog.debug.FORCE_SLOPPY_STACKS', false);\n\n\n/**\n * Catches onerror events fired by windows and similar objects.\n * @param {function(Object)} logFunc The function to call with the error\n * information.\n * @param {boolean=} opt_cancel Whether to stop the error from reaching the\n * browser.\n * @param {Object=} opt_target Object that fires onerror events.\n * @suppress {strictMissingProperties} onerror is not defined as a property\n * on Object.\n */\ngoog.debug.catchErrors = function(logFunc, opt_cancel, opt_target) {\n var target = opt_target || goog.global;\n var oldErrorHandler = target.onerror;\n var retVal = !!opt_cancel;\n\n // Chrome interprets onerror return value backwards (http://crbug.com/92062)\n // until it was fixed in webkit revision r94061 (Webkit 535.3). This\n // workaround still needs to be skipped in Safari after the webkit change\n // gets pushed out in Safari.\n // See https://bugs.webkit.org/show_bug.cgi?id=67119\n if (goog.userAgent.WEBKIT && !goog.userAgent.isVersionOrHigher('535.3')) {\n retVal = !retVal;\n }\n\n /**\n * New onerror handler for this target. This onerror handler follows the spec\n * according to\n * http://www.whatwg.org/specs/web-apps/current-work/#runtime-script-errors\n * The spec was changed in August 2013 to support receiving column information\n * and an error object for all scripts on the same origin or cross origin\n * scripts with the proper headers. See\n * https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror\n *\n * @param {string} message The error message. For cross-origin errors, this\n * will be scrubbed to just \"Script error.\". For new browsers that have\n * updated to follow the latest spec, errors that come from origins that\n * have proper cross origin headers will not be scrubbed.\n * @param {string} url The URL of the script that caused the error. The URL\n * will be scrubbed to \"\" for cross origin scripts unless the script has\n * proper cross origin headers and the browser has updated to the latest\n * spec.\n * @param {number} line The line number in the script that the error\n * occurred on.\n * @param {number=} opt_col The optional column number that the error\n * occurred on. Only browsers that have updated to the latest spec will\n * include this.\n * @param {Error=} opt_error The optional actual error object for this\n * error that should include the stack. Only browsers that have updated\n * to the latest spec will inlude this parameter.\n * @return {boolean} Whether to prevent the error from reaching the browser.\n */\n target.onerror = function(message, url, line, opt_col, opt_error) {\n if (oldErrorHandler) {\n oldErrorHandler(message, url, line, opt_col, opt_error);\n }\n logFunc({\n message: message,\n fileName: url,\n line: line,\n lineNumber: line,\n col: opt_col,\n error: opt_error\n });\n return retVal;\n };\n};\n\n\n/**\n * Creates a string representing an object and all its properties.\n * @param {Object|null|undefined} obj Object to expose.\n * @param {boolean=} opt_showFn Show the functions as well as the properties,\n * default is false.\n * @return {string} The string representation of `obj`.\n */\ngoog.debug.expose = function(obj, opt_showFn) {\n if (typeof obj == 'undefined') {\n return 'undefined';\n }\n if (obj == null) {\n return 'NULL';\n }\n var str = [];\n\n for (var x in obj) {\n if (!opt_showFn && goog.isFunction(obj[x])) {\n continue;\n }\n var s = x + ' = ';\n\n try {\n s += obj[x];\n } catch (e) {\n s += '*** ' + e + ' ***';\n }\n str.push(s);\n }\n return str.join('\\n');\n};\n\n\n/**\n * Creates a string representing a given primitive or object, and for an\n * object, all its properties and nested objects. NOTE: The output will include\n * Uids on all objects that were exposed. Any added Uids will be removed before\n * returning.\n * @param {*} obj Object to expose.\n * @param {boolean=} opt_showFn Also show properties that are functions (by\n * default, functions are omitted).\n * @return {string} A string representation of `obj`.\n */\ngoog.debug.deepExpose = function(obj, opt_showFn) {\n var str = [];\n\n // Track any objects where deepExpose added a Uid, so they can be cleaned up\n // before return. We do this globally, rather than only on ancestors so that\n // if the same object appears in the output, you can see it.\n var uidsToCleanup = [];\n var ancestorUids = {};\n\n var helper = function(obj, space) {\n var nestspace = space + ' ';\n\n var indentMultiline = function(str) {\n return str.replace(/\\n/g, '\\n' + space);\n };\n\n\n try {\n if (obj === undefined) {\n str.push('undefined');\n } else if (obj === null) {\n str.push('NULL');\n } else if (typeof obj === 'string') {\n str.push('\"' + indentMultiline(obj) + '\"');\n } else if (goog.isFunction(obj)) {\n str.push(indentMultiline(String(obj)));\n } else if (goog.isObject(obj)) {\n // Add a Uid if needed. The struct calls implicitly adds them.\n if (!goog.hasUid(obj)) {\n uidsToCleanup.push(obj);\n }\n var uid = goog.getUid(obj);\n if (ancestorUids[uid]) {\n str.push('*** reference loop detected (id=' + uid + ') ***');\n } else {\n ancestorUids[uid] = true;\n str.push('{');\n for (var x in obj) {\n if (!opt_showFn && goog.isFunction(obj[x])) {\n continue;\n }\n str.push('\\n');\n str.push(nestspace);\n str.push(x + ' = ');\n helper(obj[x], nestspace);\n }\n str.push('\\n' + space + '}');\n delete ancestorUids[uid];\n }\n } else {\n str.push(obj);\n }\n } catch (e) {\n str.push('*** ' + e + ' ***');\n }\n };\n\n helper(obj, '');\n\n // Cleanup any Uids that were added by the deepExpose.\n for (var i = 0; i < uidsToCleanup.length; i++) {\n goog.removeUid(uidsToCleanup[i]);\n }\n\n return str.join('');\n};\n\n\n/**\n * Recursively outputs a nested array as a string.\n * @param {Array<?>} arr The array.\n * @return {string} String representing nested array.\n */\ngoog.debug.exposeArray = function(arr) {\n var str = [];\n for (var i = 0; i < arr.length; i++) {\n if (Array.isArray(arr[i])) {\n str.push(goog.debug.exposeArray(arr[i]));\n } else {\n str.push(arr[i]);\n }\n }\n return '[ ' + str.join(', ') + ' ]';\n};\n\n\n/**\n * Normalizes the error/exception object between browsers.\n * @param {*} err Raw error object.\n * @return {{\n * message: (?|undefined),\n * name: (?|undefined),\n * lineNumber: (?|undefined),\n * fileName: (?|undefined),\n * stack: (?|undefined)\n * }} Normalized error object.\n * @suppress {strictMissingProperties} properties not defined on err\n */\ngoog.debug.normalizeErrorObject = function(err) {\n var href = goog.getObjectByName('window.location.href');\n if (err == null) {\n err = 'Unknown Error of type \"null/undefined\"';\n }\n if (typeof err === 'string') {\n return {\n 'message': err,\n 'name': 'Unknown error',\n 'lineNumber': 'Not available',\n 'fileName': href,\n 'stack': 'Not available'\n };\n }\n\n var lineNumber, fileName;\n var threwError = false;\n\n try {\n lineNumber = err.lineNumber || err.line || 'Not available';\n } catch (e) {\n // Firefox 2 sometimes throws an error when accessing 'lineNumber':\n // Message: Permission denied to get property UnnamedClass.lineNumber\n lineNumber = 'Not available';\n threwError = true;\n }\n\n try {\n fileName = err.fileName || err.filename || err.sourceURL ||\n // $googDebugFname may be set before a call to eval to set the filename\n // that the eval is supposed to present.\n goog.global['$googDebugFname'] || href;\n } catch (e) {\n // Firefox 2 may also throw an error when accessing 'filename'.\n fileName = 'Not available';\n threwError = true;\n }\n\n // The IE Error object contains only the name and the message.\n // The Safari Error object uses the line and sourceURL fields.\n if (threwError || !err.lineNumber || !err.fileName || !err.stack ||\n !err.message || !err.name) {\n var message = err.message;\n if (message == null) {\n if (err.constructor && err.constructor instanceof Function) {\n var ctorName = err.constructor.name ?\n err.constructor.name :\n goog.debug.getFunctionName(err.constructor);\n message = 'Unknown Error of type \"' + ctorName + '\"';\n } else {\n message = 'Unknown Error of unknown type';\n }\n }\n return {\n 'message': message,\n 'name': err.name || 'UnknownError',\n 'lineNumber': lineNumber,\n 'fileName': fileName,\n 'stack': err.stack || 'Not available'\n };\n }\n\n // Standards error object\n // Typed !Object. Should be a subtype of the return type, but it's not.\n return /** @type {?} */ (err);\n};\n\n\n/**\n * Converts an object to an Error using the object's toString if it's not\n * already an Error, adds a stacktrace if there isn't one, and optionally adds\n * an extra message.\n * @param {*} err The original thrown error, object, or string.\n * @param {string=} opt_message optional additional message to add to the\n * error.\n * @return {!Error} If err is an Error, it is enhanced and returned. Otherwise,\n * it is converted to an Error which is enhanced and returned.\n */\ngoog.debug.enhanceError = function(err, opt_message) {\n var error;\n if (!(err instanceof Error)) {\n error = Error(err);\n if (Error.captureStackTrace) {\n // Trim this function off the call stack, if we can.\n Error.captureStackTrace(error, goog.debug.enhanceError);\n }\n } else {\n error = err;\n }\n\n if (!error.stack) {\n error.stack = goog.debug.getStacktrace(goog.debug.enhanceError);\n }\n if (opt_message) {\n // find the first unoccupied 'messageX' property\n var x = 0;\n while (error['message' + x]) {\n ++x;\n }\n error['message' + x] = String(opt_message);\n }\n return error;\n};\n\n\n/**\n * Converts an object to an Error using the object's toString if it's not\n * already an Error, adds a stacktrace if there isn't one, and optionally adds\n * context to the Error, which is reported by the closure error reporter.\n * @param {*} err The original thrown error, object, or string.\n * @param {!Object<string, string>=} opt_context Key-value context to add to the\n * Error.\n * @return {!Error} If err is an Error, it is enhanced and returned. Otherwise,\n * it is converted to an Error which is enhanced and returned.\n */\ngoog.debug.enhanceErrorWithContext = function(err, opt_context) {\n var error = goog.debug.enhanceError(err);\n if (opt_context) {\n for (var key in opt_context) {\n goog.debug.errorcontext.addErrorContext(error, key, opt_context[key]);\n }\n }\n return error;\n};\n\n\n/**\n * Gets the current stack trace. Simple and iterative - doesn't worry about\n * catching circular references or getting the args.\n * @param {number=} opt_depth Optional maximum depth to trace back to.\n * @return {string} A string with the function names of all functions in the\n * stack, separated by \\n.\n * @suppress {es5Strict}\n */\ngoog.debug.getStacktraceSimple = function(opt_depth) {\n if (!goog.debug.FORCE_SLOPPY_STACKS) {\n var stack = goog.debug.getNativeStackTrace_(goog.debug.getStacktraceSimple);\n if (stack) {\n return stack;\n }\n // NOTE: browsers that have strict mode support also have native \"stack\"\n // properties. Fall-through for legacy browser support.\n }\n\n var sb = [];\n var fn = arguments.callee.caller;\n var depth = 0;\n\n while (fn && (!opt_depth || depth < opt_depth)) {\n sb.push(goog.debug.getFunctionName(fn));\n sb.push('()\\n');\n\n try {\n fn = fn.caller;\n } catch (e) {\n sb.push('[exception trying to get caller]\\n');\n break;\n }\n depth++;\n if (depth >= goog.debug.MAX_STACK_DEPTH) {\n sb.push('[...long stack...]');\n break;\n }\n }\n if (opt_depth && depth >= opt_depth) {\n sb.push('[...reached max depth limit...]');\n } else {\n sb.push('[end]');\n }\n\n return sb.join('');\n};\n\n\n/**\n * Max length of stack to try and output\n * @type {number}\n */\ngoog.debug.MAX_STACK_DEPTH = 50;\n\n\n/**\n * @param {Function} fn The function to start getting the trace from.\n * @return {?string}\n * @private\n */\ngoog.debug.getNativeStackTrace_ = function(fn) {\n var tempErr = new Error();\n if (Error.captureStackTrace) {\n Error.captureStackTrace(tempErr, fn);\n return String(tempErr.stack);\n } else {\n // IE10, only adds stack traces when an exception is thrown.\n try {\n throw tempErr;\n } catch (e) {\n tempErr = e;\n }\n var stack = tempErr.stack;\n if (stack) {\n return String(stack);\n }\n }\n return null;\n};\n\n\n/**\n * Gets the current stack trace, either starting from the caller or starting\n * from a specified function that's currently on the call stack.\n * @param {?Function=} fn If provided, when collecting the stack trace all\n * frames above the topmost call to this function, including that call,\n * will be left out of the stack trace.\n * @return {string} Stack trace.\n * @suppress {es5Strict}\n */\ngoog.debug.getStacktrace = function(fn) {\n var stack;\n if (!goog.debug.FORCE_SLOPPY_STACKS) {\n // Try to get the stack trace from the environment if it is available.\n var contextFn = fn || goog.debug.getStacktrace;\n stack = goog.debug.getNativeStackTrace_(contextFn);\n }\n if (!stack) {\n // NOTE: browsers that have strict mode support also have native \"stack\"\n // properties. This function will throw in strict mode.\n stack = goog.debug.getStacktraceHelper_(fn || arguments.callee.caller, []);\n }\n return stack;\n};\n\n\n/**\n * Private helper for getStacktrace().\n * @param {?Function} fn If provided, when collecting the stack trace all\n * frames above the topmost call to this function, including that call,\n * will be left out of the stack trace.\n * @param {Array<!Function>} visited List of functions visited so far.\n * @return {string} Stack trace starting from function fn.\n * @suppress {es5Strict}\n * @private\n */\ngoog.debug.getStacktraceHelper_ = function(fn, visited) {\n var sb = [];\n\n // Circular reference, certain functions like bind seem to cause a recursive\n // loop so we need to catch circular references\n if (goog.array.contains(visited, fn)) {\n sb.push('[...circular reference...]');\n\n // Traverse the call stack until function not found or max depth is reached\n } else if (fn && visited.length < goog.debug.MAX_STACK_DEPTH) {\n sb.push(goog.debug.getFunctionName(fn) + '(');\n var args = fn.arguments;\n // Args may be null for some special functions such as host objects or eval.\n for (var i = 0; args && i < args.length; i++) {\n if (i > 0) {\n sb.push(', ');\n }\n var argDesc;\n var arg = args[i];\n switch (typeof arg) {\n case 'object':\n argDesc = arg ? 'object' : 'null';\n break;\n\n case 'string':\n argDesc = arg;\n break;\n\n case 'number':\n argDesc = String(arg);\n break;\n\n case 'boolean':\n argDesc = arg ? 'true' : 'false';\n break;\n\n case 'function':\n argDesc = goog.debug.getFunctionName(arg);\n argDesc = argDesc ? argDesc : '[fn]';\n break;\n\n case 'undefined':\n default:\n argDesc = typeof arg;\n break;\n }\n\n if (argDesc.length > 40) {\n argDesc = argDesc.substr(0, 40) + '...';\n }\n sb.push(argDesc);\n }\n visited.push(fn);\n sb.push(')\\n');\n\n try {\n sb.push(goog.debug.getStacktraceHelper_(fn.caller, visited));\n } catch (e) {\n sb.push('[exception trying to get caller]\\n');\n }\n\n } else if (fn) {\n sb.push('[...long stack...]');\n } else {\n sb.push('[end]');\n }\n return sb.join('');\n};\n\n\n/**\n * Gets a function name\n * @param {Function} fn Function to get name of.\n * @return {string} Function's name.\n */\ngoog.debug.getFunctionName = function(fn) {\n if (goog.debug.fnNameCache_[fn]) {\n return goog.debug.fnNameCache_[fn];\n }\n\n // Heuristically determine function name based on code.\n var functionSource = String(fn);\n if (!goog.debug.fnNameCache_[functionSource]) {\n var matches = /function\\s+([^\\(]+)/m.exec(functionSource);\n if (matches) {\n var method = matches[1];\n goog.debug.fnNameCache_[functionSource] = method;\n } else {\n goog.debug.fnNameCache_[functionSource] = '[Anonymous]';\n }\n }\n\n return goog.debug.fnNameCache_[functionSource];\n};\n\n\n/**\n * Makes whitespace visible by replacing it with printable characters.\n * This is useful in finding diffrences between the expected and the actual\n * output strings of a testcase.\n * @param {string} string whose whitespace needs to be made visible.\n * @return {string} string whose whitespace is made visible.\n */\ngoog.debug.makeWhitespaceVisible = function(string) {\n return string.replace(/ /g, '[_]')\n .replace(/\\f/g, '[f]')\n .replace(/\\n/g, '[n]\\n')\n .replace(/\\r/g, '[r]')\n .replace(/\\t/g, '[t]');\n};\n\n\n/**\n * Returns the type of a value. If a constructor is passed, and a suitable\n * string cannot be found, 'unknown type name' will be returned.\n *\n * <p>Forked rather than moved from {@link goog.asserts.getType_}\n * to avoid adding a dependency to goog.asserts.\n * @param {*} value A constructor, object, or primitive.\n * @return {string} The best display name for the value, or 'unknown type name'.\n */\ngoog.debug.runtimeType = function(value) {\n if (value instanceof Function) {\n return value.displayName || value.name || 'unknown type name';\n } else if (value instanceof Object) {\n return /** @type {string} */ (value.constructor.displayName) ||\n value.constructor.name || Object.prototype.toString.call(value);\n } else {\n return value === null ? 'null' : typeof value;\n }\n};\n\n\n/**\n * Hash map for storing function names that have already been looked up.\n * @type {Object}\n * @private\n */\ngoog.debug.fnNameCache_ = {};\n\n\n/**\n * Private internal function to support goog.debug.freeze.\n * @param {T} arg\n * @return {T}\n * @template T\n * @private\n */\ngoog.debug.freezeInternal_ = goog.DEBUG && Object.freeze || function(arg) {\n return arg;\n};\n\n\n/**\n * Freezes the given object, but only in debug mode (and in browsers that\n * support it). Note that this is a shallow freeze, so for deeply nested\n * objects it must be called at every level to ensure deep immutability.\n * @param {T} arg\n * @return {T}\n * @template T\n */\ngoog.debug.freeze = function(arg) {\n // NOTE: this compiles to nothing, but hides the possible side effect of\n // freezeInternal_ from the compiler so that the entire call can be\n // removed if the result is not used.\n return {\n valueOf: function() {\n return goog.debug.freezeInternal_(arg);\n }\n }.valueOf();\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Browser capability checks for the events package.\n */\n\n\ngoog.provide('goog.events.BrowserFeature');\n\ngoog.require('goog.userAgent');\ngoog.scope(function() {\n\n\n\n/**\n * Enum of browser capabilities.\n * @enum {boolean}\n */\ngoog.events.BrowserFeature = {\n /**\n * Whether the button attribute of the event is W3C compliant. False in\n * Internet Explorer prior to version 9; document-version dependent.\n */\n HAS_W3C_BUTTON:\n !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),\n\n /**\n * Whether the browser supports full W3C event model.\n */\n HAS_W3C_EVENT_SUPPORT:\n !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),\n\n /**\n * To prevent default in IE7-8 for certain keydown events we need set the\n * keyCode to -1.\n */\n SET_KEY_CODE_TO_PREVENT_DEFAULT:\n goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),\n\n /**\n * Whether the `navigator.onLine` property is supported.\n */\n HAS_NAVIGATOR_ONLINE_PROPERTY:\n !goog.userAgent.WEBKIT || goog.userAgent.isVersionOrHigher('528'),\n\n /**\n * Whether HTML5 network online/offline events are supported.\n */\n HAS_HTML5_NETWORK_EVENT_SUPPORT:\n goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9b') ||\n goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8') ||\n goog.userAgent.OPERA && goog.userAgent.isVersionOrHigher('9.5') ||\n goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('528'),\n\n /**\n * Whether HTML5 network events fire on document.body, or otherwise the\n * window.\n */\n HTML5_NETWORK_EVENTS_FIRE_ON_BODY:\n goog.userAgent.GECKO && !goog.userAgent.isVersionOrHigher('8') ||\n goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),\n\n /**\n * Whether touch is enabled in the browser.\n */\n TOUCH_ENABLED:\n ('ontouchstart' in goog.global ||\n !!(goog.global['document'] && document.documentElement &&\n 'ontouchstart' in document.documentElement) ||\n // IE10 uses non-standard touch events, so it has a different check.\n !!(goog.global['navigator'] &&\n (goog.global['navigator']['maxTouchPoints'] ||\n goog.global['navigator']['msMaxTouchPoints']))),\n\n /**\n * Whether addEventListener supports W3C standard pointer events.\n * http://www.w3.org/TR/pointerevents/\n */\n POINTER_EVENTS: ('PointerEvent' in goog.global),\n\n /**\n * Whether addEventListener supports MSPointer events (only used in IE10).\n * http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n * http://msdn.microsoft.com/library/hh673557(v=vs.85).aspx\n */\n MSPOINTER_EVENTS:\n ('MSPointerEvent' in goog.global &&\n !!(goog.global['navigator'] &&\n goog.global['navigator']['msPointerEnabled'])),\n\n /**\n * Whether addEventListener supports {passive: true}.\n * https://developers.google.com/web/updates/2016/06/passive-event-listeners\n */\n PASSIVE_EVENTS: purify(function() {\n // If we're in a web worker or other custom environment, we can't tell.\n if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8\n return false;\n }\n\n var passive = false;\n var options = Object.defineProperty({}, 'passive', {\n get: function() {\n passive = true;\n }\n });\n try {\n goog.global.addEventListener('test', goog.nullFunction, options);\n goog.global.removeEventListener('test', goog.nullFunction, options);\n } catch (e) {\n }\n\n return passive;\n })\n};\n\n\n/**\n * Tricks Closure Compiler into believing that a function is pure. The compiler\n * assumes that any `valueOf` function is pure, without analyzing its contents.\n *\n * @param {function(): T} fn\n * @return {T}\n * @template T\n */\nfunction purify(fn) {\n return ({valueOf: fn}).valueOf();\n}\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A base class for event objects.\n */\n\n\ngoog.provide('goog.events.Event');\ngoog.provide('goog.events.EventLike');\n\n/**\n * goog.events.Event no longer depends on goog.Disposable. Keep requiring\n * goog.Disposable here to not break projects which assume this dependency.\n * @suppress {extraRequire}\n */\ngoog.require('goog.Disposable');\ngoog.require('goog.events.EventId');\n\n\n/**\n * A typedef for event like objects that are dispatchable via the\n * goog.events.dispatchEvent function. strings are treated as the type for a\n * goog.events.Event. Objects are treated as an extension of a new\n * goog.events.Event with the type property of the object being used as the type\n * of the Event.\n * @typedef {string|Object|goog.events.Event|goog.events.EventId}\n */\ngoog.events.EventLike;\n\n\n\n/**\n * A base class for event objects, so that they can support preventDefault and\n * stopPropagation.\n *\n * @param {string|!goog.events.EventId} type Event Type.\n * @param {Object=} opt_target Reference to the object that is the target of\n * this event. It has to implement the `EventTarget` interface\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\n * @constructor\n */\ngoog.events.Event = function(type, opt_target) {\n /**\n * Event type.\n * @type {string}\n */\n this.type = type instanceof goog.events.EventId ? String(type) : type;\n\n /**\n * TODO(tbreisacher): The type should probably be\n * EventTarget|goog.events.EventTarget.\n *\n * Target of the event.\n * @type {Object|undefined}\n */\n this.target = opt_target;\n\n /**\n * Object that had the listener attached.\n * @type {Object|undefined}\n */\n this.currentTarget = this.target;\n\n /**\n * Whether to cancel the event in internal capture/bubble processing for IE.\n * @type {boolean}\n * @private\n */\n this.propagationStopped_ = false;\n\n /**\n * Whether the default action has been prevented.\n * This is a property to match the W3C specification at\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\n * #events-event-type-defaultPrevented}.\n * Must be treated as read-only outside the class.\n * @type {boolean}\n */\n this.defaultPrevented = false;\n};\n\n/**\n * @return {boolean} true iff internal propagation has been stopped.\n */\ngoog.events.Event.prototype.hasPropagationStopped = function() {\n return this.propagationStopped_;\n};\n\n/**\n * Stops event propagation.\n */\ngoog.events.Event.prototype.stopPropagation = function() {\n this.propagationStopped_ = true;\n};\n\n\n/**\n * Prevents the default action, for example a link redirecting to a url.\n */\ngoog.events.Event.prototype.preventDefault = function() {\n this.defaultPrevented = true;\n};\n\n\n/**\n * Stops the propagation of the event. It is equivalent to\n * `e.stopPropagation()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n */\ngoog.events.Event.stopPropagation = function(e) {\n e.stopPropagation();\n};\n\n\n/**\n * Prevents the default action. It is equivalent to\n * `e.preventDefault()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n */\ngoog.events.Event.preventDefault = function(e) {\n e.preventDefault();\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A patched, standardized event object for browser events.\n *\n * <pre>\n * The patched event object contains the following members:\n * - type {string} Event type, e.g. 'click'\n * - target {Object} The element that actually triggered the event\n * - currentTarget {Object} The element the listener is attached to\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\n * - offsetX {number} X-coordinate relative to target\n * - offsetY {number} Y-coordinate relative to target\n * - clientX {number} X-coordinate relative to viewport\n * - clientY {number} Y-coordinate relative to viewport\n * - screenX {number} X-coordinate relative to the edge of the screen\n * - screenY {number} Y-coordinate relative to the edge of the screen\n * - button {number} Mouse button. Use isButton() to test.\n * - keyCode {number} Key-code\n * - ctrlKey {boolean} Was ctrl key depressed\n * - altKey {boolean} Was alt key depressed\n * - shiftKey {boolean} Was shift key depressed\n * - metaKey {boolean} Was meta key depressed\n * - pointerId {number} Pointer ID\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\n * - defaultPrevented {boolean} Whether the default action has been prevented\n * - state {Object} History state object\n *\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\n * key and character code use {@link goog.events.KeyHandler}.\n * </pre>\n */\n\ngoog.provide('goog.events.BrowserEvent');\ngoog.provide('goog.events.BrowserEvent.MouseButton');\ngoog.provide('goog.events.BrowserEvent.PointerType');\n\ngoog.require('goog.debug');\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventType');\ngoog.require('goog.reflect');\ngoog.require('goog.userAgent');\n\n/**\n * @define {boolean} If true, use the layerX and layerY properties of a native\n * browser event over the offsetX and offsetY properties, which cause expensive\n * reflow. If layerX or layerY is not defined, offsetX and offsetY will be used\n * as usual.\n */\ngoog.events.USE_LAYER_XY_AS_OFFSET_XY =\n goog.define('goog.events.USE_LAYER_XY_AS_OFFSET_XY', false);\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * The content of this object will not be initialized if no event object is\n * provided. If this is the case, init() needs to be invoked separately.\n * @param {Event=} opt_e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.events.BrowserEvent = function(opt_e, opt_currentTarget) {\n goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');\n\n /**\n * Target that fired the event.\n * @override\n * @type {?Node}\n */\n this.target = null;\n\n /**\n * Node that had the listener attached.\n * @override\n * @type {?Node|undefined}\n */\n this.currentTarget = null;\n\n /**\n * For mouseover and mouseout events, the related object for the event.\n * @type {?Node}\n */\n this.relatedTarget = null;\n\n /**\n * X-coordinate relative to target.\n * @type {number}\n */\n this.offsetX = 0;\n\n /**\n * Y-coordinate relative to target.\n * @type {number}\n */\n this.offsetY = 0;\n\n /**\n * X-coordinate relative to the window.\n * @type {number}\n */\n this.clientX = 0;\n\n /**\n * Y-coordinate relative to the window.\n * @type {number}\n */\n this.clientY = 0;\n\n /**\n * X-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenX = 0;\n\n /**\n * Y-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenY = 0;\n\n /**\n * Which mouse button was pressed.\n * @type {number}\n */\n this.button = 0;\n\n /**\n * Key of key press.\n * @type {string}\n */\n this.key = '';\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.keyCode = 0;\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.charCode = 0;\n\n /**\n * Whether control was pressed at time of event.\n * @type {boolean}\n */\n this.ctrlKey = false;\n\n /**\n * Whether alt was pressed at time of event.\n * @type {boolean}\n */\n this.altKey = false;\n\n /**\n * Whether shift was pressed at time of event.\n * @type {boolean}\n */\n this.shiftKey = false;\n\n /**\n * Whether the meta key was pressed at time of event.\n * @type {boolean}\n */\n this.metaKey = false;\n\n /**\n * History state object, only set for PopState events where it's a copy of the\n * state object provided to pushState or replaceState.\n * @type {?Object}\n */\n this.state = null;\n\n /**\n * Whether the default platform modifier key was pressed at time of event.\n * (This is control for all platforms except Mac, where it's Meta.)\n * @type {boolean}\n */\n this.platformModifierKey = false;\n\n /**\n * @type {number}\n */\n this.pointerId = 0;\n\n /**\n * @type {string}\n */\n this.pointerType = '';\n\n /**\n * The browser event object.\n * @private {?Event}\n */\n this.event_ = null;\n\n if (opt_e) {\n this.init(opt_e, opt_currentTarget);\n }\n};\ngoog.inherits(goog.events.BrowserEvent, goog.events.Event);\n\n\n/**\n * Normalized button constants for the mouse.\n * @enum {number}\n */\ngoog.events.BrowserEvent.MouseButton = {\n LEFT: 0,\n MIDDLE: 1,\n RIGHT: 2\n};\n\n\n/**\n * Normalized pointer type constants for pointer events.\n * @enum {string}\n */\ngoog.events.BrowserEvent.PointerType = {\n MOUSE: 'mouse',\n PEN: 'pen',\n TOUCH: 'touch'\n};\n\n\n/**\n * Static data for mapping mouse buttons.\n * @type {!Array<number>}\n * @deprecated Use `goog.events.BrowserEvent.IE_BUTTON_MAP` instead.\n */\ngoog.events.BrowserEvent.IEButtonMap = goog.debug.freeze([\n 1, // LEFT\n 4, // MIDDLE\n 2 // RIGHT\n]);\n\n\n/**\n * Static data for mapping mouse buttons.\n * @const {!Array<number>}\n */\ngoog.events.BrowserEvent.IE_BUTTON_MAP = goog.events.BrowserEvent.IEButtonMap;\n\n\n/**\n * Static data for mapping MSPointerEvent types to PointerEvent types.\n * @const {!Object<number, goog.events.BrowserEvent.PointerType>}\n */\ngoog.events.BrowserEvent.IE_POINTER_TYPE_MAP = goog.debug.freeze({\n 2: goog.events.BrowserEvent.PointerType.TOUCH,\n 3: goog.events.BrowserEvent.PointerType.PEN,\n 4: goog.events.BrowserEvent.PointerType.MOUSE\n});\n\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * @param {Event} e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n */\ngoog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {\n var type = this.type = e.type;\n\n /**\n * On touch devices use the first \"changed touch\" as the relevant touch.\n * @type {?Touch}\n */\n var relevantTouch =\n e.changedTouches && e.changedTouches.length ? e.changedTouches[0] : null;\n\n // TODO(nicksantos): Change this.target to type EventTarget.\n this.target = /** @type {Node} */ (e.target) || e.srcElement;\n\n // TODO(nicksantos): Change this.currentTarget to type EventTarget.\n this.currentTarget = /** @type {Node} */ (opt_currentTarget);\n\n var relatedTarget = /** @type {Node} */ (e.relatedTarget);\n if (relatedTarget) {\n // There's a bug in FireFox where sometimes, relatedTarget will be a\n // chrome element, and accessing any property of it will get a permission\n // denied exception. See:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=497780\n if (goog.userAgent.GECKO) {\n if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {\n relatedTarget = null;\n }\n }\n } else if (type == goog.events.EventType.MOUSEOVER) {\n relatedTarget = e.fromElement;\n } else if (type == goog.events.EventType.MOUSEOUT) {\n relatedTarget = e.toElement;\n }\n\n this.relatedTarget = relatedTarget;\n\n if (relevantTouch) {\n this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :\n relevantTouch.pageX;\n this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :\n relevantTouch.pageY;\n this.screenX = relevantTouch.screenX || 0;\n this.screenY = relevantTouch.screenY || 0;\n } else {\n if (goog.events.USE_LAYER_XY_AS_OFFSET_XY) {\n this.offsetX = (e.layerX !== undefined) ? e.layerX : e.offsetX;\n this.offsetY = (e.layerY !== undefined) ? e.layerY : e.offsetY;\n } else {\n // Webkit emits a lame warning whenever layerX/layerY is accessed.\n // http://code.google.com/p/chromium/issues/detail?id=101733\n this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?\n e.offsetX :\n e.layerX;\n this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?\n e.offsetY :\n e.layerY;\n }\n this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;\n this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;\n this.screenX = e.screenX || 0;\n this.screenY = e.screenY || 0;\n }\n\n this.button = e.button;\n\n this.keyCode = e.keyCode || 0;\n this.key = e.key || '';\n this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);\n this.ctrlKey = e.ctrlKey;\n this.altKey = e.altKey;\n this.shiftKey = e.shiftKey;\n this.metaKey = e.metaKey;\n this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;\n this.pointerId = e.pointerId || 0;\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\n this.state = e.state;\n this.event_ = e;\n if (e.defaultPrevented) {\n this.preventDefault();\n }\n};\n\n\n/**\n * Tests to see which button was pressed during the event. This is really only\n * useful in IE and Gecko browsers. And in IE, it's only useful for\n * mousedown/mouseup events, because click only fires for the left mouse button.\n *\n * Safari 2 only reports the left button being clicked, and uses the value '1'\n * instead of 0. Opera only reports a mousedown event for the middle button, and\n * no mouse events for the right button. Opera has default behavior for left and\n * middle click that can only be overridden via a configuration setting.\n *\n * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.\n *\n * @param {goog.events.BrowserEvent.MouseButton} button The button\n * to test for.\n * @return {boolean} True if button was pressed.\n */\ngoog.events.BrowserEvent.prototype.isButton = function(button) {\n if (!goog.events.BrowserFeature.HAS_W3C_BUTTON) {\n if (this.type == 'click') {\n return button == goog.events.BrowserEvent.MouseButton.LEFT;\n } else {\n return !!(\n this.event_.button & goog.events.BrowserEvent.IE_BUTTON_MAP[button]);\n }\n } else {\n return this.event_.button == button;\n }\n};\n\n\n/**\n * Whether this has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @return {boolean} The result.\n */\ngoog.events.BrowserEvent.prototype.isMouseActionButton = function() {\n // Webkit does not ctrl+click to be a right-click, so we\n // normalize it to behave like Gecko and Opera.\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\n !(goog.userAgent.WEBKIT && goog.userAgent.MAC && this.ctrlKey);\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\n goog.events.BrowserEvent.superClass_.stopPropagation.call(this);\n if (this.event_.stopPropagation) {\n this.event_.stopPropagation();\n } else {\n this.event_.cancelBubble = true;\n }\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.preventDefault = function() {\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n var be = this.event_;\n if (!be.preventDefault) {\n be.returnValue = false;\n if (goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT) {\n\n try {\n // Most keys can be prevented using returnValue. Some special keys\n // require setting the keyCode to -1 as well:\n //\n // In IE7:\n // F3, F5, F10, F11, Ctrl+P, Crtl+O, Ctrl+F (these are taken from IE6)\n //\n // In IE8:\n // Ctrl+P, Crtl+O, Ctrl+F (F1-F12 cannot be stopped through the event)\n //\n // We therefore do this for all function keys as well as when Ctrl key\n // is pressed.\n var VK_F1 = 112;\n var VK_F12 = 123;\n if (be.ctrlKey || be.keyCode >= VK_F1 && be.keyCode <= VK_F12) {\n be.keyCode = -1;\n }\n } catch (ex) {\n // IE throws an 'access denied' exception when trying to change\n // keyCode in some situations (e.g. srcElement is input[type=file],\n // or srcElement is an anchor tag rewritten by parent's innerHTML).\n // Do nothing in this case.\n }\n }\n } else {\n be.preventDefault();\n }\n};\n\n\n/**\n * @return {Event} The underlying browser event object.\n */\ngoog.events.BrowserEvent.prototype.getBrowserEvent = function() {\n return this.event_;\n};\n\n\n/**\n * Extracts the pointer type from the given event.\n * @param {!Event} e\n * @return {string} The pointer type, e.g. 'mouse', 'pen', or 'touch'.\n * @private\n */\ngoog.events.BrowserEvent.getPointerType_ = function(e) {\n if (typeof (e.pointerType) === 'string') {\n return e.pointerType;\n }\n // IE10 uses integer codes for pointer type.\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Event Types.\n */\n\n\ngoog.provide('goog.events.EventType');\ngoog.provide('goog.events.MouseAsMouseEventType');\ngoog.provide('goog.events.MouseEvents');\ngoog.provide('goog.events.PointerAsMouseEventType');\ngoog.provide('goog.events.PointerAsTouchEventType');\ngoog.provide('goog.events.PointerFallbackEventType');\ngoog.provide('goog.events.PointerTouchFallbackEventType');\n\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.userAgent');\n\n\n/**\n * Returns a prefixed event name for the current browser.\n * @param {string} eventName The name of the event.\n * @return {string} The prefixed event name.\n * @suppress {missingRequire|missingProvide}\n * @private\n */\ngoog.events.getVendorPrefixedName_ = function(eventName) {\n return goog.userAgent.WEBKIT ?\n 'webkit' + eventName :\n (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :\n eventName.toLowerCase());\n};\n\n\n/**\n * Constants for event names.\n * @enum {string}\n */\ngoog.events.EventType = {\n // Mouse events\n CLICK: 'click',\n RIGHTCLICK: 'rightclick',\n DBLCLICK: 'dblclick',\n AUXCLICK: 'auxclick',\n MOUSEDOWN: 'mousedown',\n MOUSEUP: 'mouseup',\n MOUSEOVER: 'mouseover',\n MOUSEOUT: 'mouseout',\n MOUSEMOVE: 'mousemove',\n MOUSEENTER: 'mouseenter',\n MOUSELEAVE: 'mouseleave',\n\n // Non-existent event; will never fire. This exists as a mouse counterpart to\n // POINTERCANCEL.\n MOUSECANCEL: 'mousecancel',\n\n // Selection events.\n // https://www.w3.org/TR/selection-api/\n SELECTIONCHANGE: 'selectionchange',\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\n\n // Wheel events\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\n WHEEL: 'wheel',\n\n // Key events\n KEYPRESS: 'keypress',\n KEYDOWN: 'keydown',\n KEYUP: 'keyup',\n\n // Focus\n BLUR: 'blur',\n FOCUS: 'focus',\n DEACTIVATE: 'deactivate', // IE only\n FOCUSIN: 'focusin',\n FOCUSOUT: 'focusout',\n\n // Forms\n CHANGE: 'change',\n RESET: 'reset',\n SELECT: 'select',\n SUBMIT: 'submit',\n INPUT: 'input',\n PROPERTYCHANGE: 'propertychange', // IE only\n\n // Drag and drop\n DRAGSTART: 'dragstart',\n DRAG: 'drag',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DRAGLEAVE: 'dragleave',\n DROP: 'drop',\n DRAGEND: 'dragend',\n\n // Touch events\n // Note that other touch events exist, but we should follow the W3C list here.\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\n TOUCHSTART: 'touchstart',\n TOUCHMOVE: 'touchmove',\n TOUCHEND: 'touchend',\n TOUCHCANCEL: 'touchcancel',\n\n // Misc\n BEFOREUNLOAD: 'beforeunload',\n CONSOLEMESSAGE: 'consolemessage',\n CONTEXTMENU: 'contextmenu',\n DEVICECHANGE: 'devicechange',\n DEVICEMOTION: 'devicemotion',\n DEVICEORIENTATION: 'deviceorientation',\n DOMCONTENTLOADED: 'DOMContentLoaded',\n ERROR: 'error',\n HELP: 'help',\n LOAD: 'load',\n LOSECAPTURE: 'losecapture',\n ORIENTATIONCHANGE: 'orientationchange',\n READYSTATECHANGE: 'readystatechange',\n RESIZE: 'resize',\n SCROLL: 'scroll',\n UNLOAD: 'unload',\n\n // Media events\n CANPLAY: 'canplay',\n CANPLAYTHROUGH: 'canplaythrough',\n DURATIONCHANGE: 'durationchange',\n EMPTIED: 'emptied',\n ENDED: 'ended',\n LOADEDDATA: 'loadeddata',\n LOADEDMETADATA: 'loadedmetadata',\n PAUSE: 'pause',\n PLAY: 'play',\n PLAYING: 'playing',\n PROGRESS: 'progress',\n RATECHANGE: 'ratechange',\n SEEKED: 'seeked',\n SEEKING: 'seeking',\n STALLED: 'stalled',\n SUSPEND: 'suspend',\n TIMEUPDATE: 'timeupdate',\n VOLUMECHANGE: 'volumechange',\n WAITING: 'waiting',\n\n // Media Source Extensions events\n // https://www.w3.org/TR/media-source/#mediasource-events\n SOURCEOPEN: 'sourceopen',\n SOURCEENDED: 'sourceended',\n SOURCECLOSED: 'sourceclosed',\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\n ABORT: 'abort',\n UPDATE: 'update',\n UPDATESTART: 'updatestart',\n UPDATEEND: 'updateend',\n\n // HTML 5 History events\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\n HASHCHANGE: 'hashchange',\n PAGEHIDE: 'pagehide',\n PAGESHOW: 'pageshow',\n POPSTATE: 'popstate',\n\n // Copy and Paste\n // Support is limited. Make sure it works on your favorite browser\n // before using.\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\n COPY: 'copy',\n PASTE: 'paste',\n CUT: 'cut',\n BEFORECOPY: 'beforecopy',\n BEFORECUT: 'beforecut',\n BEFOREPASTE: 'beforepaste',\n\n // HTML5 online/offline events.\n // http://www.w3.org/TR/offline-webapps/#related\n ONLINE: 'online',\n OFFLINE: 'offline',\n\n // HTML 5 worker events\n MESSAGE: 'message',\n CONNECT: 'connect',\n\n // Service Worker Events - ServiceWorkerGlobalScope context\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\n // Note: message event defined in worker events section\n INSTALL: 'install',\n ACTIVATE: 'activate',\n FETCH: 'fetch',\n FOREIGNFETCH: 'foreignfetch',\n MESSAGEERROR: 'messageerror',\n\n // Service Worker Events - Document context\n // See https://w3c.github.io/ServiceWorker/#document-context-events\n STATECHANGE: 'statechange',\n UPDATEFOUND: 'updatefound',\n CONTROLLERCHANGE: 'controllerchange',\n\n // CSS animation events.\n /** @suppress {missingRequire} */\n ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),\n /** @suppress {missingRequire} */\n ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),\n /** @suppress {missingRequire} */\n ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),\n\n // CSS transition events. Based on the browser support described at:\n // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility\n /** @suppress {missingRequire} */\n TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),\n\n // W3C Pointer Events\n // http://www.w3.org/TR/pointerevents/\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTERCANCEL: 'pointercancel',\n POINTERMOVE: 'pointermove',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n GOTPOINTERCAPTURE: 'gotpointercapture',\n LOSTPOINTERCAPTURE: 'lostpointercapture',\n\n // IE specific events.\n // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n // Note: these events will be supplanted in IE11.\n MSGESTURECHANGE: 'MSGestureChange',\n MSGESTUREEND: 'MSGestureEnd',\n MSGESTUREHOLD: 'MSGestureHold',\n MSGESTURESTART: 'MSGestureStart',\n MSGESTURETAP: 'MSGestureTap',\n MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',\n MSINERTIASTART: 'MSInertiaStart',\n MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',\n MSPOINTERCANCEL: 'MSPointerCancel',\n MSPOINTERDOWN: 'MSPointerDown',\n MSPOINTERENTER: 'MSPointerEnter',\n MSPOINTERHOVER: 'MSPointerHover',\n MSPOINTERLEAVE: 'MSPointerLeave',\n MSPOINTERMOVE: 'MSPointerMove',\n MSPOINTEROUT: 'MSPointerOut',\n MSPOINTEROVER: 'MSPointerOver',\n MSPOINTERUP: 'MSPointerUp',\n\n // Native IMEs/input tools events.\n TEXT: 'text',\n // The textInput event is supported in IE9+, but only in lower case. All other\n // browsers use the camel-case event name.\n TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',\n COMPOSITIONSTART: 'compositionstart',\n COMPOSITIONUPDATE: 'compositionupdate',\n COMPOSITIONEND: 'compositionend',\n\n // The beforeinput event is initially only supported in Safari. See\n // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome\n // implementation tracking.\n BEFOREINPUT: 'beforeinput',\n\n // Webview tag events\n // See https://developer.chrome.com/apps/tags/webview\n EXIT: 'exit',\n LOADABORT: 'loadabort',\n LOADCOMMIT: 'loadcommit',\n LOADREDIRECT: 'loadredirect',\n LOADSTART: 'loadstart',\n LOADSTOP: 'loadstop',\n RESPONSIVE: 'responsive',\n SIZECHANGED: 'sizechanged',\n UNRESPONSIVE: 'unresponsive',\n\n // HTML5 Page Visibility API. See details at\n // `goog.labs.dom.PageVisibilityMonitor`.\n VISIBILITYCHANGE: 'visibilitychange',\n\n // LocalStorage event.\n STORAGE: 'storage',\n\n // DOM Level 2 mutation events (deprecated).\n DOMSUBTREEMODIFIED: 'DOMSubtreeModified',\n DOMNODEINSERTED: 'DOMNodeInserted',\n DOMNODEREMOVED: 'DOMNodeRemoved',\n DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',\n DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',\n DOMATTRMODIFIED: 'DOMAttrModified',\n DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',\n\n // Print events.\n BEFOREPRINT: 'beforeprint',\n AFTERPRINT: 'afterprint',\n\n // Web app manifest events.\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\n APPINSTALLED: 'appinstalled'\n};\n\n\n/**\n * Returns one of the given pointer fallback event names in order of preference:\n * 1. pointerEventName\n * 2. msPointerEventName\n * 3. fallbackEventName\n * @param {string} pointerEventName\n * @param {string} msPointerEventName\n * @param {string} fallbackEventName\n * @return {string} The supported pointer or fallback (mouse or touch) event\n * name.\n * @private\n */\ngoog.events.getPointerFallbackEventName_ = function(\n pointerEventName, msPointerEventName, fallbackEventName) {\n if (goog.events.BrowserFeature.POINTER_EVENTS) {\n return pointerEventName;\n }\n if (goog.events.BrowserFeature.MSPOINTER_EVENTS) {\n return msPointerEventName;\n }\n return fallbackEventName;\n};\n\n\n/**\n * Constants for pointer event names that fall back to corresponding mouse event\n * names on unsupported platforms. These are intended to be drop-in replacements\n * for corresponding values in `goog.events.EventType`.\n * @enum {string}\n */\ngoog.events.PointerFallbackEventType = {\n POINTERDOWN: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\n goog.events.EventType.MOUSEDOWN),\n POINTERUP: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\n goog.events.EventType.MOUSEUP),\n POINTERCANCEL: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERCANCEL,\n goog.events.EventType.MSPOINTERCANCEL,\n // When falling back to mouse events, there is no MOUSECANCEL equivalent\n // of POINTERCANCEL. In this case POINTERUP already falls back to MOUSEUP\n // which represents both UP and CANCEL. POINTERCANCEL does not fall back\n // to MOUSEUP to prevent listening twice on the same event.\n goog.events.EventType.MOUSECANCEL),\n POINTERMOVE: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\n goog.events.EventType.MOUSEMOVE),\n POINTEROVER: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTEROVER, goog.events.EventType.MSPOINTEROVER,\n goog.events.EventType.MOUSEOVER),\n POINTEROUT: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTEROUT, goog.events.EventType.MSPOINTEROUT,\n goog.events.EventType.MOUSEOUT),\n POINTERENTER: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERENTER, goog.events.EventType.MSPOINTERENTER,\n goog.events.EventType.MOUSEENTER),\n POINTERLEAVE: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERLEAVE, goog.events.EventType.MSPOINTERLEAVE,\n goog.events.EventType.MOUSELEAVE)\n};\n\n\n/**\n * Constants for pointer event names that fall back to corresponding touch event\n * names on unsupported platforms. These are intended to be drop-in replacements\n * for corresponding values in `goog.events.EventType`.\n * @enum {string}\n */\ngoog.events.PointerTouchFallbackEventType = {\n POINTERDOWN: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\n goog.events.EventType.TOUCHSTART),\n POINTERUP: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\n goog.events.EventType.TOUCHEND),\n POINTERCANCEL: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERCANCEL,\n goog.events.EventType.MSPOINTERCANCEL, goog.events.EventType.TOUCHCANCEL),\n POINTERMOVE: goog.events.getPointerFallbackEventName_(\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\n goog.events.EventType.TOUCHMOVE)\n};\n\n\n/**\n * Mapping of mouse event names to underlying browser event names.\n * @typedef {{\n * MOUSEDOWN: string,\n * MOUSEUP: string,\n * MOUSECANCEL:string,\n * MOUSEMOVE:string,\n * MOUSEOVER:string,\n * MOUSEOUT:string,\n * MOUSEENTER:string,\n * MOUSELEAVE: string,\n * }}\n */\ngoog.events.MouseEvents;\n\n\n/**\n * An alias for `goog.events.EventType.MOUSE*` event types that is overridden by\n * corresponding `POINTER*` event types.\n * @const {!goog.events.MouseEvents}\n */\ngoog.events.PointerAsMouseEventType = {\n MOUSEDOWN: goog.events.PointerFallbackEventType.POINTERDOWN,\n MOUSEUP: goog.events.PointerFallbackEventType.POINTERUP,\n MOUSECANCEL: goog.events.PointerFallbackEventType.POINTERCANCEL,\n MOUSEMOVE: goog.events.PointerFallbackEventType.POINTERMOVE,\n MOUSEOVER: goog.events.PointerFallbackEventType.POINTEROVER,\n MOUSEOUT: goog.events.PointerFallbackEventType.POINTEROUT,\n MOUSEENTER: goog.events.PointerFallbackEventType.POINTERENTER,\n MOUSELEAVE: goog.events.PointerFallbackEventType.POINTERLEAVE\n};\n\n\n/**\n * An alias for `goog.events.EventType.MOUSE*` event types that continue to use\n * mouse events.\n * @const {!goog.events.MouseEvents}\n */\ngoog.events.MouseAsMouseEventType = {\n MOUSEDOWN: goog.events.EventType.MOUSEDOWN,\n MOUSEUP: goog.events.EventType.MOUSEUP,\n MOUSECANCEL: goog.events.EventType.MOUSECANCEL,\n MOUSEMOVE: goog.events.EventType.MOUSEMOVE,\n MOUSEOVER: goog.events.EventType.MOUSEOVER,\n MOUSEOUT: goog.events.EventType.MOUSEOUT,\n MOUSEENTER: goog.events.EventType.MOUSEENTER,\n MOUSELEAVE: goog.events.EventType.MOUSELEAVE\n};\n\n\n/**\n * An alias for `goog.events.EventType.TOUCH*` event types that is overridden by\n * corresponding `POINTER*` event types.\n * @enum {string}\n */\ngoog.events.PointerAsTouchEventType = {\n TOUCHCANCEL: goog.events.PointerTouchFallbackEventType.POINTERCANCEL,\n TOUCHEND: goog.events.PointerTouchFallbackEventType.POINTERUP,\n TOUCHMOVE: goog.events.PointerTouchFallbackEventType.POINTERMOVE,\n TOUCHSTART: goog.events.PointerTouchFallbackEventType.POINTERDOWN\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface for a listenable JavaScript object.\n */\n\ngoog.provide('goog.events.Listenable');\ngoog.provide('goog.events.ListenableKey');\n\ngoog.forwardDeclare('goog.events.EventLike');\ngoog.forwardDeclare('goog.events.EventTarget');\n/** @suppress {extraRequire} */\ngoog.require('goog.events.EventId');\n\n\n\n/**\n * A listenable interface. A listenable is an object with the ability\n * to dispatch/broadcast events to \"event listeners\" registered via\n * listen/listenOnce.\n *\n * The interface allows for an event propagation mechanism similar\n * to one offered by native browser event targets, such as\n * capture/bubble mechanism, stopping propagation, and preventing\n * default actions. Capture/bubble mechanism depends on the ancestor\n * tree constructed via `#getParentEventTarget`; this tree\n * must be directed acyclic graph. The meaning of default action(s)\n * in preventDefault is specific to a particular use case.\n *\n * Implementations that do not support capture/bubble or can not have\n * a parent listenable can simply not implement any ability to set the\n * parent listenable (and have `#getParentEventTarget` return\n * null).\n *\n * Implementation of this class can be used with or independently from\n * goog.events.\n *\n * Implementation must call `#addImplementation(implClass)`.\n *\n * @interface\n * @see goog.events\n * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html\n */\ngoog.events.Listenable = function() {};\n\n\n/**\n * An expando property to indicate that an object implements\n * goog.events.Listenable.\n *\n * See addImplementation/isImplementedBy.\n *\n * @type {string}\n * @const\n */\ngoog.events.Listenable.IMPLEMENTED_BY_PROP =\n 'closure_listenable_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * Marks a given class (constructor) as an implementation of\n * Listenable, so that we can query that fact at runtime. The class\n * must have already implemented the interface.\n * @param {function(new:goog.events.Listenable,...)} cls The class constructor.\n * The corresponding class must have already implemented the interface.\n */\ngoog.events.Listenable.addImplementation = function(cls) {\n cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;\n};\n\n\n/**\n * @param {Object} obj The object to check.\n * @return {boolean} Whether a given instance implements Listenable. The\n * class/superclass of the instance must call addImplementation.\n */\ngoog.events.Listenable.isImplementedBy = function(obj) {\n return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listen;\n\n\n/**\n * Adds an event listener that is removed automatically after the\n * listener fired once.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listenOnce;\n\n\n/**\n * Removes an event listener which was added with listen() or listenOnce().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.unlisten;\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.Listenable.prototype.unlistenByKey;\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n */\ngoog.events.Listenable.prototype.dispatchEvent;\n\n\n/**\n * Removes all listeners from this listenable. If type is specified,\n * it will only remove listeners of the particular type. otherwise all\n * registered listeners will be removed.\n *\n * @param {string=} opt_type Type of event to remove, default is to\n * remove all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.Listenable.prototype.removeAllListeners;\n\n\n/**\n * Returns the parent of this event target to use for capture/bubble\n * mechanism.\n *\n * NOTE(chrishenry): The name reflects the original implementation of\n * custom event target (`goog.events.EventTarget`). We decided\n * that changing the name is not worth it.\n *\n * @return {goog.events.Listenable} The parent EventTarget or null if\n * there is no parent.\n */\ngoog.events.Listenable.prototype.getParentEventTarget;\n\n\n/**\n * Fires all registered listeners in this listenable for the given\n * type and capture mode, passing them the given eventObject. This\n * does not perform actual capture/bubble. Only implementors of the\n * interface should be using this.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.fireListeners;\n\n\n/**\n * Gets all listeners in this listenable for the given type and\n * capture mode.\n *\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListeners;\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListener;\n\n\n/**\n * Whether there is any active listeners matching the specified\n * signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.hasListener;\n\n\n\n/**\n * An interface that describes a single registered listener.\n * @interface\n */\ngoog.events.ListenableKey = function() {};\n\n\n/**\n * Counter used to create a unique key\n * @type {number}\n * @private\n */\ngoog.events.ListenableKey.counter_ = 0;\n\n\n/**\n * Reserves a key to be used for ListenableKey#key field.\n * @return {number} A number to be used to fill ListenableKey#key\n * field.\n */\ngoog.events.ListenableKey.reserveKey = function() {\n return ++goog.events.ListenableKey.counter_;\n};\n\n\n/**\n * The source event target.\n * @type {Object|goog.events.Listenable|goog.events.EventTarget}\n */\ngoog.events.ListenableKey.prototype.src;\n\n\n/**\n * The event type the listener is listening to.\n * @type {string}\n */\ngoog.events.ListenableKey.prototype.type;\n\n\n/**\n * The listener function.\n * @type {function(?):?|{handleEvent:function(?):?}|null}\n */\ngoog.events.ListenableKey.prototype.listener;\n\n\n/**\n * Whether the listener works on capture phase.\n * @type {boolean}\n */\ngoog.events.ListenableKey.prototype.capture;\n\n\n/**\n * The 'this' object for the listener function's scope.\n * @type {Object|undefined}\n */\ngoog.events.ListenableKey.prototype.handler;\n\n\n/**\n * A globally unique number to identify the key.\n * @type {number}\n */\ngoog.events.ListenableKey.prototype.key;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Listener object.\n * @see ../demos/events.html\n */\n\ngoog.provide('goog.events.Listener');\n\ngoog.require('goog.events.ListenableKey');\n\n\n\n/**\n * Simple class that stores information about a listener\n * @param {function(?):?} listener Callback function.\n * @param {Function} proxy Wrapper for the listener that patches the event.\n * @param {EventTarget|goog.events.Listenable} src Source object for\n * the event.\n * @param {string} type Event type.\n * @param {boolean} capture Whether in capture or bubble phase.\n * @param {Object=} opt_handler Object in whose context to execute the callback.\n * @implements {goog.events.ListenableKey}\n * @constructor\n */\ngoog.events.Listener = function(\n listener, proxy, src, type, capture, opt_handler) {\n if (goog.events.Listener.ENABLE_MONITORING) {\n this.creationStack = new Error().stack;\n }\n\n /** @override */\n this.listener = listener;\n\n /**\n * A wrapper over the original listener. This is used solely to\n * handle native browser events (it is used to simulate the capture\n * phase and to patch the event object).\n * @type {Function}\n */\n this.proxy = proxy;\n\n /**\n * Object or node that callback is listening to\n * @type {EventTarget|goog.events.Listenable}\n */\n this.src = src;\n\n /**\n * The event type.\n * @const {string}\n */\n this.type = type;\n\n /**\n * Whether the listener is being called in the capture or bubble phase\n * @const {boolean}\n */\n this.capture = !!capture;\n\n /**\n * Optional object whose context to execute the listener in\n * @type {Object|undefined}\n */\n this.handler = opt_handler;\n\n /**\n * The key of the listener.\n * @const {number}\n * @override\n */\n this.key = goog.events.ListenableKey.reserveKey();\n\n /**\n * Whether to remove the listener after it has been called.\n * @type {boolean}\n */\n this.callOnce = false;\n\n /**\n * Whether the listener has been removed.\n * @type {boolean}\n */\n this.removed = false;\n};\n\n\n/**\n * @define {boolean} Whether to enable the monitoring of the\n * goog.events.Listener instances. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.events.Listener.ENABLE_MONITORING =\n goog.define('goog.events.Listener.ENABLE_MONITORING', false);\n\n\n/**\n * If monitoring the goog.events.Listener instances is enabled, stores the\n * creation stack trace of the Disposable instance.\n * @type {string}\n */\ngoog.events.Listener.prototype.creationStack;\n\n\n/**\n * Marks this listener as removed. This also remove references held by\n * this listener object (such as listener and event source).\n */\ngoog.events.Listener.prototype.markAsRemoved = function() {\n this.removed = true;\n this.listener = null;\n this.proxy = null;\n this.src = null;\n this.handler = null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A map of listeners that provides utility functions to\n * deal with listeners on an event target. Used by\n * `goog.events.EventTarget`.\n *\n * WARNING: Do not use this class from outside goog.events package.\n *\n */\n\ngoog.provide('goog.events.ListenerMap');\n\ngoog.require('goog.array');\ngoog.require('goog.events.Listener');\ngoog.require('goog.object');\n\n\n\n/**\n * Creates a new listener map.\n * @param {EventTarget|goog.events.Listenable} src The src object.\n * @constructor\n * @final\n */\ngoog.events.ListenerMap = function(src) {\n /** @type {EventTarget|goog.events.Listenable} */\n this.src = src;\n\n /**\n * Maps of event type to an array of listeners.\n * @type {!Object<string, !Array<!goog.events.Listener>>}\n */\n this.listeners = {};\n\n /**\n * The count of types in this map that have registered listeners.\n * @private {number}\n */\n this.typeCount_ = 0;\n};\n\n\n/**\n * @return {number} The count of event types in this map that actually\n * have registered listeners.\n */\ngoog.events.ListenerMap.prototype.getTypeCount = function() {\n return this.typeCount_;\n};\n\n\n/**\n * @return {number} Total number of registered listeners.\n */\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\n var count = 0;\n for (var type in this.listeners) {\n count += this.listeners[type].length;\n }\n return count;\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n */\ngoog.events.ListenerMap.prototype.add = function(\n type, listener, callOnce, opt_useCapture, opt_listenerScope) {\n var typeStr = type.toString();\n var listenerArray = this.listeners[typeStr];\n if (!listenerArray) {\n listenerArray = this.listeners[typeStr] = [];\n this.typeCount_++;\n }\n\n var listenerObj;\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n listenerObj = listenerArray[index];\n if (!callOnce) {\n // Ensure that, if there is an existing callOnce listener, it is no\n // longer a callOnce listener.\n listenerObj.callOnce = false;\n }\n } else {\n listenerObj = new goog.events.Listener(\n listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);\n listenerObj.callOnce = callOnce;\n listenerArray.push(listenerObj);\n }\n return listenerObj;\n};\n\n\n/**\n * Removes a matching listener.\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.ListenerMap.prototype.remove = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n var typeStr = type.toString();\n if (!(typeStr in this.listeners)) {\n return false;\n }\n\n var listenerArray = this.listeners[typeStr];\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n var listenerObj = listenerArray[index];\n listenerObj.markAsRemoved();\n goog.array.removeAt(listenerArray, index);\n if (listenerArray.length == 0) {\n delete this.listeners[typeStr];\n this.typeCount_--;\n }\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes the given listener object.\n * @param {!goog.events.ListenableKey} listener The listener to remove.\n * @return {boolean} Whether the listener is removed.\n */\ngoog.events.ListenerMap.prototype.removeByKey = function(listener) {\n var type = listener.type;\n if (!(type in this.listeners)) {\n return false;\n }\n\n var removed = goog.array.remove(this.listeners[type], listener);\n if (removed) {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n if (this.listeners[type].length == 0) {\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return removed;\n};\n\n\n/**\n * Removes all listeners from this map. If opt_type is provided, only\n * listeners that match the given type are removed.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * @return {number} Number of listeners removed.\n */\ngoog.events.ListenerMap.prototype.removeAll = function(opt_type) {\n var typeStr = opt_type && opt_type.toString();\n var count = 0;\n for (var type in this.listeners) {\n if (!typeStr || type == typeStr) {\n var listenerArray = this.listeners[type];\n for (var i = 0; i < listenerArray.length; i++) {\n ++count;\n listenerArray[i].markAsRemoved();\n }\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return count;\n};\n\n\n/**\n * Gets all listeners that match the given type and capture mode. The\n * returned array is a copy (but the listener objects are not).\n * @param {string|!goog.events.EventId} type The type of the listeners\n * to retrieve.\n * @param {boolean} capture The capture mode of the listeners to retrieve.\n * @return {!Array<!goog.events.ListenableKey>} An array of matching\n * listeners.\n */\ngoog.events.ListenerMap.prototype.getListeners = function(type, capture) {\n var listenerArray = this.listeners[type.toString()];\n var rv = [];\n if (listenerArray) {\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (listenerObj.capture == capture) {\n rv.push(listenerObj);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId} type The type of the listener\n * to retrieve.\n * @param {!Function} listener The listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n */\ngoog.events.ListenerMap.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n var listenerArray = this.listeners[type.toString()];\n var i = -1;\n if (listenerArray) {\n i = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, capture, opt_listenerScope);\n }\n return i > -1 ? listenerArray[i] : null;\n};\n\n\n/**\n * Whether there is a matching listener. If either the type or capture\n * parameters are unspecified, the function will match on the\n * remaining criteria.\n *\n * @param {string|!goog.events.EventId=} opt_type The type of the listener.\n * @param {boolean=} opt_capture The capture mode of the listener.\n * @return {boolean} Whether there is an active listener matching\n * the requested type and/or capture phase.\n */\ngoog.events.ListenerMap.prototype.hasListener = function(\n opt_type, opt_capture) {\n var hasType = (opt_type !== undefined);\n var typeStr = hasType ? opt_type.toString() : '';\n var hasCapture = (opt_capture !== undefined);\n\n return goog.object.some(this.listeners, function(listenerArray, type) {\n for (var i = 0; i < listenerArray.length; ++i) {\n if ((!hasType || listenerArray[i].type == typeStr) &&\n (!hasCapture || listenerArray[i].capture == opt_capture)) {\n return true;\n }\n }\n\n return false;\n });\n};\n\n\n/**\n * Finds the index of a matching goog.events.Listener in the given\n * listenerArray.\n * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.\n * @param {!Function} listener The listener function.\n * @param {boolean=} opt_useCapture The capture flag for the listener.\n * @param {Object=} opt_listenerScope The listener scope.\n * @return {number} The index of the matching listener within the\n * listenerArray.\n * @private\n */\ngoog.events.ListenerMap.findListenerIndex_ = function(\n listenerArray, listener, opt_useCapture, opt_listenerScope) {\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (!listenerObj.removed && listenerObj.listener == listener &&\n listenerObj.capture == !!opt_useCapture &&\n listenerObj.handler == opt_listenerScope) {\n return i;\n }\n }\n return -1;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An event manager for both native browser event\n * targets and custom JavaScript event targets\n * (`goog.events.Listenable`). This provides an abstraction\n * over browsers' event systems.\n *\n * It also provides a simulation of W3C event model's capture phase in\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\n * interact well with listeners registered directly on the elements\n * (bypassing goog.events) or even with listeners registered via\n * goog.events in a separate JS binary. In these cases, we provide\n * no ordering guarantees.\n *\n * The listeners will receive a \"patched\" event object. Such event object\n * contains normalized values for certain event properties that differs in\n * different browsers.\n *\n * Example usage:\n * <pre>\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\n * goog.events.removeAll(myNode);\n * </pre>\n *\n * in IE and event object patching]\n *\n * @see ../demos/events.html\n * @see ../demos/event-propagation.html\n * @see ../demos/stopevent.html\n */\n\n// IMPLEMENTATION NOTES:\n// goog.events stores an auxiliary data structure on each EventTarget\n// source being listened on. This allows us to take advantage of GC,\n// having the data structure GC'd when the EventTarget is GC'd. This\n// GC behavior is equivalent to using W3C DOM Events directly.\n\ngoog.provide('goog.events');\ngoog.provide('goog.events.CaptureSimulationMode');\ngoog.provide('goog.events.Key');\ngoog.provide('goog.events.ListenableType');\n\ngoog.forwardDeclare('goog.debug.ErrorHandler');\ngoog.forwardDeclare('goog.events.EventWrapper');\ngoog.require('goog.asserts');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.BrowserEvent');\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\n\n\n/**\n * @typedef {number|goog.events.ListenableKey}\n */\ngoog.events.Key;\n\n\n/**\n * @typedef {EventTarget|goog.events.Listenable}\n */\ngoog.events.ListenableType;\n\n\n/**\n * Property name on a native event target for the listener map\n * associated with the event target.\n * @private @const {string}\n */\ngoog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * String used to prepend to IE event types.\n * @const\n * @private\n */\ngoog.events.onString_ = 'on';\n\n\n/**\n * Map of computed \"on<eventname>\" strings for IE event types. Caching\n * this removes an extra object allocation in goog.events.listen which\n * improves IE6 performance.\n * @const\n * @dict\n * @private\n */\ngoog.events.onStringMap_ = {};\n\n\n/**\n * @enum {number} Different capture simulation mode for IE8-.\n */\ngoog.events.CaptureSimulationMode = {\n /**\n * Does not perform capture simulation. Will asserts in IE8- when you\n * add capture listeners.\n */\n OFF_AND_FAIL: 0,\n\n /**\n * Does not perform capture simulation, silently ignore capture\n * listeners.\n */\n OFF_AND_SILENT: 1,\n\n /**\n * Performs capture simulation.\n */\n ON: 2\n};\n\n\n/**\n * @define {number} The capture simulation mode for IE8-. By default,\n * this is ON.\n */\ngoog.events.CAPTURE_SIMULATION_MODE =\n goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);\n\n\n/**\n * Estimated count of total native listeners.\n * @private {number}\n */\ngoog.events.listenerCountEstimate_ = 0;\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. A listener can only be added once\n * to an object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method, or an object with a handleEvent function.\n * WARNING: passing an Object is now softly deprecated.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n */\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\n if (opt_options && opt_options.once) {\n return goog.events.listenOnce(\n src, type, listener, opt_options, opt_handler);\n }\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listen(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ false, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target. A listener can only be added once to an object and if it\n * is added again the key for the listener is returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {EventTarget} src The node to listen to events on.\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\n * @param {!Function} listener Callback function.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener or otherwise.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} Unique key for the listener.\n * @template EVENTOBJ\n * @private\n */\ngoog.events.listen_ = function(\n src, type, listener, callOnce, opt_options, opt_handler) {\n if (!type) {\n throw new Error('Invalid event type');\n }\n\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n if (capture && !goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {\n if (goog.events.CAPTURE_SIMULATION_MODE ==\n goog.events.CaptureSimulationMode.OFF_AND_FAIL) {\n goog.asserts.fail('Can not register capture listener in IE8-.');\n return null;\n } else if (\n goog.events.CAPTURE_SIMULATION_MODE ==\n goog.events.CaptureSimulationMode.OFF_AND_SILENT) {\n return null;\n }\n }\n\n var listenerMap = goog.events.getListenerMap_(src);\n if (!listenerMap) {\n src[goog.events.LISTENER_MAP_PROP_] = listenerMap =\n new goog.events.ListenerMap(src);\n }\n\n var listenerObj = /** @type {goog.events.Listener} */ (\n listenerMap.add(type, listener, callOnce, capture, opt_handler));\n\n // If the listenerObj already has a proxy, it has been set up\n // previously. We simply return.\n if (listenerObj.proxy) {\n return listenerObj;\n }\n\n var proxy = goog.events.getProxy();\n listenerObj.proxy = proxy;\n\n proxy.src = src;\n proxy.listener = listenerObj;\n\n // Attach the proxy through the browser's API\n if (src.addEventListener) {\n // Don't pass an object as `capture` if the browser doesn't support that.\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\n opt_options = capture;\n }\n // Don't break tests that expect a boolean.\n if (opt_options === undefined) opt_options = false;\n src.addEventListener(type.toString(), proxy, opt_options);\n } else if (src.attachEvent) {\n // The else if above used to be an unconditional else. It would call\n // attachEvent come gws or high water. This would sometimes throw an\n // exception on IE11, spoiling the day of some callers. The previous\n // incarnation of this code, from 2007, indicates that it replaced an\n // earlier still version that caused excess allocations on IE6.\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\n } else if (src.addListener && src.removeListener) {\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\n // Safari, there is no global for the MediaQueryList constructor, so we just\n // check whether the object \"looks like\" MediaQueryList.\n goog.asserts.assert(\n type === 'change', 'MediaQueryList only has a change event');\n src.addListener(proxy);\n } else {\n throw new Error('addEventListener and attachEvent are unavailable.');\n }\n\n goog.events.listenerCountEstimate_++;\n return listenerObj;\n};\n\n\n/**\n * Helper function for returning a proxy function.\n * @return {!Function} A new or reused function object.\n */\ngoog.events.getProxy = function() {\n var proxyCallbackFunction = goog.events.handleBrowserEvent_;\n // Use a local var f to prevent one allocation.\n var f =\n goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT ? function(eventObject) {\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\n } : function(eventObject) {\n var v = proxyCallbackFunction.call(f.src, f.listener, eventObject);\n // NOTE(chrishenry): In IE, we hack in a capture phase. However, if\n // there is inline event handler which tries to prevent default (for\n // example <a href=\"...\" onclick=\"return false\">...</a>) in a\n // descendant element, the prevent default will be overridden\n // by this listener if this listener were to return true. Hence, we\n // return undefined.\n if (!v) return v;\n };\n return f;\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. After the event has fired the event\n * listener is removed from the target.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n */\ngoog.events.listenOnce = function(\n src, type, listener, opt_options, opt_handler) {\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listenOnce(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ true, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.Listenable}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.Listenable} src The target to\n * listen to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @template T\n */\ngoog.events.listenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n wrapper.listen(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes an event listener which was added with listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {?boolean} indicating whether the listener was there to remove.\n * @template EVENTOBJ\n */\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.unlisten(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return false;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n var listenerObj = listenerMap.getListener(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n if (listenerObj) {\n return goog.events.unlistenByKey(listenerObj);\n }\n }\n\n return false;\n};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {goog.events.Key} key The key returned by listen() for this\n * event listener.\n * @return {boolean} indicating whether the listener was there to remove.\n */\ngoog.events.unlistenByKey = function(key) {\n // TODO(chrishenry): Remove this check when tests that rely on this\n // are fixed.\n if (typeof key === 'number') {\n return false;\n }\n\n var listener = key;\n if (!listener || listener.removed) {\n return false;\n }\n\n var src = listener.src;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\n }\n\n var type = listener.type;\n var proxy = listener.proxy;\n if (src.removeEventListener) {\n src.removeEventListener(type, proxy, listener.capture);\n } else if (src.detachEvent) {\n src.detachEvent(goog.events.getOnString_(type), proxy);\n } else if (src.addListener && src.removeListener) {\n src.removeListener(proxy);\n }\n goog.events.listenerCountEstimate_--;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n // TODO(chrishenry): Try to remove this conditional and execute the\n // first branch always. This should be safe.\n if (listenerMap) {\n listenerMap.removeByKey(listener);\n if (listenerMap.getTypeCount() == 0) {\n // Null the src, just because this is simple to do (and useful\n // for IE <= 7).\n listenerMap.src = null;\n // We don't use delete here because IE does not allow delete\n // on a window object.\n src[goog.events.LISTENER_MAP_PROP_] = null;\n }\n } else {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n }\n\n return true;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n */\ngoog.events.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n wrapper.unlisten(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes all listeners from an object. You can also optionally\n * remove listeners of a particular type.\n *\n * @param {Object|undefined} obj Object to remove listeners from. Must be an\n * EventTarget or a goog.events.Listenable.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * Default is all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.removeAll = function(obj, opt_type) {\n // TODO(chrishenry): Change the type of obj to\n // (!EventTarget|!goog.events.Listenable).\n\n if (!obj) {\n return 0;\n }\n\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {?} */ (obj).removeAllListeners(opt_type);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n if (!listenerMap) {\n return 0;\n }\n\n var count = 0;\n var typeStr = opt_type && opt_type.toString();\n for (var type in listenerMap.listeners) {\n if (!typeStr || type == typeStr) {\n // Clone so that we don't need to worry about unlistenByKey\n // changing the content of the ListenerMap.\n var listeners = listenerMap.listeners[type].concat();\n for (var i = 0; i < listeners.length; ++i) {\n if (goog.events.unlistenByKey(listeners[i])) {\n ++count;\n }\n }\n }\n }\n return count;\n};\n\n\n/**\n * Gets the listeners for a given object, type and capture phase.\n *\n * @param {Object} obj Object to get listeners for.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Capture phase?.\n * @return {Array<!goog.events.Listener>} Array of listener objects.\n */\ngoog.events.getListeners = function(obj, type, capture) {\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).getListeners(\n type, capture);\n } else {\n if (!obj) {\n // TODO(chrishenry): We should tighten the API to accept\n // !EventTarget|goog.events.Listenable, and add an assertion here.\n return [];\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return listenerMap ? listenerMap.getListeners(type, capture) : [];\n }\n};\n\n\n/**\n * Gets the goog.events.Listener for the event or null if no such listener is\n * in use.\n *\n * @param {EventTarget|goog.events.Listenable} src The target from\n * which to get listeners.\n * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The\n * listener function to get.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the\n * capture or bubble phase of the event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n * @template EVENTOBJ\n */\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\n // TODO(chrishenry): Change type from ?string to string, or add assertion.\n type = /** @type {string} */ (type);\n listener = goog.events.wrapListener(listener);\n var capture = !!opt_capt;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.getListener(type, listener, capture, opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return null;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n return listenerMap.getListener(type, listener, capture, opt_handler);\n }\n return null;\n};\n\n\n/**\n * Returns whether an event target has any active listeners matching the\n * specified signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {EventTarget|goog.events.Listenable} obj Target to get\n * listeners for.\n * @param {string|!goog.events.EventId=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble-phase\n * listeners.\n * @return {boolean} Whether an event target has one or more listeners matching\n * the requested type and/or capture phase.\n */\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return obj.hasListener(opt_type, opt_capture);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);\n};\n\n\n/**\n * Provides a nice string showing the normalized event objects public members\n * @param {Object} e Event Object.\n * @return {string} String of the public members of the normalized event object.\n */\ngoog.events.expose = function(e) {\n var str = [];\n for (var key in e) {\n if (e[key] && e[key].id) {\n str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');\n } else {\n str.push(key + ' = ' + e[key]);\n }\n }\n return str.join('\\n');\n};\n\n\n/**\n * Returns a string with on prepended to the specified type. This is used for IE\n * which expects \"on\" to be prepended. This function caches the string in order\n * to avoid extra allocations in steady state.\n * @param {string} type Event type.\n * @return {string} The type string with 'on' prepended.\n * @private\n */\ngoog.events.getOnString_ = function(type) {\n if (type in goog.events.onStringMap_) {\n return goog.events.onStringMap_[type];\n }\n return goog.events.onStringMap_[type] = goog.events.onString_ + type;\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase\n *\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n */\ngoog.events.fireListeners = function(obj, type, capture, eventObject) {\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).fireListeners(\n type, capture, eventObject);\n }\n\n return goog.events.fireListeners_(obj, type, capture, eventObject);\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase.\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n * @private\n */\ngoog.events.fireListeners_ = function(obj, type, capture, eventObject) {\n /** @type {boolean} */\n var retval = true;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {EventTarget} */ (obj));\n if (listenerMap) {\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // listenerMap.getListeners(type, capture) instead, which is simpler.\n var listenerArray = listenerMap.listeners[type.toString()];\n if (listenerArray) {\n listenerArray = listenerArray.concat();\n for (var i = 0; i < listenerArray.length; i++) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && listener.capture == capture && !listener.removed) {\n var result = goog.events.fireListener(listener, eventObject);\n retval = retval && (result !== false);\n }\n }\n }\n }\n return retval;\n};\n\n\n/**\n * Fires a listener with a set of arguments\n *\n * @param {goog.events.Listener} listener The listener object to call.\n * @param {Object} eventObject The event object to pass to the listener.\n * @return {*} Result of listener.\n */\ngoog.events.fireListener = function(listener, eventObject) {\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n goog.events.unlistenByKey(listener);\n }\n return listenerFn.call(listenerHandler, eventObject);\n};\n\n\n/**\n * Gets the total number of listeners currently in the system.\n * @return {number} Number of listeners.\n * @deprecated This returns estimated count, now that Closure no longer\n * stores a central listener registry. We still return an estimation\n * to keep existing listener-related tests passing. In the near future,\n * this function will be removed.\n */\ngoog.events.getTotalListenerCount = function() {\n return goog.events.listenerCountEstimate_;\n};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {goog.events.Listenable} src The event target.\n * @param {goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the handlers returns false) this will also return false.\n * If there are no handlers, or if all handlers return true, this returns\n * true.\n */\ngoog.events.dispatchEvent = function(src, e) {\n goog.asserts.assert(\n goog.events.Listenable.isImplementedBy(src),\n 'Can not use goog.events.dispatchEvent with ' +\n 'non-goog.events.Listenable instance.');\n return src.dispatchEvent(e);\n};\n\n\n/**\n * Installs exception protection for the browser event entry point using the\n * given error handler.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point.\n */\ngoog.events.protectBrowserEventEntryPoint = function(errorHandler) {\n goog.events.handleBrowserEvent_ =\n errorHandler.protectEntryPoint(goog.events.handleBrowserEvent_);\n};\n\n\n/**\n * Handles an event and dispatches it to the correct listeners. This\n * function is a proxy for the real listener the user specified.\n *\n * @param {goog.events.Listener} listener The listener object.\n * @param {Event=} opt_evt Optional event object that gets passed in via the\n * native event handlers.\n * @return {*} Result of the event handler.\n * @this {EventTarget} The object or Element that fired the event.\n * @private\n */\ngoog.events.handleBrowserEvent_ = function(listener, opt_evt) {\n if (listener.removed) {\n return true;\n }\n\n // Synthesize event propagation if the browser does not support W3C\n // event model.\n if (!goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {\n var ieEvent = opt_evt ||\n /** @type {Event} */ (goog.getObjectByName('window.event'));\n var evt = new goog.events.BrowserEvent(ieEvent, this);\n /** @type {*} */\n var retval = true;\n\n if (goog.events.CAPTURE_SIMULATION_MODE ==\n goog.events.CaptureSimulationMode.ON) {\n // If we have not marked this event yet, we should perform capture\n // simulation.\n if (!goog.events.isMarkedIeEvent_(ieEvent)) {\n goog.events.markIeEvent_(ieEvent);\n\n var ancestors = [];\n for (var parent = evt.currentTarget; parent;\n parent = parent.parentNode) {\n ancestors.push(parent);\n }\n\n // Fire capture listeners.\n var type = listener.type;\n for (var i = ancestors.length - 1;\n !evt.hasPropagationStopped() && i >= 0; i--) {\n evt.currentTarget = ancestors[i];\n var result =\n goog.events.fireListeners_(ancestors[i], type, true, evt);\n retval = retval && result;\n }\n\n // Fire bubble listeners.\n //\n // We can technically rely on IE to perform bubble event\n // propagation. However, it turns out that IE fires events in\n // opposite order of attachEvent registration, which broke\n // some code and tests that rely on the order. (While W3C DOM\n // Level 2 Events TR leaves the event ordering unspecified,\n // modern browsers and W3C DOM Level 3 Events Working Draft\n // actually specify the order as the registration order.)\n for (var i = 0; !evt.hasPropagationStopped() && i < ancestors.length;\n i++) {\n evt.currentTarget = ancestors[i];\n var result =\n goog.events.fireListeners_(ancestors[i], type, false, evt);\n retval = retval && result;\n }\n }\n } else {\n retval = goog.events.fireListener(listener, evt);\n }\n return retval;\n }\n\n // Otherwise, simply fire the listener.\n return goog.events.fireListener(\n listener, new goog.events.BrowserEvent(opt_evt, this));\n};\n\n\n/**\n * This is used to mark the IE event object so we do not do the Closure pass\n * twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @private\n */\ngoog.events.markIeEvent_ = function(e) {\n // Only the keyCode and the returnValue can be changed. We use keyCode for\n // non keyboard events.\n // event.returnValue is a bit more tricky. It is undefined by default. A\n // boolean false prevents the default action. In a window.onbeforeunload and\n // the returnValue is non undefined it will be alerted. However, we will only\n // modify the returnValue for keyboard events. We can get a problem if non\n // closure events sets the keyCode or the returnValue\n\n var useReturnValue = false;\n\n if (e.keyCode == 0) {\n // We cannot change the keyCode in case that srcElement is input[type=file].\n // We could test that that is the case but that would allocate 3 objects.\n // If we use try/catch we will only allocate extra objects in the case of a\n // failure.\n\n try {\n e.keyCode = -1;\n return;\n } catch (ex) {\n useReturnValue = true;\n }\n }\n\n if (useReturnValue ||\n /** @type {boolean|undefined} */ (e.returnValue) == undefined) {\n e.returnValue = true;\n }\n};\n\n\n/**\n * This is used to check if an IE event has already been handled by the Closure\n * system so we do not do the Closure pass twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @return {boolean} True if the event object has been marked.\n * @private\n */\ngoog.events.isMarkedIeEvent_ = function(e) {\n return e.keyCode < 0 || e.returnValue != undefined;\n};\n\n\n/**\n * Counter to create unique event ids.\n * @private {number}\n */\ngoog.events.uniqueIdCounter_ = 0;\n\n\n/**\n * Creates a unique event id.\n *\n * @param {string} identifier The identifier.\n * @return {string} A unique identifier.\n * @idGenerator {unique}\n */\ngoog.events.getUniqueId = function(identifier) {\n return identifier + '_' + goog.events.uniqueIdCounter_++;\n};\n\n\n/**\n * @param {EventTarget} src The source object.\n * @return {goog.events.ListenerMap} A listener map for the given\n * source object, or null if none exists.\n * @private\n */\ngoog.events.getListenerMap_ = function(src) {\n var listenerMap = src[goog.events.LISTENER_MAP_PROP_];\n // IE serializes the property as well (e.g. when serializing outer\n // HTML). So we must check that the value is of the correct type.\n return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;\n};\n\n\n/**\n * Expando property for listener function wrapper for Object with\n * handleEvent.\n * @private @const {string}\n */\ngoog.events.LISTENER_WRAPPER_PROP_ =\n '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * @param {Object|Function} listener The listener function or an\n * object that contains handleEvent method.\n * @return {!Function} Either the original function or a function that\n * calls obj.handleEvent. If the same listener is passed to this\n * function more than once, the same function is guaranteed to be\n * returned.\n */\ngoog.events.wrapListener = function(listener) {\n goog.asserts.assert(listener, 'Listener can not be null.');\n\n if (goog.isFunction(listener)) {\n return listener;\n }\n\n goog.asserts.assert(\n listener.handleEvent, 'An object listener must have handleEvent method.');\n if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {\n listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) {\n return /** @type {?} */ (listener).handleEvent(e);\n };\n }\n return listener[goog.events.LISTENER_WRAPPER_PROP_];\n};\n\n\n// Register the browser event handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n goog.events.handleBrowserEvent_ =\n transformer(goog.events.handleBrowserEvent_);\n });\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A disposable implementation of a custom\n * listenable/event target. See also: documentation for\n * `goog.events.Listenable`.\n *\n * @see ../demos/eventtarget.html\n * @see goog.events.Listenable\n */\n\ngoog.provide('goog.events.EventTarget');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.asserts');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.require('goog.object');\n\n\n\n/**\n * An implementation of `goog.events.Listenable` with full W3C\n * EventTarget-like support (capture/bubble mechanism, stopping event\n * propagation, preventing default actions).\n *\n * You may subclass this class to turn your class into a Listenable.\n *\n * Unless propagation is stopped, an event dispatched by an\n * EventTarget will bubble to the parent returned by\n * `getParentEventTarget`. To set the parent, call\n * `setParentEventTarget`. Subclasses that don't support\n * changing the parent can override the setter to throw an error.\n *\n * Example usage:\n * <pre>\n * var source = new goog.events.EventTarget();\n * function handleEvent(e) {\n * alert('Type: ' + e.type + '; Target: ' + e.target);\n * }\n * source.listen('foo', handleEvent);\n * // Or: goog.events.listen(source, 'foo', handleEvent);\n * ...\n * source.dispatchEvent('foo'); // will call handleEvent\n * ...\n * source.unlisten('foo', handleEvent);\n * // Or: goog.events.unlisten(source, 'foo', handleEvent);\n * </pre>\n *\n * @constructor\n * @extends {goog.Disposable}\n * @implements {goog.events.Listenable}\n */\ngoog.events.EventTarget = function() {\n goog.Disposable.call(this);\n\n /**\n * Maps of event type to an array of listeners.\n * @private {!goog.events.ListenerMap}\n */\n this.eventTargetListeners_ = new goog.events.ListenerMap(this);\n\n /**\n * The object to use for event.target. Useful when mixing in an\n * EventTarget to another object.\n * @private {!Object}\n */\n this.actualEventTarget_ = this;\n\n /**\n * Parent event target, used during event bubbling.\n *\n * TODO(chrishenry): Change this to goog.events.Listenable. This\n * currently breaks people who expect getParentEventTarget to return\n * goog.events.EventTarget.\n *\n * @private {?goog.events.EventTarget}\n */\n this.parentEventTarget_ = null;\n};\ngoog.inherits(goog.events.EventTarget, goog.Disposable);\ngoog.events.Listenable.addImplementation(goog.events.EventTarget);\n\n\n/**\n * An artificial cap on the number of ancestors you can have. This is mainly\n * for loop detection.\n * @const {number}\n * @private\n */\ngoog.events.EventTarget.MAX_ANCESTORS_ = 1000;\n\n\n/**\n * Returns the parent of this event target to use for bubbling.\n *\n * @return {goog.events.EventTarget} The parent EventTarget or null if\n * there is no parent.\n * @override\n */\ngoog.events.EventTarget.prototype.getParentEventTarget = function() {\n return this.parentEventTarget_;\n};\n\n\n/**\n * Sets the parent of this event target to use for capture/bubble\n * mechanism.\n * @param {goog.events.EventTarget} parent Parent listenable (null if none).\n */\ngoog.events.EventTarget.prototype.setParentEventTarget = function(parent) {\n this.parentEventTarget_ = parent;\n};\n\n\n/**\n * Adds an event listener to the event target. The same handler can only be\n * added once per the type. Even if you add the same handler multiple times\n * using the same type then it will only be called once when the event is\n * dispatched.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#listen` instead, when possible. Otherwise, use\n * `goog.events.listen` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.addEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * Removes an event listener from the event target. The handler must be the\n * same object as the one added. If the handler has not been added then\n * nothing is done.\n *\n * @param {string} type The type of the event to listen for.\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#unlisten` instead, when possible. Otherwise, use\n * `goog.events.unlisten` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.removeEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\n this.assertInitialized_();\n\n var ancestorsTree, ancestor = this.getParentEventTarget();\n if (ancestor) {\n ancestorsTree = [];\n var ancestorCount = 1;\n for (; ancestor; ancestor = ancestor.getParentEventTarget()) {\n ancestorsTree.push(ancestor);\n goog.asserts.assert(\n (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),\n 'infinite loop');\n }\n }\n\n return goog.events.EventTarget.dispatchEventInternal_(\n this.actualEventTarget_, e, ancestorsTree);\n};\n\n\n/**\n * Removes listeners from this object. Classes that extend EventTarget may\n * need to override this method in order to remove references to DOM Elements\n * and additional listeners.\n * @override\n * @protected\n */\ngoog.events.EventTarget.prototype.disposeInternal = function() {\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\n\n this.removeAllListeners();\n this.parentEventTarget_ = null;\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n this.assertInitialized_();\n return this.eventTargetListeners_.add(\n String(type), listener, false /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n return this.eventTargetListeners_.add(\n String(type), listener, true /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n return this.eventTargetListeners_.remove(\n String(type), listener, opt_useCapture, opt_listenerScope);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\n return this.eventTargetListeners_.removeByKey(key);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\n // TODO(chrishenry): Previously, removeAllListeners can be called on\n // uninitialized EventTarget, so we preserve that behavior. We\n // should remove this when usages that rely on that fact are purged.\n if (!this.eventTargetListeners_) {\n return 0;\n }\n return this.eventTargetListeners_.removeAll(opt_type);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.fireListeners = function(\n type, capture, eventObject) {\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // getListeners(type, capture) instead, which is simpler.\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\n if (!listenerArray) {\n return true;\n }\n listenerArray = listenerArray.concat();\n\n var rv = true;\n for (var i = 0; i < listenerArray.length; ++i) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && !listener.removed && listener.capture == capture) {\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n this.unlistenByKey(listener);\n }\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\n }\n }\n\n return rv && !eventObject.defaultPrevented;\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\n return this.eventTargetListeners_.getListeners(String(type), capture);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n return this.eventTargetListeners_.getListener(\n String(type), listener, capture, opt_listenerScope);\n};\n\n\n/** @override */\ngoog.events.EventTarget.prototype.hasListener = function(\n opt_type, opt_capture) {\n var id = (opt_type !== undefined) ? String(opt_type) : undefined;\n return this.eventTargetListeners_.hasListener(id, opt_capture);\n};\n\n\n/**\n * Sets the target to be used for `event.target` when firing\n * event. Mainly used for testing. For example, see\n * `goog.testing.events.mixinListenable`.\n * @param {!Object} target The target.\n */\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\n this.actualEventTarget_ = target;\n};\n\n\n/**\n * Asserts that the event target instance is initialized properly.\n * @private\n */\ngoog.events.EventTarget.prototype.assertInitialized_ = function() {\n goog.asserts.assert(\n this.eventTargetListeners_,\n 'Event target is not initialized. Did you call the superclass ' +\n '(goog.events.EventTarget) constructor?');\n};\n\n\n/**\n * Dispatches the given event on the ancestorsTree.\n *\n * @param {!Object} target The target to dispatch on.\n * @param {goog.events.Event|Object|string} e The event object.\n * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors\n * tree of the target, in reverse order from the closest ancestor\n * to the root event target. May be null if the target has no ancestor.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @private\n */\ngoog.events.EventTarget.dispatchEventInternal_ = function(\n target, e, opt_ancestorsTree) {\n /** @suppress {missingProperties} */\n var type = e.type || /** @type {string} */ (e);\n\n // If accepting a string or object, create a custom event object so that\n // preventDefault and stopPropagation work with the event.\n if (typeof e === 'string') {\n e = new goog.events.Event(e, target);\n } else if (!(e instanceof goog.events.Event)) {\n var oldEvent = e;\n e = new goog.events.Event(type, target);\n goog.object.extend(e, oldEvent);\n } else {\n e.target = e.target || target;\n }\n\n var rv = true, currentTarget;\n\n // Executes all capture listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (var i = opt_ancestorsTree.length - 1;\n !e.hasPropagationStopped() && i >= 0; i--) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, true, e) && rv;\n }\n }\n\n // Executes capture and bubble listeners on the target.\n if (!e.hasPropagationStopped()) {\n currentTarget = /** @type {?} */ (e.currentTarget = target);\n rv = currentTarget.fireListeners(type, true, e) && rv;\n if (!e.hasPropagationStopped()) {\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n // Executes all bubble listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (i = 0; !e.hasPropagationStopped() && i < opt_ancestorsTree.length;\n i++) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n return rv;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A timer class to which other classes and objects can listen on.\n * This is only an abstraction above `setInterval`.\n *\n * @see ../demos/timers.html\n */\n\ngoog.provide('goog.Timer');\n\ngoog.require('goog.Promise');\ngoog.require('goog.events.EventTarget');\n\n\n\n/**\n * Class for handling timing events.\n *\n * @param {number=} opt_interval Number of ms between ticks (default: 1ms).\n * @param {Object=} opt_timerObject An object that has `setTimeout`,\n * `setInterval`, `clearTimeout` and `clearInterval`\n * (e.g., `window`).\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.Timer = function(opt_interval, opt_timerObject) {\n goog.events.EventTarget.call(this);\n\n /**\n * Number of ms between ticks\n * @private {number}\n */\n this.interval_ = opt_interval || 1;\n\n /**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the window\n * object. Changing this on {@link goog.Timer.prototype} changes the object\n * for all timer instances which can be useful if your environment has some\n * other implementation of timers than the `window` object.\n * @private {{setTimeout:!Function, clearTimeout:!Function}}\n */\n this.timerObject_ = /** @type {{setTimeout, clearTimeout}} */ (\n opt_timerObject || goog.Timer.defaultTimerObject);\n\n /**\n * Cached `tick_` bound to the object for later use in the timer.\n * @private {Function}\n * @const\n */\n this.boundTick_ = goog.bind(this.tick_, this);\n\n /**\n * Firefox browser often fires the timer event sooner (sometimes MUCH sooner)\n * than the requested timeout. So we compare the time to when the event was\n * last fired, and reschedule if appropriate. See also\n * {@link goog.Timer.intervalScale}.\n * @private {number}\n */\n this.last_ = goog.now();\n};\ngoog.inherits(goog.Timer, goog.events.EventTarget);\n\n\n/**\n * Maximum timeout value.\n *\n * Timeout values too big to fit into a signed 32-bit integer may cause overflow\n * in FF, Safari, and Chrome, resulting in the timeout being scheduled\n * immediately. It makes more sense simply not to schedule these timeouts, since\n * 24.8 days is beyond a reasonable expectation for the browser to stay open.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.MAX_TIMEOUT_ = 2147483647;\n\n\n/**\n * A timer ID that cannot be returned by any known implementation of\n * `window.setTimeout`. Passing this value to `window.clearTimeout`\n * should therefore be a no-op.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.INVALID_TIMEOUT_ID_ = -1;\n\n\n/**\n * Whether this timer is enabled\n * @type {boolean}\n */\ngoog.Timer.prototype.enabled = false;\n\n\n/**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the global\n * object. Changing `goog.Timer.defaultTimerObject` changes the object for\n * all timer instances which can be useful if your environment has some other\n * implementation of timers you'd like to use.\n * @type {{setTimeout, clearTimeout}}\n */\ngoog.Timer.defaultTimerObject = goog.global;\n\n\n/**\n * Variable that controls the timer error correction. If the timer is called\n * before the requested interval times `intervalScale`, which often\n * happens on Mozilla, the timer is rescheduled.\n * @see {@link #last_}\n * @type {number}\n */\ngoog.Timer.intervalScale = 0.8;\n\n\n/**\n * Variable for storing the result of `setInterval`.\n * @private {?number}\n */\ngoog.Timer.prototype.timer_ = null;\n\n\n/**\n * Gets the interval of the timer.\n * @return {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.getInterval = function() {\n return this.interval_;\n};\n\n\n/**\n * Sets the interval of the timer.\n * @param {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.setInterval = function(interval) {\n this.interval_ = interval;\n if (this.timer_ && this.enabled) {\n // Stop and then start the timer to reset the interval.\n this.stop();\n this.start();\n } else if (this.timer_) {\n this.stop();\n }\n};\n\n\n/**\n * Callback for the `setTimeout` used by the timer.\n * @private\n */\ngoog.Timer.prototype.tick_ = function() {\n if (this.enabled) {\n var elapsed = goog.now() - this.last_;\n if (elapsed > 0 && elapsed < this.interval_ * goog.Timer.intervalScale) {\n this.timer_ = this.timerObject_.setTimeout(\n this.boundTick_, this.interval_ - elapsed);\n return;\n }\n\n // Prevents setInterval from registering a duplicate timeout when called\n // in the timer event handler.\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n\n this.dispatchTick();\n // The timer could be stopped in the timer event handler.\n if (this.enabled) {\n // Stop and start to ensure there is always only one timeout even if\n // start is called in the timer event handler.\n this.stop();\n this.start();\n }\n }\n};\n\n\n/**\n * Dispatches the TICK event. This is its own method so subclasses can override.\n */\ngoog.Timer.prototype.dispatchTick = function() {\n this.dispatchEvent(goog.Timer.TICK);\n};\n\n\n/**\n * Starts the timer.\n */\ngoog.Timer.prototype.start = function() {\n this.enabled = true;\n\n // If there is no interval already registered, start it now\n if (!this.timer_) {\n // IMPORTANT!\n // window.setInterval in FireFox has a bug - it fires based on\n // absolute time, rather than on relative time. What this means\n // is that if a computer is sleeping/hibernating for 24 hours\n // and the timer interval was configured to fire every 1000ms,\n // then after the PC wakes up the timer will fire, in rapid\n // succession, 3600*24 times.\n // This bug is described here and is already fixed, but it will\n // take time to propagate, so for now I am switching this over\n // to setTimeout logic.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=376643\n //\n this.timer_ = this.timerObject_.setTimeout(this.boundTick_, this.interval_);\n this.last_ = goog.now();\n }\n};\n\n\n/**\n * Stops the timer.\n */\ngoog.Timer.prototype.stop = function() {\n this.enabled = false;\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n};\n\n\n/** @override */\ngoog.Timer.prototype.disposeInternal = function() {\n goog.Timer.superClass_.disposeInternal.call(this);\n this.stop();\n delete this.timerObject_;\n};\n\n\n/**\n * Constant for the timer's event type.\n * @const\n */\ngoog.Timer.TICK = 'tick';\n\n\n/**\n * Calls the given function once, after the optional pause.\n * <p>\n * The function is always called asynchronously, even if the delay is 0. This\n * is a common trick to schedule a function to run after a batch of browser\n * event processing.\n *\n * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function\n * or object that has a handleEvent method.\n * @param {number=} opt_delay Milliseconds to wait; default is 0.\n * @param {SCOPE=} opt_handler Object in whose scope to call the listener.\n * @return {number} A handle to the timer ID.\n * @template SCOPE\n */\ngoog.Timer.callOnce = function(listener, opt_delay, opt_handler) {\n if (goog.isFunction(listener)) {\n if (opt_handler) {\n listener = goog.bind(listener, opt_handler);\n }\n } else if (listener && typeof listener.handleEvent == 'function') {\n // using typeof to prevent strict js warning\n listener = goog.bind(listener.handleEvent, listener);\n } else {\n throw new Error('Invalid listener argument');\n }\n\n if (Number(opt_delay) > goog.Timer.MAX_TIMEOUT_) {\n // Timeouts greater than MAX_INT return immediately due to integer\n // overflow in many browsers. Since MAX_INT is 24.8 days, just don't\n // schedule anything at all.\n return goog.Timer.INVALID_TIMEOUT_ID_;\n } else {\n return goog.Timer.defaultTimerObject.setTimeout(listener, opt_delay || 0);\n }\n};\n\n\n/**\n * Clears a timeout initiated by {@link #callOnce}.\n * @param {?number} timerId A timer ID.\n */\ngoog.Timer.clear = function(timerId) {\n goog.Timer.defaultTimerObject.clearTimeout(timerId);\n};\n\n\n/**\n * @param {number} delay Milliseconds to wait.\n * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value\n * with which the promise will be resolved.\n * @return {!goog.Promise<RESULT>} A promise that will be resolved after\n * the specified delay, unless it is canceled first.\n * @template RESULT\n */\ngoog.Timer.promise = function(delay, opt_result) {\n var timerKey = null;\n return new goog\n .Promise(function(resolve, reject) {\n timerKey =\n goog.Timer.callOnce(function() { resolve(opt_result); }, delay);\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\n reject(new Error('Failed to schedule timer.'));\n }\n })\n .thenCatch(function(error) {\n // Clear the timer. The most likely reason is \"cancel\" signal.\n goog.Timer.clear(timerKey);\n throw error;\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Generics method for collection-like classes and objects.\n *\n *\n * This file contains functions to work with collections. It supports using\n * Map, Set, Array and Object and other classes that implement collection-like\n * methods.\n * @suppress {strictMissingProperties}\n */\n\n\ngoog.provide('goog.structs');\n\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n// We treat an object as a dictionary if it has getKeys or it is an object that\n// isn't arrayLike.\n\n\n/**\n * Returns the number of values in the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {number} The number of values in the collection-like object.\n */\ngoog.structs.getCount = function(col) {\n if (col.getCount && typeof col.getCount == 'function') {\n return col.getCount();\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return col.length;\n }\n return goog.object.getCount(col);\n};\n\n\n/**\n * Returns the values of the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {!Array<?>} The values in the collection-like object.\n */\ngoog.structs.getValues = function(col) {\n if (col.getValues && typeof col.getValues == 'function') {\n return col.getValues();\n }\n if (typeof col === 'string') {\n return col.split('');\n }\n if (goog.isArrayLike(col)) {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(col[i]);\n }\n return rv;\n }\n return goog.object.getValues(col);\n};\n\n\n/**\n * Returns the keys of the collection. Some collections have no notion of\n * keys/indexes and this function will return undefined in those cases.\n * @param {Object} col The collection-like object.\n * @return {!Array|undefined} The keys in the collection.\n */\ngoog.structs.getKeys = function(col) {\n if (col.getKeys && typeof col.getKeys == 'function') {\n return col.getKeys();\n }\n // if we have getValues but no getKeys we know this is a key-less collection\n if (col.getValues && typeof col.getValues == 'function') {\n return undefined;\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(i);\n }\n return rv;\n }\n\n return goog.object.getKeys(col);\n};\n\n\n/**\n * Whether the collection contains the given value. This is O(n) and uses\n * equals (==) to test the existence.\n * @param {Object} col The collection-like object.\n * @param {*} val The value to check for.\n * @return {boolean} True if the map contains the value.\n */\ngoog.structs.contains = function(col, val) {\n if (col.contains && typeof col.contains == 'function') {\n return col.contains(val);\n }\n if (col.containsValue && typeof col.containsValue == 'function') {\n return col.containsValue(val);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\n }\n return goog.object.containsValue(col, val);\n};\n\n\n/**\n * Whether the collection is empty.\n * @param {Object} col The collection-like object.\n * @return {boolean} True if empty.\n */\ngoog.structs.isEmpty = function(col) {\n if (col.isEmpty && typeof col.isEmpty == 'function') {\n return col.isEmpty();\n }\n\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\n // string as\n // collection and as such even whitespace matters\n\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.isEmpty(/** @type {!Array<?>} */ (col));\n }\n return goog.object.isEmpty(col);\n};\n\n\n/**\n * Removes all the elements from the collection.\n * @param {Object} col The collection-like object.\n */\ngoog.structs.clear = function(col) {\n // NOTE(arv): This should not contain strings because strings are immutable\n if (col.clear && typeof col.clear == 'function') {\n col.clear();\n } else if (goog.isArrayLike(col)) {\n goog.array.clear(/** @type {IArrayLike<?>} */ (col));\n } else {\n goog.object.clear(col);\n }\n};\n\n\n/**\n * Calls a function for each value in a collection. The function takes\n * three arguments; the value, the key and the collection.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):?} f The function to call for every value.\n * This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and the return value is irrelevant.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @template T,S\n * @deprecated Use a more specific method, e.g. goog.array.forEach,\n * goog.object.forEach, or for-of.\n */\ngoog.structs.forEach = function(col, f, opt_obj) {\n if (col.forEach && typeof col.forEach == 'function') {\n col.forEach(f, opt_obj);\n } else if (goog.isArrayLike(col) || typeof col === 'string') {\n goog.array.forEach(/** @type {!Array<?>} */ (col), f, opt_obj);\n } else {\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);\n }\n }\n};\n\n\n/**\n * Calls a function for every value in the collection. When a call returns true,\n * adds the value to a new collection (Array is returned by default).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and should return a Boolean. If the\n * return value is true the value is added to the result collection. If it\n * is false the value is not included.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object|!Array<?>} A new collection where the passed values are\n * present. If col is a key-less collection an array is returned. If col\n * has keys and values a plain old JS object is returned.\n * @template T,S\n */\ngoog.structs.filter = function(col, f, opt_obj) {\n if (typeof col.filter == 'function') {\n return col.filter(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.filter(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {\n rv[keys[i]] = values[i];\n }\n }\n } else {\n // We should not use goog.array.filter here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n if (f.call(opt_obj, values[i], undefined, col)) {\n rv.push(values[i]);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Calls a function for every value in the collection and adds the result into a\n * new collection (defaults to creating a new Array).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):V} f The function to call for every value.\n * This function takes 3 arguments (the value, the key or undefined if the\n * collection has no notion of keys, and the collection) and should return\n * something. The result will be used as the value in the new collection.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object<V>|!Array<V>} A new collection with the new values. If\n * col is a key-less collection an array is returned. If col has keys and\n * values a plain old JS object is returned.\n * @template T,S,V\n */\ngoog.structs.map = function(col, f, opt_obj) {\n if (typeof col.map == 'function') {\n return col.map(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.map(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);\n }\n } else {\n // We should not use goog.array.map here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);\n }\n }\n return rv;\n};\n\n\n/**\n * Calls f for each value in a collection. If any call returns true this returns\n * true (without checking the rest). If all returns false this returns false.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or undefined\n * if the collection has no notion of keys, and the collection) and should\n * return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if any value passes the test.\n * @template T,S\n */\ngoog.structs.some = function(col, f, opt_obj) {\n if (typeof col.some == 'function') {\n return col.some(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.some(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Calls f for each value in a collection. If all calls return true this return\n * true this returns true. If any returns false this returns false at this point\n * and does not continue to check the remaining values.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or\n * undefined if the collection has no notion of keys, and the collection)\n * and should return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if all key-value pairs pass the test.\n * @template T,S\n */\ngoog.structs.every = function(col, f, opt_obj) {\n if (typeof col.every == 'function') {\n return col.every(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.every(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Datastructure: Hash Map.\n *\n *\n * This file contains an implementation of a Map structure. It implements a lot\n * of the methods used in goog.structs so those functions work on hashes. This\n * is best suited for complex key types. For simple keys such as numbers and\n * strings consider using the lighter-weight utilities in goog.object.\n */\n\n\ngoog.provide('goog.structs.Map');\n\ngoog.require('goog.iter.Iterator');\ngoog.require('goog.iter.StopIteration');\n\n\n\n/**\n * Class for Hash Map datastructure.\n * @param {*=} opt_map Map or Object to initialize the map with.\n * @param {...*} var_args If 2 or more arguments are present then they\n * will be used as key-value pairs.\n * @constructor\n * @template K, V\n * @deprecated This type is misleading: use ES6 Map instead.\n */\ngoog.structs.Map = function(opt_map, var_args) {\n\n /**\n * Underlying JS object used to implement the map.\n * @private {!Object}\n */\n this.map_ = {};\n\n /**\n * An array of keys. This is necessary for two reasons:\n * 1. Iterating the keys using for (var key in this.map_) allocates an\n * object for every key in IE which is really bad for IE6 GC perf.\n * 2. Without a side data structure, we would need to escape all the keys\n * as that would be the only way we could tell during iteration if the\n * key was an internal key or a property of the object.\n *\n * This array can contain deleted keys so it's necessary to check the map\n * as well to see if the key is still in the map (this doesn't require a\n * memory allocation in IE).\n * @private {!Array<string>}\n */\n this.keys_ = [];\n\n /**\n * The number of key value pairs in the map.\n * @private {number}\n */\n this.count_ = 0;\n\n /**\n * Version used to detect changes while iterating.\n * @private {number}\n */\n this.version_ = 0;\n\n var argLength = arguments.length;\n\n if (argLength > 1) {\n if (argLength % 2) {\n throw new Error('Uneven number of arguments');\n }\n for (var i = 0; i < argLength; i += 2) {\n this.set(arguments[i], arguments[i + 1]);\n }\n } else if (opt_map) {\n this.addAll(/** @type {!Object} */ (opt_map));\n }\n};\n\n\n/**\n * @return {number} The number of key-value pairs in the map.\n */\ngoog.structs.Map.prototype.getCount = function() {\n return this.count_;\n};\n\n\n/**\n * Returns the values of the map.\n * @return {!Array<V>} The values in the map.\n */\ngoog.structs.Map.prototype.getValues = function() {\n this.cleanupKeysArray_();\n\n var rv = [];\n for (var i = 0; i < this.keys_.length; i++) {\n var key = this.keys_[i];\n rv.push(this.map_[key]);\n }\n return rv;\n};\n\n\n/**\n * Returns the keys of the map.\n * @return {!Array<string>} Array of string values.\n */\ngoog.structs.Map.prototype.getKeys = function() {\n this.cleanupKeysArray_();\n return /** @type {!Array<string>} */ (this.keys_.concat());\n};\n\n\n/**\n * Whether the map contains the given key.\n * @param {*} key The key to check for.\n * @return {boolean} Whether the map contains the key.\n */\ngoog.structs.Map.prototype.containsKey = function(key) {\n return goog.structs.Map.hasKey_(this.map_, key);\n};\n\n\n/**\n * Whether the map contains the given value. This is O(n).\n * @param {V} val The value to check for.\n * @return {boolean} Whether the map contains the value.\n */\ngoog.structs.Map.prototype.containsValue = function(val) {\n for (var i = 0; i < this.keys_.length; i++) {\n var key = this.keys_[i];\n if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Whether this map is equal to the argument map.\n * @param {goog.structs.Map} otherMap The map against which to test equality.\n * @param {function(V, V): boolean=} opt_equalityFn Optional equality function\n * to test equality of values. If not specified, this will test whether\n * the values contained in each map are identical objects.\n * @return {boolean} Whether the maps are equal.\n */\ngoog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) {\n if (this === otherMap) {\n return true;\n }\n\n if (this.count_ != otherMap.getCount()) {\n return false;\n }\n\n var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals;\n\n this.cleanupKeysArray_();\n for (var key, i = 0; key = this.keys_[i]; i++) {\n if (!equalityFn(this.get(key), otherMap.get(key))) {\n return false;\n }\n }\n\n return true;\n};\n\n\n/**\n * Default equality test for values.\n * @param {*} a The first value.\n * @param {*} b The second value.\n * @return {boolean} Whether a and b reference the same object.\n */\ngoog.structs.Map.defaultEquals = function(a, b) {\n return a === b;\n};\n\n\n/**\n * @return {boolean} Whether the map is empty.\n */\ngoog.structs.Map.prototype.isEmpty = function() {\n return this.count_ == 0;\n};\n\n\n/**\n * Removes all key-value pairs from the map.\n */\ngoog.structs.Map.prototype.clear = function() {\n this.map_ = {};\n this.keys_.length = 0;\n this.count_ = 0;\n this.version_ = 0;\n};\n\n\n/**\n * Removes a key-value pair based on the key. This is O(logN) amortized due to\n * updating the keys array whenever the count becomes half the size of the keys\n * in the keys array.\n * @param {*} key The key to remove.\n * @return {boolean} Whether object was removed.\n */\ngoog.structs.Map.prototype.remove = function(key) {\n if (goog.structs.Map.hasKey_(this.map_, key)) {\n delete this.map_[key];\n this.count_--;\n this.version_++;\n\n // clean up the keys array if the threshold is hit\n if (this.keys_.length > 2 * this.count_) {\n this.cleanupKeysArray_();\n }\n\n return true;\n }\n return false;\n};\n\n\n/**\n * Cleans up the temp keys array by removing entries that are no longer in the\n * map.\n * @private\n */\ngoog.structs.Map.prototype.cleanupKeysArray_ = function() {\n if (this.count_ != this.keys_.length) {\n // First remove keys that are no longer in the map.\n var srcIndex = 0;\n var destIndex = 0;\n while (srcIndex < this.keys_.length) {\n var key = this.keys_[srcIndex];\n if (goog.structs.Map.hasKey_(this.map_, key)) {\n this.keys_[destIndex++] = key;\n }\n srcIndex++;\n }\n this.keys_.length = destIndex;\n }\n\n if (this.count_ != this.keys_.length) {\n // If the count still isn't correct, that means we have duplicates. This can\n // happen when the same key is added and removed multiple times. Now we have\n // to allocate one extra Object to remove the duplicates. This could have\n // been done in the first pass, but in the common case, we can avoid\n // allocating an extra object by only doing this when necessary.\n var seen = {};\n var srcIndex = 0;\n var destIndex = 0;\n while (srcIndex < this.keys_.length) {\n var key = this.keys_[srcIndex];\n if (!(goog.structs.Map.hasKey_(seen, key))) {\n this.keys_[destIndex++] = key;\n seen[key] = 1;\n }\n srcIndex++;\n }\n this.keys_.length = destIndex;\n }\n};\n\n\n/**\n * Returns the value for the given key. If the key is not found and the default\n * value is not given this will return `undefined`.\n * @param {*} key The key to get the value for.\n * @param {DEFAULT=} opt_val The value to return if no item is found for the\n * given key, defaults to undefined.\n * @return {V|DEFAULT} The value for the given key.\n * @template DEFAULT\n */\ngoog.structs.Map.prototype.get = function(key, opt_val) {\n if (goog.structs.Map.hasKey_(this.map_, key)) {\n return this.map_[key];\n }\n return opt_val;\n};\n\n\n/**\n * Adds a key-value pair to the map.\n * @param {*} key The key.\n * @param {V} value The value to add.\n * @return {*} Some subclasses return a value.\n */\ngoog.structs.Map.prototype.set = function(key, value) {\n if (!(goog.structs.Map.hasKey_(this.map_, key))) {\n this.count_++;\n // TODO(johnlenz): This class lies, it claims to return an array of string\n // keys, but instead returns the original object used.\n this.keys_.push(/** @type {?} */ (key));\n // Only change the version if we add a new key.\n this.version_++;\n }\n this.map_[key] = value;\n};\n\n\n/**\n * Adds multiple key-value pairs from another goog.structs.Map or Object.\n * @param {?Object} map Object containing the data to add.\n */\ngoog.structs.Map.prototype.addAll = function(map) {\n if (map instanceof goog.structs.Map) {\n var keys = map.getKeys();\n for (var i = 0; i < keys.length; i++) {\n this.set(keys[i], map.get(keys[i]));\n }\n } else {\n for (var key in map) {\n this.set(key, map[key]);\n }\n }\n};\n\n\n/**\n * Calls the given function on each entry in the map.\n * @param {function(this:T, V, K, goog.structs.Map<K,V>)} f\n * @param {T=} opt_obj The value of \"this\" inside f.\n * @template T\n */\ngoog.structs.Map.prototype.forEach = function(f, opt_obj) {\n var keys = this.getKeys();\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = this.get(key);\n f.call(opt_obj, value, key, this);\n }\n};\n\n\n/**\n * Clones a map and returns a new map.\n * @return {!goog.structs.Map} A new map with the same key-value pairs.\n */\ngoog.structs.Map.prototype.clone = function() {\n return new goog.structs.Map(this);\n};\n\n\n/**\n * Returns a new map in which all the keys and values are interchanged\n * (keys become values and values become keys). If multiple keys map to the\n * same value, the chosen transposed value is implementation-dependent.\n *\n * It acts very similarly to {goog.object.transpose(Object)}.\n *\n * @return {!goog.structs.Map} The transposed map.\n */\ngoog.structs.Map.prototype.transpose = function() {\n var transposed = new goog.structs.Map();\n for (var i = 0; i < this.keys_.length; i++) {\n var key = this.keys_[i];\n var value = this.map_[key];\n transposed.set(value, key);\n }\n\n return transposed;\n};\n\n\n/**\n * @return {!Object} Object representation of the map.\n */\ngoog.structs.Map.prototype.toObject = function() {\n this.cleanupKeysArray_();\n var obj = {};\n for (var i = 0; i < this.keys_.length; i++) {\n var key = this.keys_[i];\n obj[key] = this.map_[key];\n }\n return obj;\n};\n\n\n/**\n * Returns an iterator that iterates over the keys in the map. Removal of keys\n * while iterating might have undesired side effects.\n * @return {!goog.iter.Iterator} An iterator over the keys in the map.\n */\ngoog.structs.Map.prototype.getKeyIterator = function() {\n return this.__iterator__(true);\n};\n\n\n/**\n * Returns an iterator that iterates over the values in the map. Removal of\n * keys while iterating might have undesired side effects.\n * @return {!goog.iter.Iterator} An iterator over the values in the map.\n */\ngoog.structs.Map.prototype.getValueIterator = function() {\n return this.__iterator__(false);\n};\n\n\n/**\n * Returns an iterator that iterates over the values or the keys in the map.\n * This throws an exception if the map was mutated since the iterator was\n * created.\n * @param {boolean=} opt_keys True to iterate over the keys. False to iterate\n * over the values. The default value is false.\n * @return {!goog.iter.Iterator} An iterator over the values or keys in the map.\n */\ngoog.structs.Map.prototype.__iterator__ = function(opt_keys) {\n // Clean up keys to minimize the risk of iterating over dead keys.\n this.cleanupKeysArray_();\n\n var i = 0;\n var version = this.version_;\n var selfObj = this;\n\n var newIter = new goog.iter.Iterator;\n newIter.next = function() {\n if (version != selfObj.version_) {\n throw new Error('The map has changed since the iterator was created');\n }\n if (i >= selfObj.keys_.length) {\n throw goog.iter.StopIteration;\n }\n var key = selfObj.keys_[i++];\n return opt_keys ? key : selfObj.map_[key];\n };\n return newIter;\n};\n\n\n/**\n * Safe way to test for hasOwnProperty. It even allows testing for\n * 'hasOwnProperty'.\n * @param {!Object} obj The object to test for presence of the given key.\n * @param {*} key The key to check for.\n * @return {boolean} Whether the object has the key.\n * @private\n */\ngoog.structs.Map.hasKey_ = function(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple utilities for dealing with URI strings.\n *\n * This is intended to be a lightweight alternative to constructing goog.Uri\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\n * of how much of its functionality you use, this is designed to be a set of\n * mostly-independent utilities so that the compiler includes only what is\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\n * 1.5k post-gzip. To ensure the savings remain, future developers should\n * avoid adding new functionality to existing functions, but instead create\n * new ones and factor out shared code.\n *\n * Many of these utilities have limited functionality, tailored to common\n * cases. The query parameter utilities assume that the parameter keys are\n * already encoded, since most keys are compile-time alphanumeric strings. The\n * query parameter mutation utilities also do not tolerate fragment identifiers.\n *\n * By design, these functions can be slower than goog.Uri equivalents.\n * Repeated calls to some of functions may be quadratic in behavior for IE,\n * although the effect is somewhat limited given the 2kb limit.\n *\n * One advantage of the limited functionality here is that this approach is\n * less sensitive to differences in URI encodings than goog.Uri, since these\n * functions operate on strings directly, rather than decoding them and\n * then re-encoding.\n *\n * Uses features of RFC 3986 for parsing/formatting URIs:\n * http://www.ietf.org/rfc/rfc3986.txt\n */\n\ngoog.provide('goog.uri.utils');\ngoog.provide('goog.uri.utils.ComponentIndex');\ngoog.provide('goog.uri.utils.QueryArray');\ngoog.provide('goog.uri.utils.QueryValue');\ngoog.provide('goog.uri.utils.StandardQueryParam');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.string');\n\n\n/**\n * Character codes inlined to avoid object allocations due to charCode.\n * @enum {number}\n * @private\n */\ngoog.uri.utils.CharCode_ = {\n AMPERSAND: 38,\n EQUAL: 61,\n HASH: 35,\n QUESTION: 63\n};\n\n\n/**\n * Builds a URI string from already-encoded parts.\n *\n * No encoding is performed. Any component may be omitted as either null or\n * undefined.\n *\n * @param {?string=} opt_scheme The scheme such as 'http'.\n * @param {?string=} opt_userInfo The user name before the '@'.\n * @param {?string=} opt_domain The domain such as 'www.google.com', already\n * URI-encoded.\n * @param {(string|number|null)=} opt_port The port number.\n * @param {?string=} opt_path The path, already URI-encoded. If it is not\n * empty, it must begin with a slash.\n * @param {?string=} opt_queryData The URI-encoded query data.\n * @param {?string=} opt_fragment The URI-encoded fragment identifier.\n * @return {string} The fully combined URI.\n */\ngoog.uri.utils.buildFromEncodedParts = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,\n opt_fragment) {\n var out = '';\n\n if (opt_scheme) {\n out += opt_scheme + ':';\n }\n\n if (opt_domain) {\n out += '//';\n\n if (opt_userInfo) {\n out += opt_userInfo + '@';\n }\n\n out += opt_domain;\n\n if (opt_port) {\n out += ':' + opt_port;\n }\n }\n\n if (opt_path) {\n out += opt_path;\n }\n\n if (opt_queryData) {\n out += '?' + opt_queryData;\n }\n\n if (opt_fragment) {\n out += '#' + opt_fragment;\n }\n\n return out;\n};\n\n\n/**\n * A regular expression for breaking a URI into its component parts.\n *\n * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B\n * As the \"first-match-wins\" algorithm is identical to the \"greedy\"\n * disambiguation method used by POSIX regular expressions, it is natural and\n * commonplace to use a regular expression for parsing the potential five\n * components of a URI reference.\n *\n * The following line is the regular expression for breaking-down a\n * well-formed URI reference into its components.\n *\n * <pre>\n * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n * 12 3 4 5 6 7 8 9\n * </pre>\n *\n * The numbers in the second line above are only to assist readability; they\n * indicate the reference points for each subexpression (i.e., each paired\n * parenthesis). We refer to the value matched for subexpression <n> as $<n>.\n * For example, matching the above expression to\n * <pre>\n * http://www.ics.uci.edu/pub/ietf/uri/#Related\n * </pre>\n * results in the following subexpression matches:\n * <pre>\n * $1 = http:\n * $2 = http\n * $3 = //www.ics.uci.edu\n * $4 = www.ics.uci.edu\n * $5 = /pub/ietf/uri/\n * $6 = <undefined>\n * $7 = <undefined>\n * $8 = #Related\n * $9 = Related\n * </pre>\n * where <undefined> indicates that the component is not present, as is the\n * case for the query component in the above example. Therefore, we can\n * determine the value of the five components as\n * <pre>\n * scheme = $2\n * authority = $4\n * path = $5\n * query = $7\n * fragment = $9\n * </pre>\n *\n * The regular expression has been modified slightly to expose the\n * userInfo, domain, and port separately from the authority.\n * The modified version yields\n * <pre>\n * $1 = http scheme\n * $2 = <undefined> userInfo -\\\n * $3 = www.ics.uci.edu domain | authority\n * $4 = <undefined> port -/\n * $5 = /pub/ietf/uri/ path\n * $6 = <undefined> query without ?\n * $7 = Related fragment without #\n * </pre>\n * @type {!RegExp}\n * @private\n */\ngoog.uri.utils.splitRe_ = new RegExp(\n '^' +\n '(?:' +\n '([^:/?#.]+)' + // scheme - ignore special characters\n // used by other URL parts such as :,\n // ?, /, #, and .\n ':)?' +\n '(?://' +\n '(?:([^/?#]*)@)?' + // userInfo\n '([^/#?]*?)' + // domain\n '(?::([0-9]+))?' + // port\n '(?=[/\\\\\\\\#?]|$)' + // authority-terminating character\n ')?' +\n '([^?#]+)?' + // path\n '(?:\\\\?([^#]*))?' + // query\n '(?:#([\\\\s\\\\S]*))?' + // fragment\n '$');\n\n\n/**\n * The index of each URI component in the return value of goog.uri.utils.split.\n * @enum {number}\n */\ngoog.uri.utils.ComponentIndex = {\n SCHEME: 1,\n USER_INFO: 2,\n DOMAIN: 3,\n PORT: 4,\n PATH: 5,\n QUERY_DATA: 6,\n FRAGMENT: 7\n};\n\n\n/**\n * Splits a URI into its component parts.\n *\n * Each component can be accessed via the component indices; for example:\n * <pre>\n * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];\n * </pre>\n *\n * @param {string} uri The URI string to examine.\n * @return {!Array<string|undefined>} Each component still URI-encoded.\n * Each component that is present will contain the encoded value, whereas\n * components that are not present will be undefined or empty, depending\n * on the browser's regular expression implementation. Never null, since\n * arbitrary strings may still look like path names.\n */\ngoog.uri.utils.split = function(uri) {\n // See @return comment -- never null.\n return /** @type {!Array<string|undefined>} */ (\n uri.match(goog.uri.utils.splitRe_));\n};\n\n\n/**\n * @param {?string} uri A possibly null string.\n * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986\n * reserved characters will not be removed.\n * @return {?string} The string URI-decoded, or null if uri is null.\n * @private\n */\ngoog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {\n if (!uri) {\n return uri;\n }\n\n return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);\n};\n\n\n/**\n * Gets a URI component by index.\n *\n * It is preferred to use the getPathEncoded() variety of functions ahead,\n * since they are more readable.\n *\n * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.\n * @param {string} uri The URI to examine.\n * @return {?string} The still-encoded component, or null if the component\n * is not present.\n * @private\n */\ngoog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {\n // Convert undefined, null, and empty string into null.\n return goog.uri.utils.split(uri)[componentIndex] || null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The protocol or scheme, or null if none. Does not\n * include trailing colons or slashes.\n */\ngoog.uri.utils.getScheme = function(uri) {\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.SCHEME, uri);\n};\n\n\n/**\n * Gets the effective scheme for the URL. If the URL is relative then the\n * scheme is derived from the page's location.\n * @param {string} uri The URI to examine.\n * @return {string} The protocol or scheme, always lower case.\n */\ngoog.uri.utils.getEffectiveScheme = function(uri) {\n var scheme = goog.uri.utils.getScheme(uri);\n if (!scheme && goog.global.self && goog.global.self.location) {\n var protocol = goog.global.self.location.protocol;\n scheme = protocol.substr(0, protocol.length - 1);\n }\n // NOTE: When called from a web worker in Firefox 3.5, location may be null.\n // All other browsers with web workers support self.location from the worker.\n return scheme ? scheme.toLowerCase() : '';\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The user name still encoded, or null if none.\n */\ngoog.uri.utils.getUserInfoEncoded = function(uri) {\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.USER_INFO, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded user info, or null if none.\n */\ngoog.uri.utils.getUserInfo = function(uri) {\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getUserInfoEncoded(uri));\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The domain name still encoded, or null if none.\n */\ngoog.uri.utils.getDomainEncoded = function(uri) {\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.DOMAIN, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded domain, or null if none.\n */\ngoog.uri.utils.getDomain = function(uri) {\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?number} The port number, or null if none.\n */\ngoog.uri.utils.getPort = function(uri) {\n // Coerce to a number. If the result of getComponentByIndex_ is null or\n // non-numeric, the number coersion yields NaN. This will then return\n // null for all non-numeric cases (though also zero, which isn't a relevant\n // port number).\n return Number(\n goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PORT, uri)) ||\n null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The path still encoded, or null if none. Includes the\n * leading slash, if any.\n */\ngoog.uri.utils.getPathEncoded = function(uri) {\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PATH, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded path, or null if none. Includes the leading\n * slash, if any.\n */\ngoog.uri.utils.getPath = function(uri) {\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The query data still encoded, or null if none. Does not\n * include the question mark itself.\n */\ngoog.uri.utils.getQueryData = function(uri) {\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.QUERY_DATA, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The fragment identifier, or null if none. Does not\n * include the hash mark itself.\n */\ngoog.uri.utils.getFragmentEncoded = function(uri) {\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? null : uri.substr(hashIndex + 1);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @param {?string} fragment The encoded fragment identifier, or null if none.\n * Does not include the hash mark itself.\n * @return {string} The URI with the fragment set.\n */\ngoog.uri.utils.setFragmentEncoded = function(uri, fragment) {\n return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded fragment identifier, or null if none. Does\n * not include the hash mark.\n */\ngoog.uri.utils.getFragment = function(uri) {\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getFragmentEncoded(uri));\n};\n\n\n/**\n * Extracts everything up to the port of the URI.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getHost = function(uri) {\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME],\n pieces[goog.uri.utils.ComponentIndex.USER_INFO],\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Returns the origin for a given URL.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getOrigin = function(uri) {\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Extracts the path of the URL and everything after.\n * @param {string} uri The URI string.\n * @return {string} The URI, starting at the path and including the query\n * parameters and fragment identifier.\n */\ngoog.uri.utils.getPathAndAfter = function(uri) {\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],\n pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],\n pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Gets the URI with the fragment identifier removed.\n * @param {string} uri The URI to examine.\n * @return {string} Everything preceding the hash mark.\n */\ngoog.uri.utils.removeFragment = function(uri) {\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? uri : uri.substr(0, hashIndex);\n};\n\n\n/**\n * Ensures that two URI's have the exact same domain, scheme, and port.\n *\n * Unlike the version in goog.Uri, this checks protocol, and therefore is\n * suitable for checking against the browser's same-origin policy.\n *\n * @param {string} uri1 The first URI.\n * @param {string} uri2 The second URI.\n * @return {boolean} Whether they have the same scheme, domain and port.\n */\ngoog.uri.utils.haveSameDomain = function(uri1, uri2) {\n var pieces1 = goog.uri.utils.split(uri1);\n var pieces2 = goog.uri.utils.split(uri2);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==\n pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n/**\n * Asserts that there are no fragment or query identifiers, only in uncompiled\n * mode.\n * @param {string} uri The URI to examine.\n * @private\n */\ngoog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {\n goog.asserts.assert(\n uri.indexOf('#') < 0 && uri.indexOf('?') < 0,\n 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',\n uri);\n};\n\n\n/**\n * Supported query parameter values by the parameter serializing utilities.\n *\n * If a value is null or undefined, the key-value pair is skipped, as an easy\n * way to omit parameters conditionally. Non-array parameters are converted\n * to a string and URI encoded. Array values are expanded into multiple\n * &key=value pairs, with each element stringized and URI-encoded.\n *\n * @typedef {*}\n */\ngoog.uri.utils.QueryValue;\n\n\n/**\n * An array representing a set of query parameters with alternating keys\n * and values.\n *\n * Keys are assumed to be URI encoded already and live at even indices. See\n * goog.uri.utils.QueryValue for details on how parameter values are encoded.\n *\n * Example:\n * <pre>\n * var data = [\n * // Simple param: ?name=BobBarker\n * 'name', 'BobBarker',\n * // Conditional param -- may be omitted entirely.\n * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,\n * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null\n * 'house', ['LosAngeles', 'NewYork', null]\n * ];\n * </pre>\n *\n * @typedef {!Array<string|goog.uri.utils.QueryValue>}\n */\ngoog.uri.utils.QueryArray;\n\n\n/**\n * Parses encoded query parameters and calls callback function for every\n * parameter found in the string.\n *\n * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an\n * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means\n * that “…&=&…” and “…&&…” will result in an empty key and value.\n *\n * @param {string} encodedQuery Encoded query string excluding question mark at\n * the beginning.\n * @param {function(string, string)} callback Function called for every\n * parameter found in query string. The first argument (name) will not be\n * urldecoded (so the function is consistent with buildQueryData), but the\n * second will. If the parameter has no value (i.e. “=” was not present)\n * the second argument (value) will be an empty string.\n */\ngoog.uri.utils.parseQueryData = function(encodedQuery, callback) {\n if (!encodedQuery) {\n return;\n }\n var pairs = encodedQuery.split('&');\n for (var i = 0; i < pairs.length; i++) {\n var indexOfEquals = pairs[i].indexOf('=');\n var name = null;\n var value = null;\n if (indexOfEquals >= 0) {\n name = pairs[i].substring(0, indexOfEquals);\n value = pairs[i].substring(indexOfEquals + 1);\n } else {\n name = pairs[i];\n }\n callback(name, value ? goog.string.urlDecode(value) : '');\n }\n};\n\n\n/**\n * Split the URI into 3 parts where the [1] is the queryData without a leading\n * '?'. For example, the URI http://foo.com/bar?a=b#abc returns\n * ['http://foo.com/bar','a=b','#abc'].\n * @param {string} uri The URI to parse.\n * @return {!Array<string>} An array representation of uri of length 3 where the\n * middle value is the queryData without a leading '?'.\n * @private\n */\ngoog.uri.utils.splitQueryData_ = function(uri) {\n // Find the query data and hash.\n var hashIndex = uri.indexOf('#');\n if (hashIndex < 0) {\n hashIndex = uri.length;\n }\n var questionIndex = uri.indexOf('?');\n var queryData;\n if (questionIndex < 0 || questionIndex > hashIndex) {\n questionIndex = hashIndex;\n queryData = '';\n } else {\n queryData = uri.substring(questionIndex + 1, hashIndex);\n }\n return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)];\n};\n\n\n/**\n * Join an array created by splitQueryData_ back into a URI.\n * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.\n * @return {string} The joined URI.\n * @private\n */\ngoog.uri.utils.joinQueryData_ = function(parts) {\n return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];\n};\n\n\n/**\n * @param {string} queryData\n * @param {string} newData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryData_ = function(queryData, newData) {\n if (!newData) {\n return queryData;\n }\n return queryData ? queryData + '&' + newData : newData;\n};\n\n\n/**\n * @param {string} uri\n * @param {string} queryData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {\n if (!queryData) {\n return uri;\n }\n var parts = goog.uri.utils.splitQueryData_(uri);\n parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Appends key=value pairs to an array, supporting multi-valued objects.\n * @param {*} key The key prefix.\n * @param {goog.uri.utils.QueryValue} value The value to serialize.\n * @param {!Array<string>} pairs The array to which the 'key=value' strings\n * should be appended.\n * @private\n */\ngoog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {\n goog.asserts.assertString(key);\n if (Array.isArray(value)) {\n // Convince the compiler it's an array.\n goog.asserts.assertArray(value);\n for (var j = 0; j < value.length; j++) {\n // Convert to string explicitly, to short circuit the null and array\n // logic in this function -- this ensures that null and undefined get\n // written as literal 'null' and 'undefined', and arrays don't get\n // expanded out but instead encoded in the default way.\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\n }\n } else if (value != null) {\n // Skip a top-level null or undefined entirely.\n pairs.push(\n key +\n // Check for empty string. Zero gets encoded into the url as literal\n // strings. For empty string, skip the equal sign, to be consistent\n // with UriBuilder.java.\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\n }\n};\n\n\n/**\n * Builds a query data string from a sequence of alternating keys and values.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\n * Alternating keys and values. See the QueryArray typedef.\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\n goog.asserts.assert(\n Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,\n 'goog.uri.utils: Key/value lists must be even in length.');\n\n var params = [];\n for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {\n var key = /** @type {string} */ (keysAndValues[i]);\n goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Builds a query data string from a map.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys\n * are URI-encoded parameter keys, and the values are arbitrary types\n * or arrays. Keys with a null value are dropped.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryDataFromMap = function(map) {\n var params = [];\n for (var key in map) {\n goog.uri.utils.appendKeyValuePairs_(key, map[key], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Appends URI parameters to an existing URI.\n *\n * The variable arguments may contain alternating keys and values. Keys are\n * assumed to be already URI encoded. The values should not be URI-encoded,\n * and will instead be encoded by this function.\n * <pre>\n * appendParams('http://www.foo.com?existing=true',\n * 'key1', 'value1',\n * 'key2', 'value?willBeEncoded',\n * 'key3', ['valueA', 'valueB', 'valueC'],\n * 'key4', null);\n * result: 'http://www.foo.com?existing=true&' +\n * 'key1=value1&' +\n * 'key2=value%3FwillBeEncoded&' +\n * 'key3=valueA&key3=valueB&key3=valueC'\n * </pre>\n *\n * A single call to this function will not exhibit quadratic behavior in IE,\n * whereas multiple repeated calls may, although the effect is limited by\n * fact that URL's generally can't exceed 2kb.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}\n * var_args\n * An array or argument list conforming to goog.uri.utils.QueryArray.\n * @return {string} The URI with all query parameters added.\n */\ngoog.uri.utils.appendParams = function(uri, var_args) {\n var queryData = arguments.length == 2 ?\n goog.uri.utils.buildQueryData(arguments[1], 0) :\n goog.uri.utils.buildQueryData(arguments, 1);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends query parameters from a map.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are\n * URI-encoded parameter keys, and the values are arbitrary types or arrays.\n * Keys with a null value are dropped.\n * @return {string} The new parameters.\n */\ngoog.uri.utils.appendParamsFromMap = function(uri, map) {\n var queryData = goog.uri.utils.buildQueryDataFromMap(map);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends a single URI parameter.\n *\n * Repeated calls to this can exhibit quadratic behavior in IE6 due to the\n * way string append works, though it should be limited given the 2kb limit.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} key The key, which must already be URI encoded.\n * @param {*=} opt_value The value, which will be stringized and encoded\n * (assumed not already to be encoded). If omitted, undefined, or null, the\n * key will be added as a valueless parameter.\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.appendParam = function(uri, key, opt_value) {\n var value = (opt_value != null) ? '=' + goog.string.urlEncode(opt_value) : '';\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\n};\n\n\n/**\n * Finds the next instance of a query parameter with the specified name.\n *\n * Does not instantiate any objects.\n *\n * @param {string} uri The URI to search. May contain a fragment identifier\n * if opt_hashIndex is specified.\n * @param {number} startIndex The index to begin searching for the key at. A\n * match may be found even if this is one character after the ampersand.\n * @param {string} keyEncoded The URI-encoded key.\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\n * mark is present, it should be its index, otherwise it should be the\n * length of the string.\n * @return {number} The position of the first character in the key's name,\n * immediately after either a question mark or a dot.\n * @private\n */\ngoog.uri.utils.findParam_ = function(\n uri, startIndex, keyEncoded, hashOrEndIndex) {\n var index = startIndex;\n var keyLength = keyEncoded.length;\n\n // Search for the key itself and post-filter for surronuding punctuation,\n // rather than expensively building a regexp.\n while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&\n index < hashOrEndIndex) {\n var precedingChar = uri.charCodeAt(index - 1);\n // Ensure that the preceding character is '&' or '?'.\n if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n precedingChar == goog.uri.utils.CharCode_.QUESTION) {\n // Ensure the following character is '&', '=', '#', or NaN\n // (end of string).\n var followingChar = uri.charCodeAt(index + keyLength);\n if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||\n followingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n followingChar == goog.uri.utils.CharCode_.HASH) {\n return index;\n }\n }\n index += keyLength + 1;\n }\n\n return -1;\n};\n\n\n/**\n * Regular expression for finding a hash mark or end of string.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.hashOrEndRe_ = /#|$/;\n\n\n/**\n * Determines if the URI contains a specific key.\n *\n * Performs no object instantiations.\n *\n * @param {string} uri The URI to process. May contain a fragment\n * identifier.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {boolean} Whether the key is present.\n */\ngoog.uri.utils.hasParam = function(uri, keyEncoded) {\n return goog.uri.utils.findParam_(\n uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;\n};\n\n\n/**\n * Gets the first value of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {?string} The first value of the parameter (URI-decoded), or null\n * if the parameter is not found.\n */\ngoog.uri.utils.getParamValue = function(uri, keyEncoded) {\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var foundIndex =\n goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);\n\n if (foundIndex < 0) {\n return null;\n } else {\n var endPosition = uri.indexOf('&', foundIndex);\n if (endPosition < 0 || endPosition > hashOrEndIndex) {\n endPosition = hashOrEndIndex;\n }\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n // Use substr, because it (unlike substring) will return empty string\n // if foundIndex > endPosition.\n return goog.string.urlDecode(\n uri.substr(foundIndex, endPosition - foundIndex));\n }\n};\n\n\n/**\n * Gets all values of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {!Array<string>} All URI-decoded values with the given key.\n * If the key is not found, this will have length 0, but never be null.\n */\ngoog.uri.utils.getParamValues = function(uri, keyEncoded) {\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var result = [];\n\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Find where this parameter ends, either the '&' or the end of the\n // query parameters.\n position = uri.indexOf('&', foundIndex);\n if (position < 0 || position > hashOrEndIndex) {\n position = hashOrEndIndex;\n }\n\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n // Use substr, because it (unlike substring) will return empty string\n // if foundIndex > position.\n result.push(\n goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex)));\n }\n\n return result;\n};\n\n\n/**\n * Regexp to find trailing question marks and ampersands.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;\n\n\n/**\n * Removes all instances of a query parameter.\n * @param {string} uri The URI to process. Must not contain a fragment.\n * @param {string} keyEncoded The URI-encoded key.\n * @return {string} The URI with all instances of the parameter removed.\n */\ngoog.uri.utils.removeParam = function(uri, keyEncoded) {\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var buffer = [];\n\n // Look for a query parameter.\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Get the portion of the query string up to, but not including, the ?\n // or & starting the parameter.\n buffer.push(uri.substring(position, foundIndex));\n // Progress to immediately after the '&'. If not found, go to the end.\n // Avoid including the hash mark.\n position = Math.min(\n (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);\n }\n\n // Append everything that is remaining.\n buffer.push(uri.substr(position));\n\n // Join the buffer, and remove trailing punctuation that remains.\n return buffer.join('').replace(\n goog.uri.utils.trailingQueryPunctuationRe_, '$1');\n};\n\n\n/**\n * Replaces all existing definitions of a parameter with a single definition.\n *\n * Repeated calls to this can exhibit quadratic behavior due to the need to\n * find existing instances and reconstruct the string, though it should be\n * limited given the 2kb limit. Consider using appendParams or setParamsFromMap\n * to update multiple parameters in bulk.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} keyEncoded The key, which must already be URI encoded.\n * @param {*} value The value, which will be stringized and encoded (assumed\n * not already to be encoded).\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.setParam = function(uri, keyEncoded, value) {\n return goog.uri.utils.appendParam(\n goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);\n};\n\n\n/**\n * Effeciently set or remove multiple query parameters in a URI. Order of\n * unchanged parameters will not be modified, all updated parameters will be\n * appended to the end of the query. Params with values of null or undefined are\n * removed.\n *\n * @param {string} uri The URI to process.\n * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of\n * parameters to update. If null or undefined, the param will be removed.\n * @return {string} An updated URI where the query data has been updated with\n * the params.\n */\ngoog.uri.utils.setParamsFromMap = function(uri, params) {\n var parts = goog.uri.utils.splitQueryData_(uri);\n var queryData = parts[1];\n var buffer = [];\n if (queryData) {\n goog.array.forEach(queryData.split('&'), function(pair) {\n var indexOfEquals = pair.indexOf('=');\n var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair;\n if (!params.hasOwnProperty(name)) {\n buffer.push(pair);\n }\n });\n }\n parts[1] = goog.uri.utils.appendQueryData_(\n buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Generates a URI path using a given URI and a path with checks to\n * prevent consecutive \"//\". The baseUri passed in must not contain\n * query or fragment identifiers. The path to append may not contain query or\n * fragment identifiers.\n *\n * @param {string} baseUri URI to use as the base.\n * @param {string} path Path to append.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.appendPath = function(baseUri, path) {\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\n\n // Remove any trailing '/'\n if (goog.string.endsWith(baseUri, '/')) {\n baseUri = baseUri.substr(0, baseUri.length - 1);\n }\n // Remove any leading '/'\n if (goog.string.startsWith(path, '/')) {\n path = path.substr(1);\n }\n return goog.string.buildString(baseUri, '/', path);\n};\n\n\n/**\n * Replaces the path.\n * @param {string} uri URI to use as the base.\n * @param {string} path New path.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.setPath = function(uri, path) {\n // Add any missing '/'.\n if (!goog.string.startsWith(path, '/')) {\n path = '/' + path;\n }\n var parts = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n parts[goog.uri.utils.ComponentIndex.SCHEME],\n parts[goog.uri.utils.ComponentIndex.USER_INFO],\n parts[goog.uri.utils.ComponentIndex.DOMAIN],\n parts[goog.uri.utils.ComponentIndex.PORT], path,\n parts[goog.uri.utils.ComponentIndex.QUERY_DATA],\n parts[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Standard supported query parameters.\n * @enum {string}\n */\ngoog.uri.utils.StandardQueryParam = {\n\n /** Unused parameter for unique-ifying. */\n RANDOM: 'zx'\n};\n\n\n/**\n * Sets the zx parameter of a URI to a random value.\n * @param {string} uri Any URI.\n * @return {string} That URI with the \"zx\" parameter added or replaced to\n * contain a random string.\n */\ngoog.uri.utils.makeUnique = function(uri) {\n return goog.uri.utils.setParam(\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\n goog.string.getRandomString());\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class for parsing and formatting URIs.\n *\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\n * create a new instance of the goog.Uri object from Uri parts.\n *\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\n *\n * Implements RFC 3986 for parsing/formatting URIs.\n * http://www.ietf.org/rfc/rfc3986.txt\n *\n * Some changes have been made to the interface (more like .NETs), though the\n * internal representation is now of un-encoded parts, this will change the\n * behavior slightly.\n */\n\ngoog.provide('goog.Uri');\ngoog.provide('goog.Uri.QueryData');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.string');\ngoog.require('goog.structs');\ngoog.require('goog.structs.Map');\ngoog.require('goog.uri.utils');\ngoog.require('goog.uri.utils.ComponentIndex');\ngoog.require('goog.uri.utils.StandardQueryParam');\n\n\n\n/**\n * This class contains setters and getters for the parts of the URI.\n * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part\n * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the\n * decoded path, <code>/foo bar</code>.\n *\n * Reserved characters (see RFC 3986 section 2.2) can be present in\n * their percent-encoded form in scheme, domain, and path URI components and\n * will not be auto-decoded. For example:\n * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will\n * return <code>relative/path%2fto/resource</code>.\n *\n * The constructor accepts an optional unparsed, raw URI string. The parser\n * is relaxed, so special characters that aren't escaped but don't cause\n * ambiguities will not cause parse failures.\n *\n * All setters return <code>this</code> and so may be chained, a la\n * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.\n *\n * @param {*=} opt_uri Optional string URI to parse\n * (use goog.Uri.create() to create a URI from parts), or if\n * a goog.Uri is passed, a clone is created.\n * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore\n * the case of the parameter name.\n *\n * @throws URIError If opt_uri is provided and URI is malformed (that is,\n * if decodeURIComponent fails on any of the URI components).\n * @constructor\n * @struct\n */\ngoog.Uri = function(opt_uri, opt_ignoreCase) {\n /**\n * Scheme such as \"http\".\n * @private {string}\n */\n this.scheme_ = '';\n\n /**\n * User credentials in the form \"username:password\".\n * @private {string}\n */\n this.userInfo_ = '';\n\n /**\n * Domain part, e.g. \"www.google.com\".\n * @private {string}\n */\n this.domain_ = '';\n\n /**\n * Port, e.g. 8080.\n * @private {?number}\n */\n this.port_ = null;\n\n /**\n * Path, e.g. \"/tests/img.png\".\n * @private {string}\n */\n this.path_ = '';\n\n /**\n * The fragment without the #.\n * @private {string}\n */\n this.fragment_ = '';\n\n /**\n * Whether or not this Uri should be treated as Read Only.\n * @private {boolean}\n */\n this.isReadOnly_ = false;\n\n /**\n * Whether or not to ignore case when comparing query params.\n * @private {boolean}\n */\n this.ignoreCase_ = false;\n\n /**\n * Object representing query data.\n * @private {!goog.Uri.QueryData}\n */\n this.queryData_;\n\n // Parse in the uri string\n var m;\n if (opt_uri instanceof goog.Uri) {\n this.ignoreCase_ = (opt_ignoreCase !== undefined) ? opt_ignoreCase :\n opt_uri.getIgnoreCase();\n this.setScheme(opt_uri.getScheme());\n this.setUserInfo(opt_uri.getUserInfo());\n this.setDomain(opt_uri.getDomain());\n this.setPort(opt_uri.getPort());\n this.setPath(opt_uri.getPath());\n this.setQueryData(opt_uri.getQueryData().clone());\n this.setFragment(opt_uri.getFragment());\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\n this.ignoreCase_ = !!opt_ignoreCase;\n\n // Set the parts -- decoding as we do so.\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\n // whereas in other browsers they will be undefined.\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\n\n } else {\n this.ignoreCase_ = !!opt_ignoreCase;\n this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_);\n }\n};\n\n\n/**\n * Parameter name added to stop caching.\n * @type {string}\n */\ngoog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;\n\n\n/**\n * @return {string} The string form of the url.\n * @override\n */\ngoog.Uri.prototype.toString = function() {\n var out = [];\n\n var scheme = this.getScheme();\n if (scheme) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n ':');\n }\n\n var domain = this.getDomain();\n if (domain || scheme == 'file') {\n out.push('//');\n\n var userInfo = this.getUserInfo();\n if (userInfo) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n '@');\n }\n\n out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));\n\n var port = this.getPort();\n if (port != null) {\n out.push(':', String(port));\n }\n }\n\n var path = this.getPath();\n if (path) {\n if (this.hasDomain() && path.charAt(0) != '/') {\n out.push('/');\n }\n out.push(\n goog.Uri.encodeSpecialChars_(\n path, path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :\n goog.Uri.reDisallowedInRelativePath_,\n true));\n }\n\n var query = this.getEncodedQuery();\n if (query) {\n out.push('?', query);\n }\n\n var fragment = this.getFragment();\n if (fragment) {\n out.push(\n '#', goog.Uri.encodeSpecialChars_(\n fragment, goog.Uri.reDisallowedInFragment_));\n }\n return out.join('');\n};\n\n\n/**\n * Resolves the given relative URI (a goog.Uri object), using the URI\n * represented by this instance as the base URI.\n *\n * There are several kinds of relative URIs:<br>\n * 1. foo - replaces the last part of the path, the whole query and fragment<br>\n * 2. /foo - replaces the path, the query and fragment<br>\n * 3. //foo - replaces everything from the domain on. foo is a domain name<br>\n * 4. ?foo - replace the query and fragment<br>\n * 5. #foo - replace the fragment only\n *\n * Additionally, if relative URI has a non-empty path, all \"..\" and \".\"\n * segments will be resolved, as described in RFC 3986.\n *\n * @param {!goog.Uri} relativeUri The relative URI to resolve.\n * @return {!goog.Uri} The resolved URI.\n */\ngoog.Uri.prototype.resolve = function(relativeUri) {\n\n var absoluteUri = this.clone();\n\n // we satisfy these conditions by looking for the first part of relativeUri\n // that is not blank and applying defaults to the rest\n\n var overridden = relativeUri.hasScheme();\n\n if (overridden) {\n absoluteUri.setScheme(relativeUri.getScheme());\n } else {\n overridden = relativeUri.hasUserInfo();\n }\n\n if (overridden) {\n absoluteUri.setUserInfo(relativeUri.getUserInfo());\n } else {\n overridden = relativeUri.hasDomain();\n }\n\n if (overridden) {\n absoluteUri.setDomain(relativeUri.getDomain());\n } else {\n overridden = relativeUri.hasPort();\n }\n\n var path = relativeUri.getPath();\n if (overridden) {\n absoluteUri.setPort(relativeUri.getPort());\n } else {\n overridden = relativeUri.hasPath();\n if (overridden) {\n // resolve path properly\n if (path.charAt(0) != '/') {\n // path is relative\n if (this.hasDomain() && !this.hasPath()) {\n // RFC 3986, section 5.2.3, case 1\n path = '/' + path;\n } else {\n // RFC 3986, section 5.2.3, case 2\n var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');\n if (lastSlashIndex != -1) {\n path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;\n }\n }\n }\n path = goog.Uri.removeDotSegments(path);\n }\n }\n\n if (overridden) {\n absoluteUri.setPath(path);\n } else {\n overridden = relativeUri.hasQuery();\n }\n\n if (overridden) {\n absoluteUri.setQueryData(relativeUri.getQueryData().clone());\n } else {\n overridden = relativeUri.hasFragment();\n }\n\n if (overridden) {\n absoluteUri.setFragment(relativeUri.getFragment());\n }\n\n return absoluteUri;\n};\n\n\n/**\n * Clones the URI instance.\n * @return {!goog.Uri} New instance of the URI object.\n */\ngoog.Uri.prototype.clone = function() {\n return new goog.Uri(this);\n};\n\n\n/**\n * @return {string} The encoded scheme/protocol for the URI.\n */\ngoog.Uri.prototype.getScheme = function() {\n return this.scheme_;\n};\n\n\n/**\n * Sets the scheme/protocol.\n * @throws URIError If opt_decode is true and newScheme is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newScheme New scheme value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setScheme = function(newScheme, opt_decode) {\n this.enforceReadOnly();\n this.scheme_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;\n\n // remove an : at the end of the scheme so somebody can pass in\n // window.location.protocol\n if (this.scheme_) {\n this.scheme_ = this.scheme_.replace(/:$/, '');\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the scheme has been set.\n */\ngoog.Uri.prototype.hasScheme = function() {\n return !!this.scheme_;\n};\n\n\n/**\n * @return {string} The decoded user info.\n */\ngoog.Uri.prototype.getUserInfo = function() {\n return this.userInfo_;\n};\n\n\n/**\n * Sets the userInfo.\n * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newUserInfo New userInfo value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {\n this.enforceReadOnly();\n this.userInfo_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the user info has been set.\n */\ngoog.Uri.prototype.hasUserInfo = function() {\n return !!this.userInfo_;\n};\n\n\n/**\n * @return {string} The decoded domain.\n */\ngoog.Uri.prototype.getDomain = function() {\n return this.domain_;\n};\n\n\n/**\n * Sets the domain.\n * @throws URIError If opt_decode is true and newDomain is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newDomain New domain value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setDomain = function(newDomain, opt_decode) {\n this.enforceReadOnly();\n this.domain_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the domain has been set.\n */\ngoog.Uri.prototype.hasDomain = function() {\n return !!this.domain_;\n};\n\n\n/**\n * @return {?number} The port number.\n */\ngoog.Uri.prototype.getPort = function() {\n return this.port_;\n};\n\n\n/**\n * Sets the port number.\n * @param {*} newPort Port number. Will be explicitly casted to a number.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPort = function(newPort) {\n this.enforceReadOnly();\n\n if (newPort) {\n newPort = Number(newPort);\n if (isNaN(newPort) || newPort < 0) {\n throw new Error('Bad port number ' + newPort);\n }\n this.port_ = newPort;\n } else {\n this.port_ = null;\n }\n\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the port has been set.\n */\ngoog.Uri.prototype.hasPort = function() {\n return this.port_ != null;\n};\n\n\n/**\n * @return {string} The decoded path.\n */\ngoog.Uri.prototype.getPath = function() {\n return this.path_;\n};\n\n\n/**\n * Sets the path.\n * @throws URIError If opt_decode is true and newPath is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newPath New path value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPath = function(newPath, opt_decode) {\n this.enforceReadOnly();\n this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the path has been set.\n */\ngoog.Uri.prototype.hasPath = function() {\n return !!this.path_;\n};\n\n\n/**\n * @return {boolean} Whether the query string has been set.\n */\ngoog.Uri.prototype.hasQuery = function() {\n return this.queryData_.toString() !== '';\n};\n\n\n/**\n * Sets the query data.\n * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * Applies only if queryData is a string.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQueryData = function(queryData, opt_decode) {\n this.enforceReadOnly();\n\n if (queryData instanceof goog.Uri.QueryData) {\n this.queryData_ = queryData;\n this.queryData_.setIgnoreCase(this.ignoreCase_);\n } else {\n if (!opt_decode) {\n // QueryData accepts encoded query string, so encode it if\n // opt_decode flag is not true.\n queryData = goog.Uri.encodeSpecialChars_(\n queryData, goog.Uri.reDisallowedInQuery_);\n }\n this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_);\n }\n\n return this;\n};\n\n\n/**\n * Sets the URI query.\n * @param {string} newQuery New query value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQuery = function(newQuery, opt_decode) {\n return this.setQueryData(newQuery, opt_decode);\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getEncodedQuery = function() {\n return this.queryData_.toString();\n};\n\n\n/**\n * @return {string} The decoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getDecodedQuery = function() {\n return this.queryData_.toDecodedString();\n};\n\n\n/**\n * Returns the query data.\n * @return {!goog.Uri.QueryData} QueryData object.\n */\ngoog.Uri.prototype.getQueryData = function() {\n return this.queryData_;\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n *\n * Warning: This method, unlike other getter methods, returns encoded\n * value, instead of decoded one.\n */\ngoog.Uri.prototype.getQuery = function() {\n return this.getEncodedQuery();\n};\n\n\n/**\n * Sets the value of the named query parameters, clearing previous values for\n * that key.\n *\n * @param {string} key The parameter to set.\n * @param {*} value The new value. Value does not need to be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValue = function(key, value) {\n this.enforceReadOnly();\n this.queryData_.set(key, value);\n return this;\n};\n\n\n/**\n * Sets the values of the named query parameters, clearing previous values for\n * that key. Not new values will currently be moved to the end of the query\n * string.\n *\n * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])\n * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>\n *\n * @param {string} key The parameter to set.\n * @param {*} values The new values. If values is a single\n * string then it will be treated as the sole value. Values do not need to\n * be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValues = function(key, values) {\n this.enforceReadOnly();\n\n if (!Array.isArray(values)) {\n values = [String(values)];\n }\n\n this.queryData_.setValues(key, values);\n\n return this;\n};\n\n\n/**\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\n * query parameter values.\n * @param {string} name The parameter to get values for.\n * @return {!Array<?>} The values for a given cgi parameter as a list of\n * decoded query parameter values.\n */\ngoog.Uri.prototype.getParameterValues = function(name) {\n return this.queryData_.getValues(name);\n};\n\n\n/**\n * Returns the first value for a given cgi parameter or undefined if the given\n * parameter name does not appear in the query string.\n * @param {string} paramName Unescaped parameter name.\n * @return {string|undefined} The first value for a given cgi parameter or\n * undefined if the given parameter name does not appear in the query\n * string.\n */\ngoog.Uri.prototype.getParameterValue = function(paramName) {\n return /** @type {string|undefined} */ (this.queryData_.get(paramName));\n};\n\n\n/**\n * @return {string} The URI fragment, not including the #.\n */\ngoog.Uri.prototype.getFragment = function() {\n return this.fragment_;\n};\n\n\n/**\n * Sets the URI fragment.\n * @throws URIError If opt_decode is true and newFragment is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newFragment New fragment value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setFragment = function(newFragment, opt_decode) {\n this.enforceReadOnly();\n this.fragment_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI has a fragment set.\n */\ngoog.Uri.prototype.hasFragment = function() {\n return !!this.fragment_;\n};\n\n\n/**\n * Returns true if this has the same domain as that of uri2.\n * @param {!goog.Uri} uri2 The URI object to compare to.\n * @return {boolean} true if same domain; false otherwise.\n */\ngoog.Uri.prototype.hasSameDomainAs = function(uri2) {\n return ((!this.hasDomain() && !uri2.hasDomain()) ||\n this.getDomain() == uri2.getDomain()) &&\n ((!this.hasPort() && !uri2.hasPort()) ||\n this.getPort() == uri2.getPort());\n};\n\n\n/**\n * Adds a random parameter to the Uri.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.makeUnique = function() {\n this.enforceReadOnly();\n this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());\n\n return this;\n};\n\n\n/**\n * Removes the named query parameter.\n *\n * @param {string} key The parameter to remove.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.removeParameter = function(key) {\n this.enforceReadOnly();\n this.queryData_.remove(key);\n return this;\n};\n\n\n/**\n * Sets whether Uri is read only. If this goog.Uri is read-only,\n * enforceReadOnly_ will be called at the start of any function that may modify\n * this Uri.\n * @param {boolean} isReadOnly whether this goog.Uri should be read only.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setReadOnly = function(isReadOnly) {\n this.isReadOnly_ = isReadOnly;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI is read only.\n */\ngoog.Uri.prototype.isReadOnly = function() {\n return this.isReadOnly_;\n};\n\n\n/**\n * Checks if this Uri has been marked as read only, and if so, throws an error.\n * This should be called whenever any modifying function is called.\n */\ngoog.Uri.prototype.enforceReadOnly = function() {\n if (this.isReadOnly_) {\n throw new Error('Tried to modify a read-only Uri');\n }\n};\n\n\n/**\n * Sets whether to ignore case.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setIgnoreCase = function(ignoreCase) {\n this.ignoreCase_ = ignoreCase;\n if (this.queryData_) {\n this.queryData_.setIgnoreCase(ignoreCase);\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether to ignore case.\n */\ngoog.Uri.prototype.getIgnoreCase = function() {\n return this.ignoreCase_;\n};\n\n\n//==============================================================================\n// Static members\n//==============================================================================\n\n\n/**\n * Creates a uri from the string form. Basically an alias of new goog.Uri().\n * If a Uri object is passed to parse then it will return a clone of the object.\n *\n * @throws URIError If parsing the URI is malformed. The passed URI components\n * should all be parseable by decodeURIComponent.\n * @param {*} uri Raw URI string or instance of Uri\n * object.\n * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter\n * names in #getParameterValue.\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.parse = function(uri, opt_ignoreCase) {\n return uri instanceof goog.Uri ? uri.clone() :\n new goog.Uri(uri, opt_ignoreCase);\n};\n\n\n/**\n * Creates a new goog.Uri object from unencoded parts.\n *\n * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.\n * @param {?string=} opt_userInfo username:password.\n * @param {?string=} opt_domain www.google.com.\n * @param {?number=} opt_port 9830.\n * @param {?string=} opt_path /some/path/to/a/file.html.\n * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.\n * @param {?string=} opt_fragment The fragment without the #.\n * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in\n * #getParameterValue.\n *\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.create = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,\n opt_fragment, opt_ignoreCase) {\n\n var uri = new goog.Uri(null, opt_ignoreCase);\n\n // Only set the parts if they are defined and not empty strings.\n opt_scheme && uri.setScheme(opt_scheme);\n opt_userInfo && uri.setUserInfo(opt_userInfo);\n opt_domain && uri.setDomain(opt_domain);\n opt_port && uri.setPort(opt_port);\n opt_path && uri.setPath(opt_path);\n opt_query && uri.setQueryData(opt_query);\n opt_fragment && uri.setFragment(opt_fragment);\n\n return uri;\n};\n\n\n/**\n * Resolves a relative Uri against a base Uri, accepting both strings and\n * Uri objects.\n *\n * @param {*} base Base Uri.\n * @param {*} rel Relative Uri.\n * @return {!goog.Uri} Resolved uri.\n */\ngoog.Uri.resolve = function(base, rel) {\n if (!(base instanceof goog.Uri)) {\n base = goog.Uri.parse(base);\n }\n\n if (!(rel instanceof goog.Uri)) {\n rel = goog.Uri.parse(rel);\n }\n\n return base.resolve(rel);\n};\n\n\n/**\n * Removes dot segments in given path component, as described in\n * RFC 3986, section 5.2.4.\n *\n * @param {string} path A non-empty path component.\n * @return {string} Path component with removed dot segments.\n */\ngoog.Uri.removeDotSegments = function(path) {\n if (path == '..' || path == '.') {\n return '';\n\n } else if (\n !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {\n // This optimization detects uris which do not contain dot-segments,\n // and as a consequence do not require any processing.\n return path;\n\n } else {\n var leadingSlash = goog.string.startsWith(path, '/');\n var segments = path.split('/');\n var out = [];\n\n for (var pos = 0; pos < segments.length;) {\n var segment = segments[pos++];\n\n if (segment == '.') {\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else if (segment == '..') {\n if (out.length > 1 || out.length == 1 && out[0] != '') {\n out.pop();\n }\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else {\n out.push(segment);\n leadingSlash = true;\n }\n }\n\n return out.join('/');\n }\n};\n\n\n/**\n * Decodes a value or returns the empty string if it isn't defined or empty.\n * @throws URIError If decodeURIComponent fails to decode val.\n * @param {string|undefined} val Value to decode.\n * @param {boolean=} opt_preserveReserved If true, restricted characters will\n * not be decoded.\n * @return {string} Decoded value.\n * @private\n */\ngoog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {\n // Don't use UrlDecode() here because val is not a query parameter.\n if (!val) {\n return '';\n }\n\n // decodeURI has the same output for '%2f' and '%252f'. We double encode %25\n // so that we can distinguish between the 2 inputs. This is later undone by\n // removeDoubleEncoding_.\n return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :\n decodeURIComponent(val);\n};\n\n\n/**\n * If unescapedPart is non null, then escapes any characters in it that aren't\n * valid characters in a url and also escapes any special characters that\n * appear in extra.\n *\n * @param {*} unescapedPart The string to encode.\n * @param {RegExp} extra A character set of characters in [\\01-\\177].\n * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent\n * encoding.\n * @return {?string} null iff unescapedPart == null.\n * @private\n */\ngoog.Uri.encodeSpecialChars_ = function(\n unescapedPart, extra, opt_removeDoubleEncoding) {\n if (typeof unescapedPart === 'string') {\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\n if (opt_removeDoubleEncoding) {\n // encodeURI double-escapes %XX sequences used to represent restricted\n // characters in some URI components, remove the double escaping here.\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\n }\n return encoded;\n }\n return null;\n};\n\n\n/**\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\n * @param {string} ch One character string.\n * @return {string} Encoded string.\n * @private\n */\ngoog.Uri.encodeChar_ = function(ch) {\n var n = ch.charCodeAt(0);\n return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);\n};\n\n\n/**\n * Removes double percent-encoding from a string.\n * @param {string} doubleEncodedString String\n * @return {string} String with double encoding removed.\n * @private\n */\ngoog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {\n return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');\n};\n\n\n/**\n * Regular expression for characters that are disallowed in the scheme or\n * userInfo part of the URI.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\\/\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in a relative path.\n * Colon is included due to RFC 3986 3.3.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInRelativePath_ = /[\\#\\?:]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in an absolute path.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInAbsolutePath_ = /[\\#\\?]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the query.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInQuery_ = /[\\#\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the fragment.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInFragment_ = /#/g;\n\n\n/**\n * Checks whether two URIs have the same domain.\n * @param {string} uri1String First URI string.\n * @param {string} uri2String Second URI string.\n * @return {boolean} true if the two URIs have the same domain; false otherwise.\n */\ngoog.Uri.haveSameDomain = function(uri1String, uri2String) {\n // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.\n // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.\n var pieces1 = goog.uri.utils.split(uri1String);\n var pieces2 = goog.uri.utils.split(uri2String);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n\n/**\n * Class used to represent URI query parameters. It is essentially a hash of\n * name-value pairs, though a name can be present more than once.\n *\n * Has the same interface as the collections in goog.structs.\n *\n * @param {?string=} opt_query Optional encoded query string to parse into\n * the object.\n * @param {goog.Uri=} opt_uri Optional uri object that should have its\n * cache invalidated when this object updates. Deprecated -- this\n * is no longer required.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @constructor\n * @struct\n * @final\n */\ngoog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) {\n /**\n * The map containing name/value or name/array-of-values pairs.\n * May be null if it requires parsing from the query string.\n *\n * We need to use a Map because we cannot guarantee that the key names will\n * not be problematic for IE.\n *\n * @private {?goog.structs.Map<string, !Array<*>>}\n */\n this.keyMap_ = null;\n\n /**\n * The number of params, or null if it requires computing.\n * @private {?number}\n */\n this.count_ = null;\n\n /**\n * Encoded query string, or null if it requires computing from the key map.\n * @private {?string}\n */\n this.encodedQuery_ = opt_query || null;\n\n /**\n * If true, ignore the case of the parameter name in #get.\n * @private {boolean}\n */\n this.ignoreCase_ = !!opt_ignoreCase;\n};\n\n\n/**\n * If the underlying key map is not yet initialized, it parses the\n * query string and fills the map with parsed data.\n * @private\n */\ngoog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {\n if (!this.keyMap_) {\n this.keyMap_ = new goog.structs.Map();\n this.count_ = 0;\n if (this.encodedQuery_) {\n var self = this;\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\n self.add(goog.string.urlDecode(name), value);\n });\n }\n }\n};\n\n\n/**\n * Creates a new query data instance from a map of names and values.\n *\n * @param {!goog.structs.Map<string, ?>|!Object} map Map of string parameter\n * names to parameter value. If parameter value is an array, it is\n * treated as if the key maps to each individual value in the\n * array.\n * @param {goog.Uri=} opt_uri URI object that should have its cache\n * invalidated when this object updates.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) {\n var keys = goog.structs.getKeys(map);\n if (typeof keys == 'undefined') {\n throw new Error('Keys are undefined');\n }\n\n var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);\n var values = goog.structs.getValues(map);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = values[i];\n if (!Array.isArray(value)) {\n queryData.add(key, value);\n } else {\n queryData.setValues(key, value);\n }\n }\n return queryData;\n};\n\n\n/**\n * Creates a new query data instance from parallel arrays of parameter names\n * and values. Allows for duplicate parameter names. Throws an error if the\n * lengths of the arrays differ.\n *\n * @param {!Array<string>} keys Parameter names.\n * @param {!Array<?>} values Parameter values.\n * @param {goog.Uri=} opt_uri URI object that should have its cache\n * invalidated when this object updates.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromKeysValues = function(\n keys, values, opt_uri, opt_ignoreCase) {\n if (keys.length != values.length) {\n throw new Error('Mismatched lengths for keys/values');\n }\n var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);\n for (var i = 0; i < keys.length; i++) {\n queryData.add(keys[i], values[i]);\n }\n return queryData;\n};\n\n\n/**\n * @return {?number} The number of parameters.\n */\ngoog.Uri.QueryData.prototype.getCount = function() {\n this.ensureKeyMapInitialized_();\n return this.count_;\n};\n\n\n/**\n * Adds a key value pair.\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.add = function(key, value) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n key = this.getKeyName_(key);\n var values = this.keyMap_.get(key);\n if (!values) {\n this.keyMap_.set(key, (values = []));\n }\n values.push(value);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Removes all the params with the given key.\n * @param {string} key Name.\n * @return {boolean} Whether any parameter was removed.\n */\ngoog.Uri.QueryData.prototype.remove = function(key) {\n this.ensureKeyMapInitialized_();\n\n key = this.getKeyName_(key);\n if (this.keyMap_.containsKey(key)) {\n this.invalidateCache_();\n\n // Decrement parameter count.\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n return this.keyMap_.remove(key);\n }\n return false;\n};\n\n\n/**\n * Clears the parameters.\n */\ngoog.Uri.QueryData.prototype.clear = function() {\n this.invalidateCache_();\n this.keyMap_ = null;\n this.count_ = 0;\n};\n\n\n/**\n * @return {boolean} Whether we have any parameters.\n */\ngoog.Uri.QueryData.prototype.isEmpty = function() {\n this.ensureKeyMapInitialized_();\n return this.count_ == 0;\n};\n\n\n/**\n * Whether there is a parameter with the given name\n * @param {string} key The parameter name to check for.\n * @return {boolean} Whether there is a parameter with the given name.\n */\ngoog.Uri.QueryData.prototype.containsKey = function(key) {\n this.ensureKeyMapInitialized_();\n key = this.getKeyName_(key);\n return this.keyMap_.containsKey(key);\n};\n\n\n/**\n * Whether there is a parameter with the given value.\n * @param {*} value The value to check for.\n * @return {boolean} Whether there is a parameter with the given value.\n */\ngoog.Uri.QueryData.prototype.containsValue = function(value) {\n // NOTE(arv): This solution goes through all the params even if it was the\n // first param. We can get around this by not reusing code or by switching to\n // iterators.\n var vals = this.getValues();\n return goog.array.contains(vals, value);\n};\n\n\n/**\n * Runs a callback on every key-value pair in the map, including duplicate keys.\n * This won't maintain original order when duplicate keys are interspersed (like\n * getKeys() / getValues()).\n * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f\n * @param {SCOPE=} opt_scope The value of \"this\" inside f.\n * @template SCOPE\n */\ngoog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(values, key) {\n goog.array.forEach(values, function(value) {\n f.call(opt_scope, value, key, this);\n }, this);\n }, this);\n};\n\n\n/**\n * Returns all the keys of the parameters. If a key is used multiple times\n * it will be included multiple times in the returned array\n * @return {!Array<string>} All the keys of the parameters.\n */\ngoog.Uri.QueryData.prototype.getKeys = function() {\n this.ensureKeyMapInitialized_();\n // We need to get the values to know how many keys to add.\n var vals = this.keyMap_.getValues();\n var keys = this.keyMap_.getKeys();\n var rv = [];\n for (var i = 0; i < keys.length; i++) {\n var val = vals[i];\n for (var j = 0; j < val.length; j++) {\n rv.push(keys[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Returns all the values of the parameters with the given name. If the query\n * data has no such key this will return an empty array. If no key is given\n * all values wil be returned.\n * @param {string=} opt_key The name of the parameter to get the values for.\n * @return {!Array<?>} All the values of the parameters with the given name.\n */\ngoog.Uri.QueryData.prototype.getValues = function(opt_key) {\n this.ensureKeyMapInitialized_();\n var rv = [];\n if (typeof opt_key === 'string') {\n if (this.containsKey(opt_key)) {\n rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key)));\n }\n } else {\n // Return all values.\n var values = this.keyMap_.getValues();\n for (var i = 0; i < values.length; i++) {\n rv = goog.array.concat(rv, values[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Sets a key value pair and removes all other keys with the same value.\n *\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.set = function(key, value) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n // TODO(chrishenry): This could be better written as\n // this.remove(key), this.add(key, value), but that would reorder\n // the key (since the key is first removed and then added at the\n // end) and we would have to fix unit tests that depend on key\n // ordering.\n key = this.getKeyName_(key);\n if (this.containsKey(key)) {\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n }\n this.keyMap_.set(key, [value]);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Returns the first value associated with the key. If the query data has no\n * such key this will return undefined or the optional default.\n * @param {string} key The name of the parameter to get the value for.\n * @param {*=} opt_default The default value to return if the query data\n * has no such key.\n * @return {*} The first string value associated with the key, or opt_default\n * if there's no value.\n */\ngoog.Uri.QueryData.prototype.get = function(key, opt_default) {\n if (!key) {\n return opt_default;\n }\n var values = this.getValues(key);\n return values.length > 0 ? String(values[0]) : opt_default;\n};\n\n\n/**\n * Sets the values for a key. If the key already exists, this will\n * override all of the existing values that correspond to the key.\n * @param {string} key The key to set values for.\n * @param {!Array<?>} values The values to set.\n */\ngoog.Uri.QueryData.prototype.setValues = function(key, values) {\n this.remove(key);\n\n if (values.length > 0) {\n this.invalidateCache_();\n this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));\n this.count_ = goog.asserts.assertNumber(this.count_) + values.length;\n }\n};\n\n\n/**\n * @return {string} Encoded query string.\n * @override\n */\ngoog.Uri.QueryData.prototype.toString = function() {\n if (this.encodedQuery_) {\n return this.encodedQuery_;\n }\n\n if (!this.keyMap_) {\n return '';\n }\n\n var sb = [];\n\n // In the past, we use this.getKeys() and this.getVals(), but that\n // generates a lot of allocations as compared to simply iterating\n // over the keys.\n var keys = this.keyMap_.getKeys();\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var encodedKey = goog.string.urlEncode(key);\n var val = this.getValues(key);\n for (var j = 0; j < val.length; j++) {\n var param = encodedKey;\n // Ensure that null and undefined are encoded into the url as\n // literal strings.\n if (val[j] !== '') {\n param += '=' + goog.string.urlEncode(val[j]);\n }\n sb.push(param);\n }\n }\n\n return this.encodedQuery_ = sb.join('&');\n};\n\n\n/**\n * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on\n * any of the URI components).\n * @return {string} Decoded query string.\n */\ngoog.Uri.QueryData.prototype.toDecodedString = function() {\n return goog.Uri.decodeOrEmpty_(this.toString());\n};\n\n\n/**\n * Invalidate the cache.\n * @private\n */\ngoog.Uri.QueryData.prototype.invalidateCache_ = function() {\n this.encodedQuery_ = null;\n};\n\n\n/**\n * Removes all keys that are not in the provided list. (Modifies this object.)\n * @param {Array<string>} keys The desired keys.\n * @return {!goog.Uri.QueryData} a reference to this object.\n */\ngoog.Uri.QueryData.prototype.filterKeys = function(keys) {\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(value, key) {\n if (!goog.array.contains(keys, key)) {\n this.remove(key);\n }\n }, this);\n return this;\n};\n\n\n/**\n * Clone the query data instance.\n * @return {!goog.Uri.QueryData} New instance of the QueryData object.\n */\ngoog.Uri.QueryData.prototype.clone = function() {\n var rv = new goog.Uri.QueryData();\n rv.encodedQuery_ = this.encodedQuery_;\n if (this.keyMap_) {\n rv.keyMap_ = this.keyMap_.clone();\n rv.count_ = this.count_;\n }\n return rv;\n};\n\n\n/**\n * Helper function to get the key name from a JavaScript object. Converts\n * the object to a string, and to lower case if necessary.\n * @private\n * @param {*} arg The object to get a key name from.\n * @return {string} valid key name which can be looked up in #keyMap_.\n */\ngoog.Uri.QueryData.prototype.getKeyName_ = function(arg) {\n var keyName = String(arg);\n if (this.ignoreCase_) {\n keyName = keyName.toLowerCase();\n }\n return keyName;\n};\n\n\n/**\n * Ignore case in parameter names.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n */\ngoog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {\n var resetKeys = ignoreCase && !this.ignoreCase_;\n if (resetKeys) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n this.keyMap_.forEach(function(value, key) {\n var lowerCase = key.toLowerCase();\n if (key != lowerCase) {\n this.remove(key);\n this.setValues(lowerCase, value);\n }\n }, this);\n }\n this.ignoreCase_ = ignoreCase;\n};\n\n\n/**\n * Extends a query data object with another query data or map like object. This\n * operates 'in-place', it does not create a new QueryData object.\n *\n * @param {...(?goog.Uri.QueryData|?goog.structs.Map<?, ?>|?Object)} var_args\n * The object from which key value pairs will be copied. Note: does not\n * accept null.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters.\n */\ngoog.Uri.QueryData.prototype.extend = function(var_args) {\n for (var i = 0; i < arguments.length; i++) {\n var data = arguments[i];\n goog.structs.forEach(\n data, function(value, key) { this.add(key, value); }, this);\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.iframeclient.IfcHandler used to communicate\n * with the serverless widget.\n */\n\ngoog.provide('fireauth.iframeclient.IfcHandler');\ngoog.provide('fireauth.iframeclient.IframeUrlBuilder');\ngoog.provide('fireauth.iframeclient.OAuthUrlBuilder');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthEvent');\ngoog.require('fireauth.AuthProvider');\ngoog.require('fireauth.InvalidOriginError');\ngoog.require('fireauth.OAuthSignInHandler');\ngoog.require('fireauth.RpcHandler');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.iframeclient.IframeWrapper');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.Timer');\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n/**\n * The OAuth handler and iframe prototcol.\n * @const {string}\n * @suppress {const|duplicate}\n */\nfireauth.iframeclient.SCHEME = 'https';\n\n\n\n/**\n * The OAuth handler and iframe port number.\n * @const {?number}\n * @suppress {const|duplicate}\n */\nfireauth.iframeclient.PORT_NUMBER = null;\n\n\n\n/**\n * The iframe URL builder used to build the iframe widget URL.\n * @param {string} authDomain The application authDomain.\n * @param {string} apiKey The API key.\n * @param {string} appName The App name.\n * @constructor\n */\nfireauth.iframeclient.IframeUrlBuilder = function(authDomain, apiKey, appName) {\n /** @private {string} The application authDomain. */\n this.authDomain_ = authDomain;\n /** @private {string} The API key. */\n this.apiKey_ = apiKey;\n /** @private {string} The App name. */\n this.appName_ = appName;\n /** @private {?string|undefined} The client version. */\n this.v_ = null;\n /**\n * @private {!goog.Uri} The URI object used to build the iframe URL.\n */\n this.uri_ = goog.Uri.create(\n fireauth.iframeclient.SCHEME,\n null,\n this.authDomain_,\n fireauth.iframeclient.PORT_NUMBER,\n '/__/auth/iframe',\n null,\n null);\n this.uri_.setParameterValue('apiKey', this.apiKey_);\n this.uri_.setParameterValue('appName', this.appName_);\n /** @private {?string|undefined} The endpoint ID. */\n this.endpointId_ = null;\n /** @private {!Array<string>} The list of framework IDs. */\n this.frameworks_ = [];\n};\n\n\n/**\n * Sets the client version.\n * @param {?string|undefined} v The client version.\n * @return {!fireauth.iframeclient.IframeUrlBuilder} The current iframe URL\n * builder instance.\n */\nfireauth.iframeclient.IframeUrlBuilder.prototype.setVersion = function(v) {\n this.v_ = v;\n return this;\n};\n\n\n/**\n * Sets the endpoint ID.\n * @param {?string|undefined} eid The endpoint ID (staging, test Gaia, etc).\n * @return {!fireauth.iframeclient.IframeUrlBuilder} The current iframe URL\n * builder instance.\n */\nfireauth.iframeclient.IframeUrlBuilder.prototype.setEndpointId = function(eid) {\n this.endpointId_ = eid;\n return this;\n};\n\n\n/**\n * Sets the list of frameworks to pass to the iframe.\n * @param {?Array<string>|undefined} frameworks The list of frameworks to log.\n * @return {!fireauth.iframeclient.IframeUrlBuilder} The current iframe URL\n * builder instance.\n */\nfireauth.iframeclient.IframeUrlBuilder.prototype.setFrameworks =\n function(frameworks) {\n this.frameworks_ = goog.array.clone(frameworks || []);\n return this;\n};\n\n\n/**\n * Modifes the URI with the relevant Auth provider parameters.\n * @return {string} The constructed OAuth URL string.\n * @override\n */\nfireauth.iframeclient.IframeUrlBuilder.prototype.toString = function() {\n // Pass the client version if available.\n if (this.v_) {\n this.uri_.setParameterValue('v', this.v_);\n } else {\n this.uri_.removeParameter('v');\n }\n // Pass the endpoint ID if available.\n if (this.endpointId_) {\n this.uri_.setParameterValue('eid', this.endpointId_);\n } else {\n this.uri_.removeParameter('eid');\n }\n // Pass the list of frameworks if available.\n if (this.frameworks_.length) {\n this.uri_.setParameterValue('fw', this.frameworks_.join(','));\n } else {\n this.uri_.removeParameter('fw');\n }\n return this.uri_.toString();\n};\n\n\n\n/**\n * The OAuth URL builder used to build the OAuth handler widget URL.\n * @param {string} authDomain The application authDomain.\n * @param {string} apiKey The API key.\n * @param {string} appName The App name.\n * @param {string} authType The Auth operation type.\n * @param {!fireauth.AuthProvider} provider The Auth provider that the OAuth\n * handler request is built to sign in to.\n * @constructor\n */\nfireauth.iframeclient.OAuthUrlBuilder =\n function(authDomain, apiKey, appName, authType, provider) {\n /** @private {string} The application authDomain. */\n this.authDomain_ = authDomain;\n /** @private {string} The API key. */\n this.apiKey_ = apiKey;\n /** @private {string} The App name. */\n this.appName_ = appName;\n /** @private {string} The Auth operation type. */\n this.authType_ = authType;\n /**\n * @private {?string|undefined} The redirect URL used in redirect operations.\n */\n this.redirectUrl_ = null;\n /** @private {?string|undefined} The event ID. */\n this.eventId_ = null;\n /** @private {?string|undefined} The client version. */\n this.v_ = null;\n /**\n * @private {!fireauth.AuthProvider} The Firebase Auth provider that the OAuth\n * handler request is built to sign in to.\n */\n this.provider_ = provider;\n /** @private {?string|undefined} The endpoint ID. */\n this.endpointId_ = null;\n /** @private {?string|undefined} The tenant ID. */\n this.tenantId_ = null;\n};\n\n\n/**\n * Sets the redirect URL.\n * @param {?string|undefined} redirectUrl The redirect URL used in redirect\n * operations.\n * @return {!fireauth.iframeclient.OAuthUrlBuilder} The current OAuth URL\n * builder instance.\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.setRedirectUrl =\n function(redirectUrl) {\n this.redirectUrl_ = redirectUrl;\n return this;\n};\n\n\n/**\n * Sets the event ID.\n * @param {?string|undefined} eventId The event ID.\n * @return {!fireauth.iframeclient.OAuthUrlBuilder} The current OAuth URL\n * builder instance.\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.setEventId = function(eventId) {\n this.eventId_ = eventId;\n return this;\n};\n\n\n/**\n * Sets the tenant ID.\n * @param {?string|undefined} tenantId The event ID.\n * @return {!fireauth.iframeclient.OAuthUrlBuilder} The current OAuth URL\n * builder instance.\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.setTenantId =\n function(tenantId) {\n this.tenantId_ = tenantId;\n return this;\n};\n\n\n/**\n * Sets the client version.\n * @param {?string|undefined} v The client version.\n * @return {!fireauth.iframeclient.OAuthUrlBuilder} The current OAuth URL\n * builder instance.\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.setVersion = function(v) {\n this.v_ = v;\n return this;\n};\n\n\n/**\n * Sets the endpoint ID.\n * @param {?string|undefined} eid The endpoint ID (staging, test Gaia, etc).\n * @return {!fireauth.iframeclient.OAuthUrlBuilder} The current OAuth URL\n * builder instance.\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.setEndpointId = function(eid) {\n this.endpointId_ = eid;\n return this;\n};\n\n\n/**\n * Sets any additional optional parameters. This will overwrite any previously\n * set additional parameters.\n * @param {?Object<string, string>|undefined} additionalParams The optional\n * additional parameters.\n * @return {!fireauth.iframeclient.OAuthUrlBuilder} The current OAuth URL\n * builder instance.\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.setAdditionalParameters =\n function(additionalParams) {\n this.additionalParams_ = goog.object.clone(additionalParams || null);\n return this;\n};\n\n\n/**\n * Modifies the URI with the relevant Auth provider parameters.\n * @return {string} The constructed OAuth URL string.\n * @override\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.toString = function() {\n var uri = goog.Uri.create(\n fireauth.iframeclient.SCHEME,\n null,\n this.authDomain_,\n fireauth.iframeclient.PORT_NUMBER,\n '/__/auth/handler',\n null,\n null);\n uri.setParameterValue('apiKey', this.apiKey_);\n uri.setParameterValue('appName', this.appName_);\n uri.setParameterValue('authType', this.authType_);\n\n // Add custom parameters for OAuth1/OAuth2 providers.\n if (this.provider_['isOAuthProvider']) {\n // Set default language if available and no language already set.\n /** @type {!fireauth.FederatedProvider} */ (this.provider_)\n .setDefaultLanguage(this.getAuthLanguage_());\n uri.setParameterValue('providerId', this.provider_['providerId']);\n var customParameters = /** @type {!fireauth.FederatedProvider} */ (\n this.provider_).getCustomParameters();\n if (!goog.object.isEmpty(customParameters)) {\n uri.setParameterValue(\n 'customParameters',\n /** @type {string} */ (fireauth.util.stringifyJSON(customParameters))\n );\n }\n }\n\n // Add scopes for OAuth2 providers.\n if (typeof this.provider_.getScopes === 'function') {\n var scopes = this.provider_.getScopes();\n if (scopes.length) {\n uri.setParameterValue('scopes', scopes.join(','));\n }\n }\n\n if (this.redirectUrl_) {\n uri.setParameterValue('redirectUrl', this.redirectUrl_);\n } else {\n uri.removeParameter('redirectUrl');\n }\n if (this.eventId_) {\n uri.setParameterValue('eventId', this.eventId_);\n } else {\n uri.removeParameter('eventId');\n }\n // Pass the client version if available.\n if (this.v_) {\n uri.setParameterValue('v', this.v_);\n } else {\n uri.removeParameter('v');\n }\n if (this.additionalParams_) {\n for (var key in this.additionalParams_) {\n if (this.additionalParams_.hasOwnProperty(key) &&\n // Don't overwrite other existing parameters.\n !uri.getParameterValue(key)) {\n uri.setParameterValue(key, this.additionalParams_[key]);\n }\n }\n }\n // Pass the tenant ID if available.\n if (this.tenantId_) {\n uri.setParameterValue('tid', this.tenantId_);\n } else {\n uri.removeParameter('tid');\n }\n // Pass the endpoint ID if available.\n if (this.endpointId_) {\n uri.setParameterValue('eid', this.endpointId_);\n } else {\n uri.removeParameter('eid');\n }\n // Append any framework IDs to the handler URL to log in handler RPC requests.\n var frameworks = this.getAuthFrameworks_();\n if (frameworks.length) {\n uri.setParameterValue('fw', frameworks.join(','));\n }\n return uri.toString();\n};\n\n\n/**\n * Returns the current Auth instance's language code.\n * @return {?string} The corresponding language code.\n * @private\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.getAuthLanguage_ = function() {\n try {\n // Get the Auth instance for the current App identified by the App name.\n // This could fail if, for example, the App instance was deleted.\n return firebase['app'](this.appName_)['auth']().getLanguageCode();\n } catch (e) {\n return null;\n }\n};\n\n\n/**\n * Returns the list of Firebase frameworks used for logging purposes.\n * @return {!Array<string>} The list of corresponding Firebase frameworks.\n * @private\n */\nfireauth.iframeclient.OAuthUrlBuilder.prototype.getAuthFrameworks_ =\n function() {\n return fireauth.iframeclient.OAuthUrlBuilder.getAuthFrameworksForApp_(\n this.appName_);\n};\n\n\n/**\n * Returns the list of Firebase frameworks used for logging purposes\n * corresponding to the Firebase App name provided.\n * @param {string} appName The Firebase App name.\n * @return {!Array<string>} The list of corresponding Firebase frameworks.\n * @private\n */\nfireauth.iframeclient.OAuthUrlBuilder.getAuthFrameworksForApp_ =\n function(appName) {\n try {\n // Get the Auth instance's list of Firebase framework IDs for the current\n // App identified by the App name.\n // This could fail if, for example, the App instance was deleted.\n return firebase['app'](appName)['auth']().getFramework();\n } catch (e) {\n return [];\n }\n};\n\n\n\n/**\n * Initializes the ifcHandler which provides the mechanism to listen to Auth\n * events on the hidden iframe.\n * @param {string} authDomain The firebase authDomain used to determine the\n * OAuth helper page domain.\n * @param {string} apiKey The API key for sending backend Auth requests.\n * @param {string} appName The App ID for the Auth instance that triggered this\n * request.\n * @param {?string=} opt_clientVersion The optional client version string.\n * @param {?string=} opt_endpointId The endpoint ID (staging, test Gaia, etc).\n * @constructor\n * @implements {fireauth.OAuthSignInHandler}\n */\nfireauth.iframeclient.IfcHandler = function(authDomain, apiKey, appName,\n opt_clientVersion, opt_endpointId) {\n /** @private {string} The Auth domain. */\n this.authDomain_ = authDomain;\n /** @private {string} The API key. */\n this.apiKey_ = apiKey;\n /** @private {string} The App name. */\n this.appName_ = appName;\n /** @private {?string} The client version. */\n this.clientVersion_ = opt_clientVersion || null;\n /** @private {?string} The Auth endpoint ID. */\n this.endpointId_ = opt_endpointId || null;\n // Delay RPC handler and iframe URL initialization until needed to ensure\n // logged frameworks are propagated to the iframe.\n /** @private {?string} The full client version string. */\n this.fullClientVersion_ = null;\n /** @private {?string} The iframe URL. */\n this.iframeUrl_ = null;\n /** @private {?fireauth.RpcHandler} The RPC handler for provided API key. */\n this.rpcHandler_ = null;\n /**\n * @private {!Array<!function(?fireauth.AuthEvent)>} The Auth event\n * listeners.\n */\n this.authEventListeners_ = [];\n // Delay origin validator determination until needed, so the error is not\n // thrown in the background. This will also prevent the getProjectConfig RPC\n // until it is required.\n /** @private {?goog.Promise} The origin validator. */\n this.originValidator_ = null;\n /** @private {?goog.Promise} The initialization promise. */\n this.isInitialized_ = null;\n};\n\n\n/**\n * Validates the provided URL.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler used to validate the\n * requested origin.\n * @param {string=} opt_origin The optional page origin. If not provided, the\n * window.location.href value is used.\n * @return {!goog.Promise} The promise that resolves if the provided origin is\n * valid.\n * @private\n */\nfireauth.iframeclient.IfcHandler.getOriginValidator_ =\n function(rpcHandler, opt_origin) {\n var origin = opt_origin || fireauth.util.getCurrentUrl();\n return rpcHandler.getAuthorizedDomains().then(function(authorizedDomains) {\n if (!fireauth.util.isAuthorizedDomain(authorizedDomains, origin)) {\n throw new fireauth.InvalidOriginError(fireauth.util.getCurrentUrl());\n }\n });\n};\n\n\n/**\n * Initializes the iframe client wrapper.\n * @return {!goog.Promise} The promise that resolves on initialization.\n */\nfireauth.iframeclient.IfcHandler.prototype.initialize = function() {\n // Already initialized.\n if (this.isInitialized_) {\n return this.isInitialized_;\n }\n var self = this;\n this.isInitialized_ = fireauth.util.onDomReady().then(function() {\n /**\n * @private {!fireauth.iframeclient.IframeWrapper} The iframe wrapper\n * instance.\n */\n self.iframeWrapper_ = new fireauth.iframeclient.IframeWrapper(\n self.getIframeUrl());\n // Register all event listeners to Auth event messages sent from Auth\n // iframe.\n self.registerEvents_();\n });\n return this.isInitialized_;\n};\n\n\n/**\n * Waits for popup window to close. When closed start timeout listener for popup\n * pending promise. If in the process, it was detected that the iframe does not\n * support web storage, the popup is closed and the web storage unsupported\n * error is thrown.\n * @param {!Window} popupWin The popup window.\n * @param {!function(!fireauth.AuthError)} onError The on error callback.\n * @param {number} timeoutDuration The time to wait in ms after the popup is\n * closed before triggering the popup closed by user error.\n * @return {!goog.Promise}\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.startPopupTimeout =\n function(popupWin, onError, timeoutDuration) {\n // Expire pending timeout promise for popup operation.\n var popupClosedByUserError = new fireauth.AuthError(\n fireauth.authenum.Error.POPUP_CLOSED_BY_USER);\n // If web storage is disabled in the iframe, expire popup timeout quickly with\n // this error.\n var webStorageNotSupportedError = new fireauth.AuthError(\n fireauth.authenum.Error.WEB_STORAGE_UNSUPPORTED);\n var self = this;\n var isResolved = false;\n // Wait for the iframe to be ready first.\n return this.initializeAndWait().then(function() {\n // We do not return isWebStorageSupported() to ensure that this is backward\n // compatible.\n // Pushing the following client changes before updating the iframe to\n // respond to these events would continue to work.\n // The downside is that the popup could be closed before this resolves.\n // In that case, they would get an error that the popup was closed and not\n // the error that web storage is not supported, though that is unlikely\n // as isWebStorageSupported should execute faster than the popup timeout.\n // If web storage is not supported in the iframe, fail quickly.\n self.isWebStorageSupported().then(function(isSupported) {\n if (!isSupported) {\n // If not supported, close window.\n if (popupWin) {\n fireauth.util.closeWindow(popupWin);\n }\n onError(webStorageNotSupportedError);\n isResolved = true;\n }\n });\n }).thenCatch(function(error) {\n // Ignore any possible error in iframe embedding.\n // These types of errors will be handled in processPopup which will close\n // the popup too if that happens.\n return;\n }).then(function() {\n // Skip if already resolved.\n if (isResolved) {\n return;\n }\n // After the iframe is ready, wait for popup to close and then start timeout\n // check.\n return fireauth.util.onPopupClose(popupWin);\n }).then(function() {\n // Skip if already resolved.\n if (isResolved) {\n return;\n }\n return goog.Timer.promise(timeoutDuration).then(function() {\n // If this is already resolved or rejected, this will do nothing.\n onError(popupClosedByUserError);\n });\n });\n};\n\n\n/**\n * @return {boolean} Whether the handler should be initialized early.\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.shouldBeInitializedEarly =\n function() {\n var ua = fireauth.util.getUserAgentString();\n // Cannot run in the background (can't wait for iframe to be embedded\n // before triggering popup redirect) and is Safari (can only detect\n // localStorage in iframe via change event) => embed iframe ASAP.\n // Do the same for mobile browsers on iOS devices as they use the same\n // Safari implementation underneath.\n return !fireauth.util.runsInBackground(ua) &&\n !fireauth.util.iframeCanSyncWebStorage(ua);\n};\n\n\n/**\n * @return {boolean} Whether the sign-in handler in the current environment\n * has volatile session storage.\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.hasVolatileStorage = function() {\n // Web environment with web storage enabled has stable sessionStorage.\n return false;\n};\n\n\n/**\n * Processes the popup request. The popup instance must be provided externally\n * and on error, the requestor must close the window.\n * @param {?Window} popupWin The popup window reference.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {function()} onInitialize The function to call on initialization.\n * @param {function(*)} onError The function to call on error.\n * @param {string=} opt_eventId The optional event ID.\n * @param {boolean=} opt_alreadyRedirected Whether popup is already redirected\n * to final destination.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {!goog.Promise} The popup window promise.\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.processPopup = function(\n popupWin,\n mode,\n provider,\n onInitialize,\n onError,\n opt_eventId,\n opt_alreadyRedirected,\n opt_tenantId) {\n // processPopup is failing since it tries to access popup win when tab can\n // not run in background. For now bypass processPopup which runs\n // additional origin check not accounted above. Besides, iframe will never\n // hand result to parent if origin not whitelisted.\n // Error thrown by browser: Unable to establish a connection with the\n // popup. It may have been blocked by the browser.\n // If popup is null, startPopupTimeout will catch it without having the\n // above error getting triggered due to popup access from opener.\n\n // Reject immediately if the popup is blocked.\n if (!popupWin) {\n return goog.Promise.reject(\n new fireauth.AuthError(fireauth.authenum.Error.POPUP_BLOCKED));\n }\n // Already redirected and cannot run in the background, resolve quickly while\n // initializing.\n if (opt_alreadyRedirected && !fireauth.util.runsInBackground()) {\n // Initialize first before resolving.\n this.initializeAndWait().thenCatch(function(error) {\n fireauth.util.closeWindow(popupWin);\n onError(error);\n });\n onInitialize();\n // Already redirected.\n return goog.Promise.resolve();\n }\n // If origin validator not determined yet.\n if (!this.originValidator_) {\n this.originValidator_ =\n fireauth.iframeclient.IfcHandler.getOriginValidator_(\n this.getRpcHandler_());\n }\n var self = this;\n return this.originValidator_.then(function() {\n // After origin validation, wait for iframe to be ready before redirecting.\n var onReady = self.initializeAndWait().thenCatch(function(error) {\n fireauth.util.closeWindow(popupWin);\n onError(error);\n throw error;\n });\n onInitialize();\n return onReady;\n }).then(function() {\n // Popup and redirect operations work for OAuth providers only.\n fireauth.AuthProvider.checkIfOAuthSupported(provider);\n // Already redirected to intended destination, no need to redirect again.\n if (opt_alreadyRedirected) {\n return;\n }\n var oauthHelperWidgetUrl =\n fireauth.iframeclient.IfcHandler.getOAuthHelperWidgetUrl(\n self.authDomain_,\n self.apiKey_,\n self.appName_,\n mode,\n provider,\n null,\n opt_eventId,\n self.clientVersion_,\n undefined,\n self.endpointId_,\n opt_tenantId);\n // Redirect popup to OAuth helper widget URL.\n fireauth.util.goTo(oauthHelperWidgetUrl, /** @type {!Window} */ (popupWin));\n }).thenCatch(function(e) {\n // Force another origin validation.\n if (e.code == 'auth/network-request-failed') {\n self.originValidator_ = null;\n }\n throw e;\n });\n};\n\n\n/**\n * @return {!fireauth.RpcHandler} The RPC handler instance with the relevant\n * endpoints, version and frameworks.\n * @private\n */\nfireauth.iframeclient.IfcHandler.prototype.getRpcHandler_ = function() {\n if (!this.rpcHandler_) {\n this.fullClientVersion_ = this.clientVersion_ ?\n fireauth.util.getClientVersion(\n fireauth.util.ClientImplementation.JSCORE,\n this.clientVersion_,\n fireauth.iframeclient.OAuthUrlBuilder.getAuthFrameworksForApp_(\n this.appName_)) :\n null;\n this.rpcHandler_ = new fireauth.RpcHandler(\n this.apiKey_,\n // Get the client Auth endpoint used.\n fireauth.constants.getEndpointConfig(this.endpointId_),\n this.fullClientVersion_);\n }\n return this.rpcHandler_;\n};\n\n\n/**\n * Processes the redirect request.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {?string=} opt_eventId The optional event ID.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {!goog.Promise}\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.processRedirect =\n function(mode, provider, opt_eventId, opt_tenantId) {\n // If origin validator not determined yet.\n if (!this.originValidator_) {\n this.originValidator_ =\n fireauth.iframeclient.IfcHandler.getOriginValidator_(\n this.getRpcHandler_());\n }\n var self = this;\n // Make sure origin is validated.\n return this.originValidator_.then(function() {\n fireauth.AuthProvider.checkIfOAuthSupported(provider);\n var oauthHelperWidgetUrl =\n fireauth.iframeclient.IfcHandler.getOAuthHelperWidgetUrl(\n self.authDomain_,\n self.apiKey_,\n self.appName_,\n mode,\n provider,\n fireauth.util.getCurrentUrl(),\n opt_eventId,\n self.clientVersion_,\n undefined,\n self.endpointId_,\n opt_tenantId);\n // Redirect to OAuth helper widget URL.\n fireauth.util.goTo(oauthHelperWidgetUrl);\n }).thenCatch(function(e) {\n // Force another origin validation on network errors.\n if (e.code == 'auth/network-request-failed') {\n self.originValidator_ = null;\n }\n throw e;\n });\n};\n\n\n/** @return {string} The iframe URL. */\nfireauth.iframeclient.IfcHandler.prototype.getIframeUrl = function() {\n if (!this.iframeUrl_) {\n this.iframeUrl_ = fireauth.iframeclient.IfcHandler.getAuthIframeUrl(\n this.authDomain_, this.apiKey_, this.appName_, this.clientVersion_,\n this.endpointId_,\n fireauth.iframeclient.OAuthUrlBuilder.getAuthFrameworksForApp_(\n this.appName_));\n }\n return this.iframeUrl_;\n};\n\n\n/**\n * @return {!goog.Promise} The promise that resolves when the iframe is ready.\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.initializeAndWait = function() {\n // Initialize if not initialized yet.\n var self = this;\n return this.initialize().then(function() {\n return self.iframeWrapper_.onReady();\n }).thenCatch(function(error) {\n // Reset origin validator.\n self.originValidator_ = null;\n // Reject iframe ready promise with network error.\n throw new fireauth.AuthError(\n fireauth.authenum.Error.NETWORK_REQUEST_FAILED);\n });\n};\n\n\n/**\n * @return {boolean} Whether the handler will unload the current page on\n * redirect operations.\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.unloadsOnRedirect = function() {\n return true;\n};\n\n\n/**\n * @param {string} authDomain The Firebase authDomain used to determine the\n * OAuth helper page domain.\n * @param {string} apiKey The API key for sending backend Auth requests.\n * @param {string} appName The App ID for the Auth instance that triggered this\n * request.\n * @param {?string=} opt_clientVersion The optional client version string.\n * @param {?string=} opt_endpointId The endpoint ID (staging, test Gaia, etc).\n * @param {?Array<string>=} opt_frameworks The optional list of framework IDs.\n * @return {string} The data iframe src URL.\n */\nfireauth.iframeclient.IfcHandler.getAuthIframeUrl = function(authDomain, apiKey,\n appName, opt_clientVersion, opt_endpointId, opt_frameworks) {\n // OAuth helper iframe URL.\n var builder = new fireauth.iframeclient.IframeUrlBuilder(\n authDomain, apiKey, appName);\n return builder\n .setVersion(opt_clientVersion)\n .setEndpointId(opt_endpointId)\n .setFrameworks(opt_frameworks)\n .toString();\n};\n\n\n/**\n * @param {string} authDomain The Firebase authDomain used to determine the\n * OAuth helper page domain.\n * @param {string} apiKey The API key for sending backend Auth requests.\n * @param {string} appName The App ID for the Auth instance that triggered this\n * request.\n * @param {string} authType The type of operation that depends on OAuth sign in.\n * @param {!fireauth.AuthProvider} provider The provider to sign in to.\n * @param {?string=} opt_redirectUrl The optional URL to redirect to on OAuth\n * sign in completion.\n * @param {?string=} opt_eventId The optional event ID to identify on receipt.\n * @param {?string=} opt_clientVersion The optional client version string.\n * @param {?Object<string, string>=} opt_additionalParams The optional\n * additional parameters.\n * @param {?string=} opt_endpointId The endpoint ID (staging, test Gaia, etc).\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {string} The OAuth helper widget URL.\n */\nfireauth.iframeclient.IfcHandler.getOAuthHelperWidgetUrl = function(\n authDomain,\n apiKey,\n appName,\n authType,\n provider,\n opt_redirectUrl,\n opt_eventId,\n opt_clientVersion,\n opt_additionalParams,\n opt_endpointId,\n opt_tenantId) {\n // OAuth helper widget URL.\n var builder = new fireauth.iframeclient.OAuthUrlBuilder(\n authDomain, apiKey, appName, authType, provider);\n return builder\n .setRedirectUrl(opt_redirectUrl)\n .setEventId(opt_eventId)\n .setVersion(opt_clientVersion)\n .setAdditionalParameters(opt_additionalParams)\n .setEndpointId(opt_endpointId)\n .setTenantId(opt_tenantId)\n .toString();\n};\n\n\n/**\n * Post message receiver event names.\n * @enum {string}\n */\nfireauth.iframeclient.IfcHandler.ReceiverEvent = {\n AUTH_EVENT: 'authEvent'\n};\n\n\n/**\n * Post message sender event names.\n * @enum {string}\n */\nfireauth.iframeclient.IfcHandler.SenderEvent = {\n WEB_STORAGE_SUPPORT_EVENT: 'webStorageSupport'\n};\n\n\n/**\n * Post message response field names.\n * @enum {string}\n */\nfireauth.iframeclient.IfcHandler.Response = {\n STATUS: 'status',\n AUTH_EVENT: 'authEvent',\n WEB_STORAGE_SUPPORT: 'webStorageSupport'\n};\n\n\n/**\n * Post message status values.\n * @enum {string}\n */\nfireauth.iframeclient.IfcHandler.Status = {\n ACK: 'ACK',\n ERROR: 'ERROR'\n};\n\n\n/**\n * Registers all event listeners.\n * @private\n */\nfireauth.iframeclient.IfcHandler.prototype.registerEvents_ = function() {\n // Should be run in initialization.\n if (!this.iframeWrapper_) {\n throw new Error('IfcHandler must be initialized!');\n }\n var self = this;\n // Listen to Auth change events emitted from iframe.\n this.iframeWrapper_.registerEvent(\n fireauth.iframeclient.IfcHandler.ReceiverEvent.AUTH_EVENT,\n function(response) {\n var resolveResponse = {};\n if (response &&\n response[fireauth.iframeclient.IfcHandler.Response.AUTH_EVENT]) {\n var isHandled = false;\n // Get Auth event (plain object).\n var authEvent = fireauth.AuthEvent.fromPlainObject(\n response[fireauth.iframeclient.IfcHandler.Response.AUTH_EVENT]);\n // Trigger Auth change on all listeners.\n for (var i = 0; i < self.authEventListeners_.length; i++) {\n isHandled = self.authEventListeners_[i](authEvent) || isHandled;\n }\n // Return ack response to notify sender of success.\n resolveResponse = {};\n resolveResponse[fireauth.iframeclient.IfcHandler.Response.STATUS] =\n isHandled ? fireauth.iframeclient.IfcHandler.Status.ACK :\n fireauth.iframeclient.IfcHandler.Status.ERROR;\n return goog.Promise.resolve(resolveResponse);\n }\n // Return error status if the response is invalid.\n resolveResponse[fireauth.iframeclient.IfcHandler.Response.STATUS] =\n fireauth.iframeclient.IfcHandler.Status.ERROR;\n return goog.Promise.resolve(resolveResponse);\n });\n};\n\n\n/**\n * @return {!goog.Promise<boolean>} Whether web storage is supported in the\n * iframe.\n */\nfireauth.iframeclient.IfcHandler.prototype.isWebStorageSupported = function() {\n var webStorageSupportEvent =\n fireauth.iframeclient.IfcHandler.SenderEvent.WEB_STORAGE_SUPPORT_EVENT;\n var message = {\n 'type': webStorageSupportEvent\n };\n var self = this;\n // Initialize if not initialized yet.\n return this.initialize().then(function() {\n return self.iframeWrapper_.sendMessage(message);\n }).then(function(response) {\n // Parse the response and return the passed web storage support status.\n var key = fireauth.iframeclient.IfcHandler.Response.WEB_STORAGE_SUPPORT;\n if (response &&\n response.length &&\n typeof response[0][key] !== 'undefined') {\n return response[0][key];\n }\n // Internal error.\n throw new Error;\n });\n};\n\n\n/**\n * @param {!function(?fireauth.AuthEvent):boolean} listener The Auth event\n * listener to add.\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.addAuthEventListener =\n function(listener) {\n this.authEventListeners_.push(listener);\n};\n\n\n/**\n * @param {!function(?fireauth.AuthEvent):boolean} listener The Auth event\n * listener to remove.\n * @override\n */\nfireauth.iframeclient.IfcHandler.prototype.removeAuthEventListener =\n function(listener) {\n goog.array.removeAllIf(this.authEventListeners_, function(ele) {\n return ele == listener;\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview JSON utility functions.\n */\n\n\ngoog.provide('goog.json');\ngoog.provide('goog.json.Replacer');\ngoog.provide('goog.json.Reviver');\ngoog.provide('goog.json.Serializer');\n\n\n/**\n * @define {boolean} If true, use the native JSON parsing API.\n * NOTE: The default `goog.json.parse` implementation is able to handle\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\n * faster and safer than the default implementation using `eval`.\n */\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\n\n/**\n * @define {boolean} If true, try the native JSON parsing API first. If it\n * fails, log an error and use `eval` instead. This is useful when\n * transitioning to `goog.json.USE_NATIVE_JSON`. The error logger needs to\n * be set by `goog.json.setErrorLogger`. If it is not set then the error\n * is ignored.\n */\ngoog.json.TRY_NATIVE_JSON = goog.define('goog.json.TRY_NATIVE_JSON', false);\n\n\n/**\n * Tests if a string is an invalid JSON string. This only ensures that we are\n * not using any invalid characters\n * @param {string} s The string to test.\n * @return {boolean} True if the input is a valid JSON string.\n */\ngoog.json.isValid = function(s) {\n // All empty whitespace is not valid.\n if (/^\\s*$/.test(s)) {\n return false;\n }\n\n // This is taken from http://www.json.org/json2.js which is released to the\n // public domain.\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\n // are in the RFC but IE and Safari does not match \\s to these so we need to\n // include them in the reg exps in all places where whitespace is allowed.\n // We allowed \\x7f inside strings because some tools don't escape it,\n // e.g. http://www.json.org/java/org/json/JSONObject.java\n\n // Parsing happens in three stages. In the first stage, we run the text\n // against regular expressions that look for non-JSON patterns. We are\n // especially concerned with '()' and 'new' because they can cause invocation,\n // and '=' because it can cause mutation. But just to be safe, we want to\n // reject all unexpected forms.\n\n // We split the first stage into 4 regexp operations in order to work around\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\n // replace all simple value tokens with ']' characters, but only when followed\n // by a colon, comma, closing bracket or end of string. Third, we delete all\n // open brackets that follow a colon or comma or that begin the text. Finally,\n // we look to see that the remaining characters are only whitespace or ']' or\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\n\n // Don't make these static since they have the global flag.\n const backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\n const simpleValuesRe =\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\n const openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\n const remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\n\n return remainderRe.test(\n s.replace(backslashesRe, '@')\n .replace(simpleValuesRe, ']')\n .replace(openBracketsRe, ''));\n};\n\n/**\n * Logs a parsing error in `JSON.parse` solvable by using `eval`\n * if `goog.json.TRY_NATIVE_JSON` is enabled.\n * @private {function(string, !Error)} The first parameter is the error message,\n * the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.errorLogger_ = goog.nullFunction;\n\n\n/**\n * Sets an error logger to use if there's a recoverable parsing error and\n * `goog.json.TRY_NATIVE_JSON` is enabled.\n * @param {function(string, !Error)} errorLogger The first parameter is the\n * error message, the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.setErrorLogger = function(errorLogger) {\n goog.json.errorLogger_ = errorLogger;\n};\n\n\n/**\n * Parses a JSON string and returns the result. This throws an exception if\n * the string is an invalid JSON string.\n *\n * Note that this is very slow on large strings. Use JSON.parse if possible.\n *\n * @param {*} s The JSON string to parse.\n * @throws Error if s is invalid JSON.\n * @return {Object} The object generated from the JSON string, or null.\n * @deprecated Use JSON.parse.\n */\ngoog.json.parse = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :\n function(s) {\n let error;\n if (goog.json.TRY_NATIVE_JSON) {\n try {\n return goog.global['JSON']['parse'](s);\n } catch (ex) {\n error = ex;\n }\n }\n const o = String(s);\n if (goog.json.isValid(o)) {\n\n try {\n const result = /** @type {?Object} */ (eval('(' + o + ')'));\n if (error) {\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\n }\n return result;\n } catch (ex) {\n }\n }\n throw new Error('Invalid JSON string: ' + o);\n };\n\n\n/**\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * TODO(nicksantos): Array should also be a valid replacer.\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Replacer;\n\n\n/**\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Reviver;\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\n * called for each (key, value) pair that determines how the value\n * should be serialized. By defult, this just returns the value\n * and allows default serialization to kick in.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*, ?goog.json.Replacer=):string} */\n (goog.global['JSON']['stringify']) :\n function(object, opt_replacer) {\n // NOTE(nicksantos): Currently, we never use JSON.stringify.\n //\n // The last time I evaluated this, JSON.stringify had subtle bugs and\n // behavior differences on all browsers, and the performance win was not\n // large enough to justify all the issues. This may change in the future\n // as browser implementations get better.\n //\n // assertSerialize in json_test contains if branches for the cases\n // that fail.\n return new goog.json.Serializer(opt_replacer).serialize(object);\n };\n\n\n\n/**\n * Class that is used to serialize JSON objects to a string.\n * @param {?goog.json.Replacer=} opt_replacer Replacer.\n * @constructor\n */\ngoog.json.Serializer = function(opt_replacer) {\n /**\n * @type {goog.json.Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n};\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.Serializer.prototype.serialize = function(object) {\n const sb = [];\n this.serializeInternal(object, sb);\n return sb.join('');\n};\n\n\n/**\n * Serializes a generic value to a JSON string\n * @protected\n * @param {*} object The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @throws Error if there are loops in the object graph.\n */\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\n if (object == null) {\n // undefined == null so this branch covers undefined as well as null\n sb.push('null');\n return;\n }\n\n if (typeof object == 'object') {\n if (Array.isArray(object)) {\n this.serializeArray(object, sb);\n return;\n } else if (\n object instanceof String || object instanceof Number ||\n object instanceof Boolean) {\n object = object.valueOf();\n // Fall through to switch below.\n } else {\n this.serializeObject_(/** @type {!Object} */ (object), sb);\n return;\n }\n }\n\n switch (typeof object) {\n case 'string':\n this.serializeString_(object, sb);\n break;\n case 'number':\n this.serializeNumber_(object, sb);\n break;\n case 'boolean':\n sb.push(String(object));\n break;\n case 'function':\n sb.push('null');\n break;\n default:\n throw new Error('Unknown type: ' + typeof object);\n }\n};\n\n\n/**\n * Character mappings used internally for goog.string.quote\n * @private\n * @type {!Object}\n */\ngoog.json.Serializer.charToJsonCharCache_ = {\n '\\\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '/': '\\\\/',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\n};\n\n\n/**\n * Regular expression used to match characters that need to be replaced.\n * The S60 browser has a bug where unicode characters are not matched by\n * regular expressions. The condition below detects such behaviour and\n * adjusts the regular expression accordingly.\n * @private\n * @type {!RegExp}\n */\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\n\n\n/**\n * Serializes a string to a JSON string\n * @private\n * @param {string} s The string to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\n // The official JSON implementation does not work with international\n // characters.\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\n // caching the result improves performance by a factor 2-3\n let rv = goog.json.Serializer.charToJsonCharCache_[c];\n if (!rv) {\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).substr(1);\n goog.json.Serializer.charToJsonCharCache_[c] = rv;\n }\n return rv;\n }), '\"');\n};\n\n\n/**\n * Serializes a number to a JSON string\n * @private\n * @param {number} n The number to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {\n sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');\n};\n\n\n/**\n * Serializes an array to a JSON string\n * @param {Array<string>} arr The array to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @protected\n */\ngoog.json.Serializer.prototype.serializeArray = function(arr, sb) {\n const l = arr.length;\n sb.push('[');\n let sep = '';\n for (let i = 0; i < l; i++) {\n sb.push(sep);\n\n const value = arr[i];\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\n sb);\n\n sep = ',';\n }\n sb.push(']');\n};\n\n\n/**\n * Serializes an object to a JSON string\n * @private\n * @param {!Object} obj The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\n sb.push('{');\n let sep = '';\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n // Skip functions.\n if (typeof value != 'function') {\n sb.push(sep);\n this.serializeString_(key, sb);\n sb.push(':');\n\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\n\n sep = ',';\n }\n }\n }\n sb.push('}');\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 utility and helper functions.\n */\n\ngoog.provide('fireauth.util');\n\ngoog.require('goog.Promise');\ngoog.require('goog.Timer');\ngoog.require('goog.Uri');\ngoog.require('goog.dom');\ngoog.require('goog.events');\ngoog.require('goog.events.EventType');\ngoog.require('goog.html.SafeUrl');\ngoog.require('goog.json');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\ngoog.require('goog.window');\n\n\n/** @suppress {duplicate} Suppress variable 'angular' first declared. */\nvar angular;\n\n/**\n * Checks whether the user agent is IE11.\n * @return {boolean} True if it is IE11.\n */\nfireauth.util.isIe11 = function() {\n return goog.userAgent.IE &&\n !!goog.userAgent.DOCUMENT_MODE &&\n goog.userAgent.DOCUMENT_MODE == 11;\n};\n\n\n/**\n * Checks whether the user agent is IE10.\n * @return {boolean} True if it is IE10.\n */\nfireauth.util.isIe10 = function() {\n return goog.userAgent.IE &&\n !!goog.userAgent.DOCUMENT_MODE &&\n goog.userAgent.DOCUMENT_MODE == 10;\n};\n\n\n/**\n * Checks whether the user agent is Edge.\n * @param {string} userAgent The browser user agent string.\n * @return {boolean} True if it is Edge.\n */\nfireauth.util.isEdge = function(userAgent) {\n return /Edge\\/\\d+/.test(userAgent);\n};\n\n\n/**\n * @param {?string=} opt_userAgent The navigator user agent.\n * @return {boolean} Whether local storage is not synchronized between an iframe\n * and a popup of the same domain.\n */\nfireauth.util.isLocalStorageNotSynchronized = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n return fireauth.util.isIe11() || fireauth.util.isEdge(ua);\n};\n\n\n/** @return {string} The current URL. */\nfireauth.util.getCurrentUrl = function() {\n return (goog.global['window'] && goog.global['window']['location']['href']) ||\n // Check for worker environments.\n (self && self['location'] && self['location']['href']) || '';\n};\n\n\n/**\n * @param {string} requestUri The request URI to send in verifyAssertion\n * request.\n * @return {string} The sanitized URI, in this case it undoes the hashbang\n * angularJs routing changes to request URI.\n */\nfireauth.util.sanitizeRequestUri = function(requestUri) {\n // If AngularJS is included.\n if (typeof angular != 'undefined') {\n // Remove hashbang modifications from URL.\n requestUri = requestUri.replace('#/', '#').replace('#!/', '#');\n }\n return requestUri;\n};\n\n\n/**\n * @param {?string} url The target URL. When !url, redirects to a blank page.\n * @param {!Window=} opt_window The optional window to redirect to target URL.\n * @param {boolean=} opt_bypassCheck Whether to bypass check. Used for custom\n * scheme redirects.\n */\nfireauth.util.goTo = function(url, opt_window, opt_bypassCheck) {\n var win = opt_window || goog.global['window'];\n // No URL, redirect to blank page.\n var finalUrl = 'about:blank';\n // Popping up a window and then assigning its URL seems to cause some weird\n // error. Fixed by setting win.location.href for now in IE browsers.\n // Bug was detected in Edge and IE9.\n if (url && !opt_bypassCheck) {\n // We cannot use goog.dom.safe.setLocationHref since it tries to read\n // popup.location from a different origin, which is an error in IE.\n // (In Chrome, popup.location is just an empty Location object)\n finalUrl = goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(url));\n }\n win.location.href = finalUrl;\n};\n\n\n/**\n * @param {string} url The target URL.\n * @param {!Window=} opt_window The optional window to replace with target URL.\n * @param {boolean=} opt_bypassCheck Whether to bypass check. Used for custom\n * scheme redirects.\n */\nfireauth.util.replaceCurrentUrl = function(url, opt_window, opt_bypassCheck) {\n var win = opt_window || goog.global['window'];\n if (!opt_bypassCheck) {\n win.location.replace(\n goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(url)));\n } else {\n win.location.replace(url);\n }\n};\n\n\n/**\n * Deep comparison of two objects.\n * @param {!Object} a The first object.\n * @param {!Object} b The second object.\n * @return {!Array<string>} The list of keys that are different between both\n * objects provided.\n */\nfireauth.util.getKeyDiff = function(a, b) {\n var diff = [];\n for (var k in a) {\n if (!(k in b)) {\n diff.push(k);\n } else if (typeof a[k] != typeof b[k]) {\n diff.push(k);\n } else if (typeof a[k] == 'object' && a[k] != null && b[k] != null) {\n if (fireauth.util.getKeyDiff(\n a[k], b[k]).length > 0) {\n diff.push(k);\n }\n } else if (a[k] !== b[k]) {\n diff.push(k);\n }\n }\n for (var k in b) {\n if (!(k in a)) {\n diff.push(k);\n }\n }\n return diff;\n};\n\n\n/**\n * @param {?string=} opt_userAgent The navigator user agent.\n * @return {?number} The Chrome version, null if the user agent is not Chrome.\n */\nfireauth.util.getChromeVersion = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n var browserName = fireauth.util.getBrowserName(ua);\n // Confirm current browser is Chrome.\n if (browserName != fireauth.util.BrowserName.CHROME) {\n return null;\n }\n var matches = ua.match(/\\sChrome\\/(\\d+)/i);\n if (matches && matches.length == 2) {\n return parseInt(matches[1], 10);\n }\n return null;\n};\n\n\n/**\n * Detects CORS support.\n * @param {?string=} opt_userAgent The navigator user agent.\n * @return {boolean} True if the browser supports CORS.\n */\nfireauth.util.supportsCors = function(opt_userAgent) {\n // Chrome 7 has CORS issues, pick 30 as upper limit.\n var chromeVersion = fireauth.util.getChromeVersion(opt_userAgent);\n if (chromeVersion && chromeVersion < 30) {\n return false;\n }\n // Among all other supported browsers, only IE8 and IE9 don't support CORS.\n return !goog.userAgent.IE || // Not IE.\n !goog.userAgent.DOCUMENT_MODE || // No document mode == IE Edge.\n goog.userAgent.DOCUMENT_MODE > 9;\n};\n\n\n/**\n * Detects whether browser is running on a mobile device.\n * @param {?string=} opt_userAgent The navigator user agent.\n * @return {boolean} True if the browser is running on a mobile device.\n */\nfireauth.util.isMobileBrowser = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n var uaLower = ua.toLowerCase();\n // TODO: implement getBrowserName equivalent for OS.\n if (uaLower.match(/android/) ||\n uaLower.match(/webos/) ||\n uaLower.match(/iphone|ipad|ipod/) ||\n uaLower.match(/blackberry/) ||\n uaLower.match(/windows phone/) ||\n uaLower.match(/iemobile/)) {\n return true;\n }\n return false;\n};\n\n\n/**\n * Closes the provided window.\n * @param {?Window=} opt_window The optional window to close. The current window\n * is used if none is provided.\n */\nfireauth.util.closeWindow = function(opt_window) {\n var win = opt_window || goog.global['window'];\n // In some browsers, in certain cases after the window closes, as seen in\n // Samsung Galaxy S3 Android 4.4.2 stock browser, the win object here is an\n // empty object {}. Try to catch the failure and ignore it.\n try {\n win.close();\n } catch(e) {}\n};\n\n\n/**\n * Opens a popup window.\n * @param {?string=} opt_url initial URL of the popup window\n * @param {string=} opt_name title of the popup\n * @param {?number=} opt_width width of the popup\n * @param {?number=} opt_height height of the popup\n * @return {?Window} Returns the window object that was opened. This returns\n * null if a popup blocker prevented the window from being\n * opened.\n */\nfireauth.util.popup = function(opt_url, opt_name, opt_width, opt_height) {\n var width = opt_width || 500;\n var height = opt_height || 600;\n var top = (window.screen.availHeight - height) / 2;\n var left = (window.screen.availWidth - width) / 2;\n var options = {\n 'width': width,\n 'height': height,\n 'top': top > 0 ? top : 0,\n 'left': left > 0 ? left : 0,\n 'location': true,\n 'resizable': true,\n 'statusbar': true,\n 'toolbar': false\n };\n // Chrome iOS 7 and 8 is returning an undefined popup win when target is\n // specified, even though the popup is not necessarily blocked.\n var ua = fireauth.util.getUserAgentString().toLowerCase();\n if (opt_name) {\n options['target'] = opt_name;\n // This will force a new window on each call, achieving the same effect as\n // passing a random name on each call.\n if (goog.string.contains(ua, 'crios/')) {\n options['target'] = '_blank';\n }\n }\n var browserName = fireauth.util.getBrowserName(\n fireauth.util.getUserAgentString());\n if (browserName == fireauth.util.BrowserName.FIREFOX) {\n // Firefox complains when invalid URLs are popped out. Hacky way to bypass.\n opt_url = opt_url || 'http://localhost';\n // Firefox disables by default scrolling on popup windows, which can create\n // issues when the user has many Google accounts, for instance.\n options['scrollbars'] = true;\n }\n // about:blank getting sanitized causing browsers like IE/Edge to display\n // brief error message before redirecting to handler.\n var newWin = goog.window.open(opt_url || '', options);\n if (newWin) {\n // Flaky on IE edge, encapsulate with a try and catch.\n try {\n newWin.focus();\n } catch (e) {}\n }\n return newWin;\n};\n\n\n/**\n * The default value for the popup wait cycle in ms.\n * @const {number}\n * @private\n */\nfireauth.util.POPUP_WAIT_CYCLE_MS_ = 2000;\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {boolean} Whether the popup requires a delay before closing itself.\n */\nfireauth.util.requiresPopupDelay = function(opt_userAgent) {\n // TODO: remove this hack when CriOS behavior is fixed in iOS.\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n // Was observed in iOS 10.2 Chrome version 55.0.2883.79.\n // Apply to Chrome 55+ iOS 10+ to ensure future Chrome versions or iOS 10\n // minor updates do not suddenly resurface this bug. Revisit this check on\n // next CriOS update.\n var matches = ua.match(/OS (\\d+)_.*CriOS\\/(\\d+)\\./i);\n if (matches && matches.length > 2) {\n // iOS 10+ && chrome 55+.\n return parseInt(matches[1], 10) >= 10 && parseInt(matches[2], 10) >= 55;\n }\n return false;\n};\n\n\n/**\n * @param {?Window} win The popup window to check.\n * @param {number=} opt_stepDuration The duration of each wait cycle before\n * checking that window is closed.\n * @return {!goog.Promise<undefined>} The promise to resolve when window is\n * closed.\n */\nfireauth.util.onPopupClose = function(win, opt_stepDuration) {\n var stepDuration = opt_stepDuration || fireauth.util.POPUP_WAIT_CYCLE_MS_;\n return new goog.Promise(function(resolve, reject) {\n // Function to repeat each stepDuration.\n var repeat = function() {\n goog.Timer.promise(stepDuration).then(function() {\n // After wait, check if window is closed.\n if (!win || win.closed) {\n // If so, resolve.\n resolve();\n } else {\n // Call repeat again.\n return repeat();\n }\n });\n };\n return repeat();\n });\n};\n\n\n/**\n * @param {!Array<string>} authorizedDomains List of authorized domains.\n * @param {string} url The URL to check.\n * @return {boolean} Whether the passed domain is an authorized one.\n */\nfireauth.util.isAuthorizedDomain = function(authorizedDomains, url) {\n var uri = goog.Uri.parse(url);\n var scheme = uri.getScheme();\n var domain = uri.getDomain();\n for (var i = 0; i < authorizedDomains.length; i++) {\n // Currently this corresponds to: domain.com = *://*.domain.com:* or\n // exact domain match.\n // In the case of Chrome extensions, the authorizedDomain will be formatted\n // as 'chrome-extension://abcdefghijklmnopqrstuvwxyz123456'.\n // The URL to check must have a chrome extension scheme and the domain\n // must be an exact match domain == 'abcdefghijklmnopqrstuvwxyz123456'.\n if (fireauth.util.matchDomain(authorizedDomains[i], domain, scheme)) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Represents the dimensions of an entity (width and height).\n * @typedef {{\n * width: number,\n * height: number\n * }}\n */\nfireauth.util.Dimensions;\n\n\n/**\n * @param {?Window=} opt_window The optional window whose dimensions are to be\n * returned. The current window is used if not found.\n * @return {?fireauth.util.Dimensions} The requested window dimensions if\n * available.\n */\nfireauth.util.getWindowDimensions = function(opt_window) {\n var win = opt_window || goog.global['window'];\n if (win && win['innerWidth'] && win['innerHeight']) {\n return {\n 'width': parseFloat(win['innerWidth']),\n 'height': parseFloat(win['innerHeight'])\n };\n }\n return null;\n};\n\n\n/**\n * RegExp to detect if the domain given is an IP address. This is only used\n * for validating http and https schemes.\n *\n * It does not strictly validate if the IP is a real IP address, but as the\n * matchDomain method tests against a set of valid domains (extracted from the\n * window's current URL), it is sufficient.\n *\n * @const {!RegExp}\n * @private\n */\nfireauth.util.IP_ADDRESS_REGEXP_ = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\n\n\n/**\n * @param {string} domainPattern The domain pattern to match.\n * @param {string} domain The domain to check. It is assumed that it is a valid\n * domain, not a user provided one.\n * @param {string} scheme The scheme of the domain to check.\n * @return {boolean} Whether the provided domain matches the domain pattern.\n */\nfireauth.util.matchDomain = function(domainPattern, domain, scheme) {\n // Chrome extension matching.\n if (domainPattern.indexOf('chrome-extension://') == 0) {\n var chromeExtUri = goog.Uri.parse(domainPattern);\n // Domain must match and the current scheme must be a Chrome extension.\n return chromeExtUri.getDomain() == domain && scheme == 'chrome-extension';\n } else if (scheme != 'http' && scheme != 'https') {\n // Any other scheme that is not http or https cannot be whitelisted.\n return false;\n } else {\n // domainPattern must not contain a scheme and the current scheme must be\n // either http or https.\n // Check if authorized domain pattern is an IP address.\n if (fireauth.util.IP_ADDRESS_REGEXP_.test(domainPattern)) {\n // The domain has to be exactly equal to the pattern, as an IP domain will\n // only contain the IP, no extra character.\n return domain == domainPattern;\n }\n // Dots in pattern should be escaped.\n var escapedDomainPattern = domainPattern.split('.').join('\\\\.');\n // Non ip address domains.\n // domain.com = *.domain.com OR domain.com\n var re = new RegExp(\n '^(.+\\\\.' + escapedDomainPattern + '|' +\n escapedDomainPattern + ')$', 'i');\n return re.test(domain);\n }\n};\n\n\n/**\n * RegExp to detect if the email address given is valid.\n * @const {!RegExp}\n * @private\n */\nfireauth.util.EMAIL_ADDRESS_REGEXP_ = /^[^@]+@[^@]+$/;\n\n\n/**\n * Determines if it is a valid email address.\n * @param {*} email The email address.\n * @return {boolean} Whether the email address is valid.\n */\nfireauth.util.isValidEmailAddress = function(email) {\n return typeof email === 'string' &&\n fireauth.util.EMAIL_ADDRESS_REGEXP_.test(email);\n};\n\n\n/**\n * @return {!goog.Promise<void>} A promise that resolves when DOM is ready.\n */\nfireauth.util.onDomReady = function() {\n var resolver = null;\n return new goog.Promise(function(resolve, reject) {\n var doc = goog.global.document;\n // If document already loaded, resolve immediately.\n if (doc.readyState == 'complete') {\n resolve();\n } else {\n // Document not ready, wait for load before resolving.\n // Save resolver, so we can remove listener in case it was externally\n // cancelled.\n resolver = function() {\n resolve();\n };\n goog.events.listenOnce(window, goog.events.EventType.LOAD, resolver);\n }\n }).thenCatch(function(error) {\n // In case this promise was cancelled, make sure it unlistens to load.\n goog.events.unlisten(window, goog.events.EventType.LOAD, resolver);\n throw error;\n });\n};\n\n\n/** @return {boolean} Whether environment supports DOM. */\nfireauth.util.isDOMSupported = function() {\n return !!goog.global.document;\n};\n\n\n/**\n * The default ondeviceready Cordova timeout in ms.\n * @const {number}\n * @private\n */\nfireauth.util.CORDOVA_ONDEVICEREADY_TIMEOUT_MS_ = 1000;\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @param {number=} opt_timeout The optional timeout in ms for deviceready\n * event to resolve.\n * @return {!goog.Promise} A promise that resolves if the current environment is\n * a Cordova environment.\n */\nfireauth.util.checkIfCordova = function(opt_userAgent, opt_timeout) {\n // Errors generated are internal and should be converted if needed to\n // developer facing Firebase errors.\n // Only supported in Android/iOS environment.\n if (fireauth.util.isAndroidOrIosCordovaScheme(opt_userAgent)) {\n return fireauth.util.onDomReady().then(function() {\n return new goog.Promise(function(resolve, reject) {\n var doc = goog.global.document;\n var timeoutId = setTimeout(function() {\n reject(new Error('Cordova framework is not ready.'));\n }, opt_timeout || fireauth.util.CORDOVA_ONDEVICEREADY_TIMEOUT_MS_);\n // This should resolve immediately after DOM ready.\n doc.addEventListener('deviceready', function() {\n clearTimeout(timeoutId);\n resolve();\n }, false);\n });\n });\n }\n return goog.Promise.reject(\n new Error('Cordova must run in an Android or iOS file scheme.'));\n};\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {boolean} Whether the app is rendered in a mobile iOS or Android\n * Cordova environment.\n */\nfireauth.util.isAndroidOrIosCordovaScheme = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n return !!((fireauth.util.getCurrentScheme() === 'file:' ||\n fireauth.util.getCurrentScheme() === 'ionic:') &&\n ua.toLowerCase().match(/iphone|ipad|ipod|android/));\n};\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {boolean} Whether the app is rendered in a mobile iOS 7 or 8 browser.\n */\nfireauth.util.isIOS7Or8 = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n return !!(ua.match(/(iPad|iPhone|iPod).*OS 7_\\d/i) ||\n ua.match(/(iPad|iPhone|iPod).*OS 8_\\d/i));\n};\n\n\n/**\n * @return {boolean} Whether browser is Safari or an iOS browser and page is\n * embedded in an iframe. Local Storage does not synchronize with an iframe\n * embedded on a page in a different domain but will still trigger storage\n * event with storage changes.\n */\nfireauth.util.isSafariLocalStorageNotSynced = function() {\n var ua = fireauth.util.getUserAgentString();\n // Safari or iOS browser and embedded in an iframe.\n if (!fireauth.util.iframeCanSyncWebStorage(ua) && fireauth.util.isIframe()) {\n return true;\n }\n return false;\n};\n\n\n/**\n * @param {?Window=} opt_win Optional window to check whether it is an iframe.\n * If not provided, the current window is checked.\n * @return {boolean} Whether web page is running in an iframe.\n */\nfireauth.util.isIframe = function(opt_win) {\n var win = opt_win || goog.global['window'];\n try {\n // Check that the current window is not the top window.\n // If so, return true.\n return !!(win && win != win['top']);\n } catch (e) {\n return false;\n }\n};\n\n\n/**\n * @param {?Window=} opt_win Optional window to check whether it has an opener\n * that is an iframe.\n * @return {boolean} Whether the web page was opened from an iframe.\n */\nfireauth.util.isOpenerAnIframe = function(opt_win) {\n var win = opt_win || goog.global['window'];\n try {\n // Get the opener if available.\n var opener = win && win['opener'];\n // Check if the opener is an iframe. If so, return true.\n // Confirm opener is available, otherwise the current window is checked\n // instead.\n return !!(opener && fireauth.util.isIframe(opener));\n } catch (e) {\n return false;\n }\n};\n\n\n/**\n * @param {?Object=} global The optional global scope.\n * @return {boolean} Whether current environment is a worker.\n */\nfireauth.util.isWorker = function(global) {\n var scope = global || goog.global;\n // WorkerGlobalScope only defined in worker environment.\n return typeof scope['WorkerGlobalScope'] !== 'undefined' &&\n typeof scope['importScripts'] === 'function';\n};\n\n\n/**\n * @param {?Object=} opt_global The optional global scope.\n * @return {boolean} Whether current environment supports fetch API and other\n * APIs it depends on.\n */\nfireauth.util.isFetchSupported = function(opt_global) {\n // Required by fetch API calls.\n var scope = opt_global || goog.global;\n return typeof scope['fetch'] !== 'undefined' &&\n typeof scope['Headers'] !== 'undefined' &&\n typeof scope['Request'] !== 'undefined';\n};\n\n\n/**\n * Enum for the runtime environment.\n * @enum {string}\n */\nfireauth.util.Env = {\n BROWSER: 'Browser',\n NODE: 'Node',\n REACT_NATIVE: 'ReactNative',\n WORKER: 'Worker'\n};\n\n\n/**\n * @return {!fireauth.util.Env} The current runtime environment.\n */\nfireauth.util.getEnvironment = function() {\n if (firebase.INTERNAL.hasOwnProperty('reactNative')) {\n return fireauth.util.Env.REACT_NATIVE;\n } else if (firebase.INTERNAL.hasOwnProperty('node')) {\n // browserify seems to keep the process property in some cases even though\n // the library is browser only. Use this check instead to reliably detect\n // a Node.js environment.\n return fireauth.util.Env.NODE;\n } else if (fireauth.util.isWorker()) {\n // Worker environment.\n return fireauth.util.Env.WORKER;\n }\n // The default is a browser environment.\n return fireauth.util.Env.BROWSER;\n};\n\n\n/**\n * @return {boolean} Whether the environment is a native environment, where\n * CORS checks do not apply.\n */\nfireauth.util.isNativeEnvironment = function() {\n var environment = fireauth.util.getEnvironment();\n return environment === fireauth.util.Env.REACT_NATIVE ||\n environment === fireauth.util.Env.NODE;\n};\n\n\n/**\n * The separator for storage keys to concatenate App name and API key.\n * @const {string}\n * @private\n */\nfireauth.util.STORAGE_KEY_SEPARATOR_ = ':';\n\n\n/**\n * @param {string} apiKey The API Key of the app.\n * @param {string} appName The App name.\n * @return {string} The key used for identifying the app owner of the user.\n */\nfireauth.util.createStorageKey = function(apiKey, appName) {\n return apiKey + fireauth.util.STORAGE_KEY_SEPARATOR_ + appName;\n};\n\n\n/** @return {string} a long random character string. */\nfireauth.util.generateRandomString = function() {\n return Math.floor(Math.random() * 1000000000).toString();\n};\n\n\n/**\n * Generates a random alpha numeric string.\n * @param {number} numOfChars The number of random characters within the string.\n * @return {string} A string with a specific number of random characters.\n */\nfireauth.util.generateRandomAlphaNumericString = function(numOfChars) {\n var chars = [];\n var allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n while (numOfChars > 0) {\n chars.push(\n allowedChars.charAt(\n Math.floor(Math.random() * allowedChars.length)));\n numOfChars--;\n }\n return chars.join('');\n};\n\n\n/**\n * Enums for Browser name.\n * @enum {string}\n */\nfireauth.util.BrowserName = {\n ANDROID: 'Android',\n BLACKBERRY: 'Blackberry',\n EDGE: 'Edge',\n FIREFOX: 'Firefox',\n IE: 'IE',\n IEMOBILE: 'IEMobile',\n OPERA: 'Opera',\n OTHER: 'Other',\n CHROME: 'Chrome',\n SAFARI: 'Safari',\n SILK: 'Silk',\n WEBOS: 'Webos'\n};\n\n\n/**\n * @param {string} userAgent The navigator user agent string.\n * @return {string} The browser name, eg Safari, Firefox, etc.\n */\nfireauth.util.getBrowserName = function(userAgent) {\n var ua = userAgent.toLowerCase();\n if (goog.string.contains(ua, 'opera/') ||\n goog.string.contains(ua, 'opr/') ||\n goog.string.contains(ua, 'opios/')) {\n return fireauth.util.BrowserName.OPERA;\n } else if (goog.string.contains(ua, 'iemobile')) {\n // Windows phone IEMobile browser.\n return fireauth.util.BrowserName.IEMOBILE;\n } else if (goog.string.contains(ua, 'msie') ||\n goog.string.contains(ua, 'trident/')) {\n return fireauth.util.BrowserName.IE;\n } else if (goog.string.contains(ua, 'edge/')) {\n return fireauth.util.BrowserName.EDGE;\n } else if (goog.string.contains(ua, 'firefox/')) {\n return fireauth.util.BrowserName.FIREFOX;\n } else if (goog.string.contains(ua, 'silk/')) {\n return fireauth.util.BrowserName.SILK;\n } else if (goog.string.contains(ua, 'blackberry')) {\n // Blackberry browser.\n return fireauth.util.BrowserName.BLACKBERRY;\n } else if (goog.string.contains(ua, 'webos')) {\n // WebOS default browser.\n return fireauth.util.BrowserName.WEBOS;\n } else if (goog.string.contains(ua, 'safari/') &&\n !goog.string.contains(ua, 'chrome/') &&\n !goog.string.contains(ua, 'crios/') &&\n !goog.string.contains(ua, 'android')) {\n return fireauth.util.BrowserName.SAFARI;\n } else if ((goog.string.contains(ua, 'chrome/') ||\n goog.string.contains(ua, 'crios/')) &&\n !goog.string.contains(ua, 'edge/')) {\n return fireauth.util.BrowserName.CHROME;\n } else if (goog.string.contains(ua, 'android')) {\n // Android stock browser.\n return fireauth.util.BrowserName.ANDROID;\n } else {\n // Most modern browsers have name/version at end of user agent string.\n var re = new RegExp('([a-zA-Z\\\\d\\\\.]+)\\/[a-zA-Z\\\\d\\\\.]*$');\n var matches = userAgent.match(re);\n if (matches && matches.length == 2) {\n return matches[1];\n }\n }\n return fireauth.util.BrowserName.OTHER;\n};\n\n\n/**\n * Enums for client implementation name.\n * @enum {string}\n */\nfireauth.util.ClientImplementation = {\n JSCORE: 'JsCore',\n OAUTH_HANDLER: 'Handler',\n OAUTH_IFRAME: 'Iframe'\n};\n\n\n/**\n * Enums for the framework ID to be logged in RPC header.\n * Future frameworks to possibly add: angularfire, polymerfire, reactfire, etc.\n * @enum {string}.\n */\nfireauth.util.Framework = {\n // No other framework used.\n DEFAULT: 'FirebaseCore-web',\n // Firebase Auth used with FirebaseUI-web.\n FIREBASEUI: 'FirebaseUI-web'\n};\n\n\n/**\n * @param {!Array<string>} providedFrameworks List of framework ID strings.\n * @return {!Array<!fireauth.util.Framework>} List of supported framework IDs\n * with no duplicates.\n */\nfireauth.util.getFrameworkIds = function(providedFrameworks) {\n var frameworkVersion = [];\n var frameworkSet = {};\n for (var key in fireauth.util.Framework) {\n frameworkSet[fireauth.util.Framework[key]] = true;\n }\n for (var i = 0; i < providedFrameworks.length; i++) {\n if (typeof frameworkSet[providedFrameworks[i]] !== 'undefined') {\n // Delete it from set to prevent duplications.\n delete frameworkSet[providedFrameworks[i]];\n frameworkVersion.push(providedFrameworks[i]);\n }\n }\n // Sort alphabetically so that \"FirebaseCore-web,FirebaseUI-web\" and\n // \"FirebaseUI-web,FirebaseCore-web\" aren't viewed as different.\n frameworkVersion.sort();\n return frameworkVersion;\n};\n\n\n/**\n * @param {!fireauth.util.ClientImplementation} clientImplementation The client\n * implementation.\n * @param {string} clientVersion The client version.\n * @param {?Array<string>=} opt_frameworkVersion The framework version.\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {string} The full client SDK version.\n */\nfireauth.util.getClientVersion = function(clientImplementation, clientVersion,\n opt_frameworkVersion, opt_userAgent) {\n var frameworkVersion = fireauth.util.getFrameworkIds(\n opt_frameworkVersion || []);\n if (!frameworkVersion.length) {\n frameworkVersion = [fireauth.util.Framework.DEFAULT];\n }\n var environment = fireauth.util.getEnvironment();\n var reportedEnvironment = '';\n if (environment === fireauth.util.Env.BROWSER) {\n // In a browser environment, report the browser name.\n var userAgent = opt_userAgent || fireauth.util.getUserAgentString();\n reportedEnvironment = fireauth.util.getBrowserName(userAgent);\n } else if (environment === fireauth.util.Env.WORKER) {\n // Technically a worker runs from a browser but we need to differentiate a\n // worker from a browser.\n // For example: Chrome-Worker/JsCore/4.9.1/FirebaseCore-web.\n var userAgent = opt_userAgent || fireauth.util.getUserAgentString();\n reportedEnvironment = fireauth.util.getBrowserName(userAgent) + '-' +\n environment;\n } else {\n // Otherwise, just report the environment name.\n reportedEnvironment = environment;\n }\n // The format to be followed:\n // ${browserName}/${clientImplementation}/${clientVersion}/${frameworkVersion}\n // As multiple Firebase frameworks/libraries can be used, join their IDs with\n // a comma.\n return reportedEnvironment + '/' + clientImplementation +\n '/' + clientVersion + '/' + frameworkVersion.join(',');\n};\n\n\n/**\n * @return {string} The user agent string reported by the environment, or the\n * empty string if not available.\n */\nfireauth.util.getUserAgentString = function() {\n return (goog.global['navigator'] && goog.global['navigator']['userAgent']) ||\n '';\n};\n\n\n/**\n * @param {string} varStrName The variable string name.\n * @param {?Object=} opt_scope The optional scope where to look in. The default\n * is window.\n * @return {*} The reference if found.\n */\nfireauth.util.getObjectRef = function(varStrName, opt_scope) {\n var pieces = varStrName.split('.');\n var last = opt_scope || goog.global;\n for (var i = 0;\n i < pieces.length && typeof last == 'object' && last != null;\n i++) {\n last = last[pieces[i]];\n }\n // Last hasn't reached the end yet, return undefined.\n if (i != pieces.length) {\n last = undefined;\n }\n return last;\n};\n\n\n/** @return {boolean} Whether web storage is supported. */\nfireauth.util.isWebStorageSupported = function() {\n try {\n var storage = goog.global['localStorage'];\n var key = fireauth.util.generateEventId();\n if (storage) {\n // setItem will throw an exception if we cannot access WebStorage (e.g.,\n // Safari in private mode).\n storage['setItem'](key, '1');\n storage['removeItem'](key);\n // For browsers where iframe web storage does not synchronize with a popup\n // of the same domain, indexedDB is used for persistent storage. These\n // browsers include IE11 and Edge.\n // Make sure it is supported (IE11 and Edge private mode does not support\n // that).\n if (fireauth.util.isLocalStorageNotSynchronized()) {\n // In such browsers, if indexedDB is not supported, an iframe cannot be\n // notified of the popup sign in result.\n return !!goog.global['indexedDB'];\n }\n return true;\n }\n } catch (e) {\n // localStorage is not available from a worker. Test availability of\n // indexedDB.\n return fireauth.util.isWorker() && !!goog.global['indexedDB'];\n }\n return false;\n};\n\n\n/**\n * This guards against leaking Cordova support before official launch.\n * This field will be removed or updated to return true when the new feature is\n * ready for launch.\n * @return {boolean} Whether Cordova OAuth support is enabled.\n */\nfireauth.util.isCordovaOAuthEnabled = function() {\n return false;\n};\n\n\n/**\n * @return {boolean} Whether popup and redirect operations are supported in the\n * current environment.\n */\nfireauth.util.isPopupRedirectSupported = function() {\n // Popup and redirect are supported in an environment where the container\n // origin can be securely whitelisted.\n return (fireauth.util.isHttpOrHttps() ||\n fireauth.util.isChromeExtension() ||\n fireauth.util.isAndroidOrIosCordovaScheme()) &&\n // React Native with remote debugging reports its location.protocol as\n // http.\n !fireauth.util.isNativeEnvironment() &&\n // Local storage has to be supported for browser popup and redirect\n // operations to work.\n fireauth.util.isWebStorageSupported() &&\n // DOM, popups and redirects are not supported within a worker.\n !fireauth.util.isWorker();\n};\n\n\n/**\n * @return {boolean} Whether the current environment is http or https.\n */\nfireauth.util.isHttpOrHttps = function() {\n return fireauth.util.getCurrentScheme() === 'http:' ||\n fireauth.util.getCurrentScheme() === 'https:';\n};\n\n\n/** @return {?string} The current URL scheme. */\nfireauth.util.getCurrentScheme = function() {\n return (goog.global['location'] && goog.global['location']['protocol']) ||\n null;\n};\n\n\n/**\n * Checks whether the current page is a Chrome extension.\n * @return {boolean} Whether the current page is a Chrome extension.\n */\nfireauth.util.isChromeExtension = function() {\n return fireauth.util.getCurrentScheme() === 'chrome-extension:';\n};\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {boolean} Whether the current browser is running in an iOS\n * environment.\n */\nfireauth.util.isIOS = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n return !!ua.toLowerCase().match(/iphone|ipad|ipod/);\n};\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {boolean} Whether the current browser is running in an Android\n * environment.\n */\nfireauth.util.isAndroid = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n return !!ua.toLowerCase().match(/android/);\n};\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {boolean} Whether the opener of a popup cannot communicate with the\n * popup while it is in the foreground.\n */\nfireauth.util.runsInBackground = function(opt_userAgent) {\n // TODO: split this check into 2, one check that opener can access\n // popup, another check that storage synchronizes between popup and opener.\n // Popup events fail in iOS version 7 (lowest version we currently support)\n // browsers. When the popup is triggered, the opener is unable to redirect\n // the popup url, close the popup and in some cases will miss the storage\n // event triggered when localStorage is changed.\n // Extend this to all mobile devices. This behavior is more likely to work\n // cross mobile platforms.\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n if (fireauth.util.isMobileBrowser(ua)) {\n return false;\n } else if (fireauth.util.getBrowserName(ua) ==\n fireauth.util.BrowserName.FIREFOX) {\n // Latest version of Firefox 47.0 does not allow you to access properties on\n // the popup window from the opener.\n return false;\n }\n return true;\n};\n\n\n/**\n * Stringifies an object, retuning null if the object is not defined.\n * @param {*} obj The raw object.\n * @return {?string} The JSON-serialized object.\n */\nfireauth.util.stringifyJSON = function(obj) {\n if (typeof obj === 'undefined') {\n return null;\n }\n return goog.json.serialize(obj);\n};\n\n\n/**\n * @param {!Object} obj The original object.\n * @return {!Object} A copy of the original object with all entries that are\n * null or undefined removed.\n */\nfireauth.util.copyWithoutNullsOrUndefined = function(obj) {\n // The processed copy to return.\n var trimmedObj = {};\n // Remove all empty fields from data, allow zero and false booleans.\n for (var key in obj) {\n if (obj.hasOwnProperty(key) &&\n obj[key] !== null &&\n obj[key] !== undefined) {\n trimmedObj[key] = obj[key];\n }\n }\n return trimmedObj;\n};\n\n\n/**\n * Removes all key/pairs with the specified keys from the given object.\n * @param {!Object} obj The object to process.\n * @param {!Array<string>} keys The list of keys to remove.\n * @return {!Object} The object with the keys removed.\n */\nfireauth.util.removeEntriesWithKeys = function(obj, keys) {\n // Clone object.\n var copy = goog.object.clone(obj);\n // Traverse keys.\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n // If key found in object, remove it.\n if (key in copy) {\n delete copy[key];\n }\n }\n // Returned filtered copy.\n return copy;\n};\n\n\n/**\n * Parses a JSON string, returning undefined if null is passed.\n * @param {?string} json The JSON-serialized object.\n * @return {*} The raw object.\n */\nfireauth.util.parseJSON = function(json) {\n if (json === null) {\n return undefined;\n }\n\n // Do not use goog.json.parse since it uses eval underneath to support old\n // browsers that do not provide JSON.parse. The recommended Content Security\n // Policy does not allow unsafe-eval in some environments like Chrome\n // extensions. Usage of eval is not recommend in Chrome in general.\n // Use native parsing instead via JSON.parse. This is provided in our list\n // of supported browsers.\n return JSON.parse(json);\n};\n\n\n/**\n * @param {?string=} opt_prefix An optional prefix string to prepend to ID.\n * @return {string} The generated event ID used to identify a generic event.\n */\nfireauth.util.generateEventId = function(opt_prefix) {\n return opt_prefix ? opt_prefix : '' +\n Math.floor(Math.random() * 1000000000).toString();\n};\n\n\n/**\n * @param {?string=} opt_userAgent The optional user agent.\n * @return {boolean} Whether an embedded iframe can sync to web storage changes.\n * Web storage sync fails in Safari desktop browsers and iOS mobile\n * browsers.\n */\nfireauth.util.iframeCanSyncWebStorage = function(opt_userAgent) {\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n if (fireauth.util.getBrowserName(ua) == fireauth.util.BrowserName.SAFARI ||\n ua.toLowerCase().match(/iphone|ipad|ipod/)) {\n return false;\n }\n return true;\n};\n\n\n/**\n * Reset unlaoded GApi modules. If gapi.load fails due to a network error,\n * it will stop working after a retrial. This is a hack to fix this issue.\n */\nfireauth.util.resetUnloadedGapiModules = function() {\n // Clear last failed gapi.load state to force next gapi.load to first\n // load the failed gapi.iframes module.\n // Get gapix.beacon context.\n var beacon = goog.global['___jsl'];\n // Get current hint.\n if (beacon && beacon['H']) {\n // Get gapi hint.\n for (var hint in beacon['H']) {\n // Requested modules.\n beacon['H'][hint]['r'] = beacon['H'][hint]['r'] || [];\n // Loaded modules.\n beacon['H'][hint]['L'] = beacon['H'][hint]['L'] || [];\n // Set requested modules to a copy of the loaded modules.\n beacon['H'][hint]['r'] = beacon['H'][hint]['L'].concat();\n // Clear pending callbacks.\n if (beacon['CP']) {\n for (var i = 0; i < beacon['CP'].length; i++) {\n // Remove all failed pending callbacks.\n beacon['CP'][i] = null;\n }\n }\n }\n }\n};\n\n\n/**\n * Returns whether the current device is a mobile device. Mobile browsers and\n * React-Native environments are considered mobile devices.\n * @param {?string=} opt_userAgent The optional navigator user agent.\n * @param {?fireauth.util.Env=} opt_env The optional environment.\n * @return {boolean} Whether the current device is a mobile device or not.\n */\nfireauth.util.isMobileDevice = function(opt_userAgent, opt_env) {\n // Get user agent.\n var ua = opt_userAgent || fireauth.util.getUserAgentString();\n // Get environment.\n var environment = opt_env || fireauth.util.getEnvironment();\n return fireauth.util.isMobileBrowser(ua) ||\n environment === fireauth.util.Env.REACT_NATIVE;\n};\n\n\n/**\n * @param {?Object=} opt_navigator The optional navigator object typically used\n * for testing.\n * @return {boolean} Whether the app is currently online. If offline, false is\n * returned. If this cannot be determined, true is returned.\n */\nfireauth.util.isOnline = function(opt_navigator) {\n var navigator = opt_navigator || goog.global['navigator'];\n if (navigator &&\n typeof navigator['onLine'] === 'boolean' &&\n // Apply only for traditional web apps and Chrome extensions.\n // This is especially true for Cordova apps which have unreliable\n // navigator.onLine behavior unless cordova-plugin-network-information is\n // installed which overwrites the native navigator.onLine value and\n // defines navigator.connection.\n (fireauth.util.isHttpOrHttps() ||\n fireauth.util.isChromeExtension() ||\n typeof navigator['connection'] !== 'undefined')) {\n return navigator['onLine'];\n }\n // If we can't determine the state, assume it is online.\n return true;\n};\n\n\n/**\n * @param {?Object=} opt_navigator The object with navigator data, defaulting\n * to window.navigator if unspecified.\n * @return {?string} The user's preferred language. Returns null if\n */\nfireauth.util.getUserLanguage = function(opt_navigator) {\n var navigator = opt_navigator || goog.global['navigator'];\n if (!navigator) {\n return null;\n }\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n navigator['languages'] && navigator['languages'][0] ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigator['language'] ||\n // IE <= 10.\n navigator['userLanguage'] ||\n // Couldn't determine language.\n null\n );\n};\n\n\n/**\n * A structure to help pick between a range of long and short delay durations\n * depending on the current environment. In general, the long delay is used for\n * mobile environments whereas short delays are used for desktop environments.\n * @param {number} shortDelay The short delay duration.\n * @param {number} longDelay The long delay duration.\n * @param {?string=} opt_userAgent The optional navigator user agent.\n * @param {?fireauth.util.Env=} opt_env The optional environment.\n * @constructor\n */\nfireauth.util.Delay = function(shortDelay, longDelay, opt_userAgent, opt_env) {\n // Internal error when improperly initialized.\n if (shortDelay > longDelay) {\n throw new Error('Short delay should be less than long delay!');\n }\n /**\n * @private @const {number} The short duration delay used for desktop\n * environments.\n */\n this.shortDelay_ = shortDelay;\n /**\n * @private @const {number} The long duration delay used for mobile\n * environments.\n */\n this.longDelay_ = longDelay;\n /** @private @const {boolean} Whether the environment is a mobile one. */\n this.isMobile_ = fireauth.util.isMobileDevice(opt_userAgent, opt_env);\n};\n\n\n/**\n * The default value for the offline delay timeout in ms.\n * @const {number}\n * @private\n */\nfireauth.util.Delay.OFFLINE_DELAY_MS_ = 5000;\n\n\n/**\n * @return {number} The delay that matches with the current environment.\n */\nfireauth.util.Delay.prototype.get = function() {\n // navigator.onLine is unreliable in some cases.\n // Failing hard in those cases may make it impossible to recover for end user.\n // Waiting for the regular full duration when there is no network can result\n // in a bad experience.\n // Instead return a short timeout duration. If there is no network connection,\n // the user would wait 5 seconds to detect that. If there is a connection\n // (false alert case), the user still has the ability to try to send the\n // request. If it fails (timeout too short), they can still retry.\n if (!fireauth.util.isOnline()) {\n // Pick the shorter timeout.\n return Math.min(fireauth.util.Delay.OFFLINE_DELAY_MS_, this.shortDelay_);\n }\n // If running in a mobile environment, return the long delay, otherwise\n // return the short delay.\n // This could be improved in the future to dynamically change based on other\n // variables instead of just reading the current environment.\n return this.isMobile_ ? this.longDelay_ : this.shortDelay_;\n};\n\n\n/**\n * @return {boolean} Whether the app is visible in the foreground. This uses\n * document.visibilityState. For browsers that do not support it, this is\n * always true.\n */\nfireauth.util.isAppVisible = function() {\n // https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\n var doc = goog.global.document;\n // Check if supported.\n if (doc && typeof doc['visibilityState'] !== 'undefined') {\n // Check if visible.\n return doc['visibilityState'] == 'visible';\n }\n // API not supported in current browser, default to true.\n return true;\n};\n\n\n/**\n * @return {!goog.Promise} A promise that resolves when the app is visible in\n * the foreground.\n */\nfireauth.util.onAppVisible = function() {\n var doc = goog.global.document;\n // Visibility change listener reference.\n var onVisibilityChange = null;\n if (fireauth.util.isAppVisible() || !doc) {\n // Visible or non browser environment.\n return goog.Promise.resolve();\n } else {\n // Invisible and in browser environment.\n return new goog.Promise(function(resolve, reject) {\n // On visibility change listener.\n onVisibilityChange = function(event) {\n // App is visible.\n if (fireauth.util.isAppVisible()) {\n // Unregister event listener.\n doc.removeEventListener(\n 'visibilitychange', onVisibilityChange, false);\n // Resolve promise.\n resolve();\n }\n };\n // Listen to visibility change.\n doc.addEventListener('visibilitychange', onVisibilityChange, false);\n }).thenCatch(function(error) {\n // In case this promise was cancelled, make sure it unlistens to\n // visibilitychange event.\n doc.removeEventListener('visibilitychange', onVisibilityChange, false);\n // Rethrow the same error.\n throw error;\n });\n }\n};\n\n\n/**\n * Logs a warning message to the console, if the console is available.\n * @param {string} message\n */\nfireauth.util.consoleWarn = function(message) {\n if (typeof console !== 'undefined' && typeof console.warn === 'function') {\n console.warn(message);\n }\n};\n\n\n/**\n * Parses a UTC time stamp string or number and returns the corresponding UTC\n * date string if valid. Otherwise, returns null.\n * @param {?string|number} utcTimestamp The UTC timestamp number or string.\n * @return {?string} The corresponding UTC date string. Null if invalid.\n */\nfireauth.util.utcTimestampToDateString = function(utcTimestamp) {\n try {\n // Convert to date object.\n var date = new Date(parseInt(utcTimestamp, 10));\n // Test date is valid.\n if (!isNaN(date.getTime()) &&\n // Confirm that utcTimestamp is numeric.\n goog.string.isNumeric(utcTimestamp)) {\n // Convert to UTC date string.\n return date.toUTCString();\n }\n } catch (e) {\n // Do nothing. null will be returned.\n }\n return null;\n};\n\n\n/** @return {boolean} Whether indexedDB is available. */\nfireauth.util.isIndexedDBAvailable = function() {\n return !!goog.global['indexedDB'];\n};\n\n\n/** @return {boolean} Whether current mode is Auth handler or iframe. */\nfireauth.util.isAuthHandlerOrIframe = function() {\n return !!(fireauth.util.getObjectRef('fireauth.oauthhelper', goog.global) ||\n fireauth.util.getObjectRef('fireauth.iframe', goog.global));\n};\n\n\n/** @return {boolean} Whether indexedDB is used to persist storage. */\nfireauth.util.persistsStorageWithIndexedDB = function() {\n // This will cover:\n // IE11, Edge when indexedDB is available (this is unavailable in InPrivate\n // mode). (SDK, OAuth handler and iframe)\n // Any environment where indexedDB is available (SDK only).\n\n // In a browser environment, when an iframe and a popup web storage are not\n // synchronized, use the indexedDB fireauth.storage.Storage implementation.\n return (fireauth.util.isLocalStorageNotSynchronized() ||\n !fireauth.util.isAuthHandlerOrIframe()) &&\n fireauth.util.isIndexedDBAvailable();\n};\n\n\n/** Sets the no-referrer meta tag in the document head if applicable. */\nfireauth.util.setNoReferrer = function() {\n var doc = goog.global.document;\n if (doc) {\n try {\n var meta = goog.dom.createDom(goog.dom.TagName.META, {\n 'name': 'referrer',\n 'content': 'no-referrer'\n });\n var headCollection = goog.dom.getElementsByTagName(goog.dom.TagName.HEAD);\n // Append meta tag to head.\n if (headCollection.length) {\n headCollection[0].appendChild(meta);\n }\n } catch (e) {\n // Best effort approach.\n }\n }\n};\n\n\n/** @return {?ServiceWorker} The servicerWorker controller if available. */\nfireauth.util.getServiceWorkerController = function() {\n var navigator = goog.global['navigator'];\n return (navigator &&\n navigator.serviceWorker &&\n navigator.serviceWorker.controller) || null;\n};\n\n\n/** @return {?WorkerGlobalScope} The worker global scope if available. */\nfireauth.util.getWorkerGlobalScope = function() {\n return fireauth.util.isWorker() ? /** @type {!WorkerGlobalScope} */ (self) :\n null;\n};\n\n/**\n * @return {!goog.Promise<?ServiceWorker>} A promise that resolves with the\n * service worker. This will resolve only when a service worker becomes\n * available. If no service worker is supported, it will resolve with null.\n */\nfireauth.util.getActiveServiceWorker = function() {\n var navigator = goog.global['navigator'];\n if (navigator && navigator.serviceWorker) {\n return goog.Promise.resolve()\n .then(function() {\n return navigator.serviceWorker.ready;\n })\n .then(function(registration) {\n return /** @type {?ServiceWorker} */ (registration.active || null);\n })\n .thenCatch(function(error) {\n return null;\n });\n }\n return goog.Promise.resolve(/** @type {?ServiceWorker} */ (null));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for window manipulation.\n */\n\n\ngoog.provide('goog.window');\n\ngoog.require('goog.dom');\ngoog.require('goog.dom.TagName');\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.SafeUrl');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.labs.userAgent.platform');\ngoog.require('goog.string');\ngoog.require('goog.string.Const');\ngoog.require('goog.userAgent');\n\n\n/**\n * Default height for popup windows\n * @type {number}\n */\ngoog.window.DEFAULT_POPUP_HEIGHT = 500;\n\n\n/**\n * Default width for popup windows\n * @type {number}\n */\ngoog.window.DEFAULT_POPUP_WIDTH = 690;\n\n\n/**\n * Default target for popup windows\n * @type {string}\n */\ngoog.window.DEFAULT_POPUP_TARGET = 'google_popup';\n\n\n/**\n * @return {!Window}\n * @suppress {checkTypes}\n * @private\n */\ngoog.window.createFakeWindow_ = function() {\n return /** @type {!Window} */ ({});\n};\n\n/**\n * Opens a new window.\n *\n * @param {!goog.html.SafeUrl|string|!Object|null} linkRef If an Object with an\n * 'href' attribute (such as HTMLAnchorElement) is passed then the value of\n * 'href' is used, otherwise its toString method is called. Note that if a\n * string|Object is used, it will be sanitized with SafeUrl.sanitize().\n *\n * @param {?Object=} opt_options supports the following options:\n * 'target': (string) target (window name). If null, linkRef.target will\n * be used.\n * 'width': (number) window width.\n * 'height': (number) window height.\n * 'top': (number) distance from top of screen\n * 'left': (number) distance from left of screen\n * 'toolbar': (boolean) show toolbar\n * 'scrollbars': (boolean) show scrollbars\n * 'location': (boolean) show location\n * 'statusbar': (boolean) show statusbar\n * 'menubar': (boolean) show menubar\n * 'resizable': (boolean) resizable\n * 'noreferrer': (boolean) whether to attempt to remove the referrer header\n * from the request headers. Does this by opening a blank window that\n * then redirects to the target url, so users may see some flickering.\n * 'noopener': (boolean) whether to remove the `opener` property from the\n * window object of the newly created window. The property contains a\n * reference to the original window, and can be used to launch a\n * reverse tabnabbing attack.\n *\n * @param {?Window=} opt_parentWin Parent window that should be used to open the\n * new window.\n *\n * @return {?Window} Returns the window object that was opened. This returns\n * null if a popup blocker prevented the window from being\n * opened. In case when a new window is opened in a different\n * browser sandbox (such as iOS standalone mode), the returned\n * object is a emulated Window object that functions as if\n * a cross-origin window has been opened.\n */\ngoog.window.open = function(linkRef, opt_options, opt_parentWin) {\n if (!opt_options) {\n opt_options = {};\n }\n var parentWin = opt_parentWin || window;\n\n /** @type {!goog.html.SafeUrl} */\n var safeLinkRef;\n\n if (linkRef instanceof goog.html.SafeUrl) {\n safeLinkRef = linkRef;\n } else {\n // HTMLAnchorElement has a toString() method with the same behavior as\n // goog.Uri in all browsers except for Safari, which returns\n // '[object HTMLAnchorElement]'. We check for the href first, then\n // assume that it's a goog.Uri or String otherwise.\n /**\n * @type {string|!goog.string.TypedString}\n * @suppress {missingProperties}\n */\n var url =\n typeof linkRef.href != 'undefined' ? linkRef.href : String(linkRef);\n safeLinkRef = goog.html.SafeUrl.sanitize(url);\n }\n\n /** @suppress {missingProperties} loose references to 'target' */\n /** @suppress {strictMissingProperties} */\n var target = opt_options.target || linkRef.target;\n\n var sb = [];\n for (var option in opt_options) {\n switch (option) {\n case 'width':\n case 'height':\n case 'top':\n case 'left':\n sb.push(option + '=' + opt_options[option]);\n break;\n case 'target':\n case 'noopener':\n case 'noreferrer':\n break;\n default:\n sb.push(option + '=' + (opt_options[option] ? 1 : 0));\n }\n }\n var optionString = sb.join(',');\n\n var newWin;\n if (goog.labs.userAgent.platform.isIos() && parentWin.navigator &&\n parentWin.navigator['standalone'] && target && target != '_self') {\n // iOS in standalone mode disregards \"target\" in window.open and always\n // opens new URL in the same window. The workaround is to create an \"A\"\n // element and send a click event to it.\n // Notice that the \"A\" tag does NOT have to be added to the DOM.\n\n var a = goog.dom.createElement(goog.dom.TagName.A);\n goog.dom.safe.setAnchorHref(a, safeLinkRef);\n\n a.setAttribute('target', target);\n if (opt_options['noreferrer']) {\n a.setAttribute('rel', 'noreferrer');\n }\n\n var click = /** @type {!MouseEvent} */ (document.createEvent('MouseEvent'));\n click.initMouseEvent(\n 'click',\n true, // canBubble\n true, // cancelable\n parentWin,\n 1); // detail = mousebutton\n a.dispatchEvent(click);\n // New window is not available in this case. Instead, a fake Window object\n // is returned. In particular, it will have window.document undefined. In\n // general, it will appear to most of clients as a Window for a different\n // origin. Since iOS standalone web apps are run in their own sandbox, this\n // is the most appropriate return value.\n newWin = goog.window.createFakeWindow_();\n } else if (opt_options['noreferrer']) {\n // This code used to use meta-refresh to stop the referrer from being\n // included in the request headers. This was the only cross-browser way\n // to remove the referrer circa 2009. However, this never worked in Chrome,\n // and, instead newWin.opener had to be set to null on this browser. This\n // behavior is slated to be removed in Chrome and should not be relied\n // upon. Referrer Policy is the only spec'd and supported way of stripping\n // referrers and works across all current browsers. This is used in\n // addition to the aforementioned tricks.\n //\n // We also set the opener to be set to null in the new window, thus\n // disallowing the opened window from navigating its opener.\n //\n // Detecting user agent and then using a different strategy per browser\n // would allow the referrer to leak in case of an incorrect/missing user\n // agent.\n //\n // Also note that we can't use goog.dom.safe.openInWindow here, as it\n // requires a goog.string.Const 'name' parameter, while we're using plain\n // strings here for target.\n newWin = parentWin.open('', target, optionString);\n\n var sanitizedLinkRef = goog.html.SafeUrl.unwrap(safeLinkRef);\n if (newWin) {\n if (goog.userAgent.EDGE_OR_IE) {\n // IE/EDGE can't parse the content attribute if the url contains\n // a semicolon. We can fix this by adding quotes around the url, but\n // then we can't parse quotes in the URL correctly. We take a\n // best-effort approach.\n //\n // If the URL has semicolons, wrap it in single quotes to protect\n // the semicolons.\n // If the URL has semicolons and single quotes, url-encode the single\n // quotes as well.\n //\n // This is imperfect. Notice that both ' and ; are reserved characters\n // in URIs, so this could do the wrong thing, but at least it will\n // do the wrong thing in only rare cases.\n // ugh.\n if (goog.string.contains(sanitizedLinkRef, ';')) {\n sanitizedLinkRef = \"'\" + sanitizedLinkRef.replace(/'/g, '%27') + \"'\";\n }\n }\n newWin.opener = null;\n\n // TODO(rjamet): Building proper SafeHtml with SafeHtml.createMetaRefresh\n // pulls in a lot of compiled code, which is composed of various unneeded\n // goog.html parts such as SafeStyle.create among others. So, for now,\n // keep the unchecked conversion until we figure out how to make the\n // dependencies of createSafeHtmlTagSecurityPrivateDoNotAccessOrElse less\n // heavy.\n var safeHtml =\n goog.html.uncheckedconversions\n .safeHtmlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from(\n 'b/12014412, meta tag with sanitized URL'),\n '<meta name=\"referrer\" content=\"no-referrer\">' +\n '<meta http-equiv=\"refresh\" content=\"0; url=' +\n goog.string.htmlEscape(sanitizedLinkRef) + '\">');\n\n // During window loading `newWin.document` may be unset in some browsers.\n // Storing and checking a reference to the document prevents NPEs.\n var newDoc = newWin.document;\n if (newDoc) {\n goog.dom.safe.documentWrite(newDoc, safeHtml);\n newDoc.close();\n }\n }\n } else {\n newWin = parentWin.open(\n goog.html.SafeUrl.unwrap(safeLinkRef), target, optionString);\n // Passing in 'noopener' into the 'windowFeatures' param of window.open(...)\n // will yield a feature-deprived browser. This is an known issue, tracked\n // here: https://github.com/whatwg/html/issues/1902\n if (newWin && opt_options['noopener']) {\n newWin.opener = null;\n }\n }\n // newWin is null if a popup blocker prevented the window open.\n return newWin;\n};\n\n\n/**\n * Opens a new window without any real content in it.\n *\n * This can be used to get around popup blockers if you need to open a window\n * in response to a user event, but need to do asynchronous work to determine\n * the URL to open, and then set the URL later.\n *\n * Example usage:\n *\n * var newWin = goog.window.openBlank('Loading...');\n * setTimeout(\n * function() {\n * newWin.location.href = 'http://www.google.com';\n * }, 100);\n *\n * @param {string=} opt_message String to show in the new window. This string\n * will be HTML-escaped to avoid XSS issues.\n * @param {?Object=} opt_options Options to open window with.\n * {@see goog.window.open for exact option semantics}.\n * @param {?Window=} opt_parentWin Parent window that should be used to open the\n * new window.\n * @return {?Window} Returns the window object that was opened. This returns\n * null if a popup blocker prevented the window from being\n * opened.\n */\ngoog.window.openBlank = function(opt_message, opt_options, opt_parentWin) {\n // Open up a window with the loading message and nothing else.\n // This will be interpreted as HTML content type with a missing doctype\n // and html/body tags, but is otherwise acceptable.\n //\n // IMPORTANT: The order of escaping is crucial here in order to avoid XSS.\n // First, HTML-escaping is needed because the result of the JS expression\n // is evaluated as HTML. Second, JS-string escaping is needed; this avoids\n // \\u escaping from inserting HTML tags and \\ from escaping the final \".\n // Finally, URL percent-encoding is done with encodeURI(); this\n // avoids percent-encoding from bypassing HTML and JS escaping.\n //\n // Note: There are other ways the same result could be achieved but the\n // current behavior was preserved when this code was refactored to use\n // SafeUrl, in order to avoid breakage.\n var loadingMessage;\n if (!opt_message) {\n loadingMessage = '';\n } else {\n loadingMessage =\n goog.string.escapeString(goog.string.htmlEscape(opt_message));\n }\n var url = goog.html.uncheckedconversions\n .safeUrlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from(\n 'b/12014412, encoded string in javascript: URL'),\n 'javascript:\"' + encodeURI(loadingMessage) + '\"');\n return /** @type {?Window} */ (\n goog.window.open(url, opt_options, opt_parentWin));\n};\n\n\n/**\n * Raise a help popup window, defaulting to \"Google standard\" size and name.\n *\n * (If your project is using GXPs, consider using {@link PopUpLink.gxp}.)\n *\n* @param {?goog.html.SafeUrl|string|?Object} linkRef If an Object with an 'href'\n * attribute (such as HTMLAnchorElement) is passed then the value of 'href'\n * is used, otherwise otherwise its toString method is called. Note that\n * if a string|Object is used, it will be sanitized with SafeUrl.sanitize().\n *\n * @param {?Object=} opt_options Options to open window with.\n * {@see goog.window.open for exact option semantics}\n * Additional wrinkles to the options:\n * - if 'target' field is null, linkRef.target will be used. If *that's*\n * null, the default is \"google_popup\".\n * - if 'width' field is not specified, the default is 690.\n * - if 'height' field is not specified, the default is 500.\n *\n * @return {boolean} true if the window was not popped up, false if it was.\n */\ngoog.window.popup = function(linkRef, opt_options) {\n if (!opt_options) {\n opt_options = {};\n }\n\n // set default properties\n opt_options['target'] = opt_options['target'] || linkRef['target'] ||\n goog.window.DEFAULT_POPUP_TARGET;\n opt_options['width'] =\n opt_options['width'] || goog.window.DEFAULT_POPUP_WIDTH;\n opt_options['height'] =\n opt_options['height'] || goog.window.DEFAULT_POPUP_HEIGHT;\n\n var newWin = goog.window.open(linkRef, opt_options);\n if (!newWin) {\n return true;\n }\n newWin.focus();\n\n return false;\n};\n","// Copyright 2013 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 Closure user agent platform detection.\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For more information on browser brand, rendering engine, or device see the\n * other sub-namespaces in goog.labs.userAgent (browser, engine, and device\n * respectively).\n */\n\ngoog.provide('goog.labs.userAgent.platform');\n\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.string');\n\n\n/**\n * @return {boolean} Whether the platform is Android.\n */\ngoog.labs.userAgent.platform.isAndroid = function() {\n return goog.labs.userAgent.util.matchUserAgent('Android');\n};\n\n\n/**\n * @return {boolean} Whether the platform is iPod.\n */\ngoog.labs.userAgent.platform.isIpod = function() {\n return goog.labs.userAgent.util.matchUserAgent('iPod');\n};\n\n\n/**\n * @return {boolean} Whether the platform is iPhone.\n */\ngoog.labs.userAgent.platform.isIphone = function() {\n return goog.labs.userAgent.util.matchUserAgent('iPhone') &&\n !goog.labs.userAgent.util.matchUserAgent('iPod') &&\n !goog.labs.userAgent.util.matchUserAgent('iPad');\n};\n\n\n/**\n * @return {boolean} Whether the platform is iPad.\n */\ngoog.labs.userAgent.platform.isIpad = function() {\n return goog.labs.userAgent.util.matchUserAgent('iPad');\n};\n\n\n/**\n * @return {boolean} Whether the platform is iOS.\n */\ngoog.labs.userAgent.platform.isIos = function() {\n return goog.labs.userAgent.platform.isIphone() ||\n goog.labs.userAgent.platform.isIpad() ||\n goog.labs.userAgent.platform.isIpod();\n};\n\n\n/**\n * @return {boolean} Whether the platform is Mac.\n */\ngoog.labs.userAgent.platform.isMacintosh = function() {\n return goog.labs.userAgent.util.matchUserAgent('Macintosh');\n};\n\n\n/**\n * Note: ChromeOS is not considered to be Linux as it does not report itself\n * as Linux in the user agent string.\n * @return {boolean} Whether the platform is Linux.\n */\ngoog.labs.userAgent.platform.isLinux = function() {\n return goog.labs.userAgent.util.matchUserAgent('Linux');\n};\n\n\n/**\n * @return {boolean} Whether the platform is Windows.\n */\ngoog.labs.userAgent.platform.isWindows = function() {\n return goog.labs.userAgent.util.matchUserAgent('Windows');\n};\n\n\n/**\n * @return {boolean} Whether the platform is ChromeOS.\n */\ngoog.labs.userAgent.platform.isChromeOS = function() {\n return goog.labs.userAgent.util.matchUserAgent('CrOS');\n};\n\n/**\n * @return {boolean} Whether the platform is Chromecast.\n */\ngoog.labs.userAgent.platform.isChromecast = function() {\n return goog.labs.userAgent.util.matchUserAgent('CrKey');\n};\n\n/**\n * @return {boolean} Whether the platform is KaiOS.\n */\ngoog.labs.userAgent.platform.isKaiOS = function() {\n return goog.labs.userAgent.util.matchUserAgentIgnoreCase('KaiOS');\n};\n\n/**\n * The version of the platform. We only determine the version for Windows,\n * Mac, and Chrome OS. It doesn't make much sense on Linux. For Windows, we only\n * look at the NT version. Non-NT-based versions (e.g. 95, 98, etc.) are given\n * version 0.0.\n *\n * @return {string} The platform version or empty string if version cannot be\n * determined.\n */\ngoog.labs.userAgent.platform.getVersion = function() {\n var userAgentString = goog.labs.userAgent.util.getUserAgent();\n var version = '', re;\n if (goog.labs.userAgent.platform.isWindows()) {\n re = /Windows (?:NT|Phone) ([0-9.]+)/;\n var match = re.exec(userAgentString);\n if (match) {\n version = match[1];\n } else {\n version = '0.0';\n }\n } else if (goog.labs.userAgent.platform.isIos()) {\n re = /(?:iPhone|iPod|iPad|CPU)\\s+OS\\s+(\\S+)/;\n var match = re.exec(userAgentString);\n // Report the version as x.y.z and not x_y_z\n version = match && match[1].replace(/_/g, '.');\n } else if (goog.labs.userAgent.platform.isMacintosh()) {\n re = /Mac OS X ([0-9_.]+)/;\n var match = re.exec(userAgentString);\n // Note: some old versions of Camino do not report an OSX version.\n // Default to 10.\n version = match ? match[1].replace(/_/g, '.') : '10';\n } else if (goog.labs.userAgent.platform.isKaiOS()) {\n re = /(?:KaiOS)\\/(\\S+)/i;\n var match = re.exec(userAgentString);\n version = match && match[1];\n } else if (goog.labs.userAgent.platform.isAndroid()) {\n re = /Android\\s+([^\\);]+)(\\)|;)/;\n var match = re.exec(userAgentString);\n version = match && match[1];\n } else if (goog.labs.userAgent.platform.isChromeOS()) {\n re = /(?:CrOS\\s+(?:i686|x86_64)\\s+([0-9.]+))/;\n var match = re.exec(userAgentString);\n version = match && match[1];\n }\n return version || '';\n};\n\n\n/**\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the browser version is higher or the same as the\n * given version.\n */\ngoog.labs.userAgent.platform.isVersionOrHigher = function(version) {\n return goog.string.compareVersions(\n goog.labs.userAgent.platform.getVersion(), version) >= 0;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 utilities for displaying deprecation notices.\n */\ngoog.provide('fireauth.deprecation');\ngoog.provide('fireauth.deprecation.Deprecations');\ngoog.require('fireauth.util');\n\n\n/**\n * An enum of valid notices to display. All deprecation notices must be in this\n * enum. Deprecation messages should be unique and provide the full context\n * of what is deprecated (e.g. the fully qualified path to a method).\n * @enum {string}\n */\nfireauth.deprecation.Deprecations = {\n LINK_WITH_CREDENTIAL: 'firebase.User.prototype.linkAndRetrieveDataWithCrede' +\n 'ntial is deprecated. Please use firebase.User.prototype.linkWithCreden' +\n 'tial instead.',\n REAUTH_WITH_CREDENTIAL: 'firebase.User.prototype.reauthenticateAndRetrieveD' +\n 'ataWithCredential is deprecated. Please use firebase.User.prototype.re' +\n 'authenticateWithCredential instead.',\n SIGN_IN_WITH_CREDENTIAL: 'firebase.auth.Auth.prototype.signInAndRetrieveDat' +\n 'aWithCredential is deprecated. Please use firebase.auth.Auth.prototype' +\n '.signInWithCredential instead.'\n};\n\n\n/**\n * Keeps track of notices that were already displayed.\n * @type {!Object<fireauth.deprecation.Deprecations, boolean>}\n * @private\n */\nfireauth.deprecation.shownMessages_ = {};\n\n\n/**\n * Logs a deprecation notice to the developer.\n * @param {!fireauth.deprecation.Deprecations} message\n */\nfireauth.deprecation.log = function(message) {\n if (fireauth.deprecation.shownMessages_[message]) {\n return;\n }\n fireauth.deprecation.shownMessages_[message] = true;\n fireauth.util.consoleWarn(message);\n};\n\n\n/**\n * Resets the displayed deprecation notices.\n */\nfireauth.deprecation.resetForTesting = function() {\n fireauth.deprecation.shownMessages_ =\n /** @type {!Object<fireauth.deprecation.Deprecations, boolean>} */ ({});\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 methods for manipulating objects.\n */\n\ngoog.provide('fireauth.object');\n\ngoog.require('fireauth.deprecation');\ngoog.require('fireauth.deprecation.Deprecations');\n\n\n/**\n * Checks whether the defineProperty method allows to change the value of\n * the property.\n * @return {boolean} Whether the defineProperty method allows to change the\n * value of the property.\n * @private\n */\nfireauth.object.isReadonlyConfigurable_ = function() {\n // Android 2.3 stock browser doesn't allow to change the value of\n // a read-only property once defined.\n try {\n var obj = {};\n Object.defineProperty(obj, 'abcd', {\n configurable: true,\n enumerable: true,\n value: 1\n });\n Object.defineProperty(obj, 'abcd', {\n configurable: true,\n enumerable: true,\n value: 2\n });\n return obj['abcd'] == 2;\n } catch (e) {\n return false;\n }\n};\n\n\n/**\n * @private {boolean} Whether the defineProperty method allows to change the\n * value of the property.\n */\nfireauth.object.readonlyConfigurable_ =\n fireauth.object.isReadonlyConfigurable_();\n\n\n/**\n * Defines a property on an object that is not writable by clients. However, the\n * property can be overwritten within the Firebase library through subsequent\n * calls to setReadonlyProperty.\n *\n * In browsers that do not support read-only properties (notably IE8 and below),\n * fall back to writable properties.\n *\n * @param {!Object} obj The object to which we add the property.\n * @param {string} key The name of the property.\n * @param {*} value The desired value.\n */\nfireauth.object.setReadonlyProperty = function(obj, key, value) {\n if (fireauth.object.readonlyConfigurable_) {\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n value: value\n });\n } else {\n obj[key] = value;\n }\n};\n\n\n/**\n * Defines a deprecated property, which emits a warning if the developer tries\n * to use it.\n *\n * In browsers that do not support getters, we fall back to a normal property\n * with no message.\n *\n * @param {!Object} obj The object to which we add the property.\n * @param {string} key The name of the deprecated property.\n * @param {*} value The desired value.\n * @param {!fireauth.deprecation.Deprecations} deprecationMessage The\n * deprecation warning to display.\n */\nfireauth.object.setDeprecatedReadonlyProperty = function(obj, key, value,\n deprecationMessage) {\n if (fireauth.object.readonlyConfigurable_) {\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: true,\n get: function() {\n fireauth.deprecation.log(deprecationMessage);\n return value;\n }\n });\n } else {\n obj[key] = value;\n }\n};\n\n\n/**\n * Defines properties on an object that are not writable by clients, equivalent\n * to many calls to setReadonlyProperty.\n * @param {!Object} obj The object to which we add the properties.\n * @param {?Object<string, *>} props An object that maps the keys and values\n * that we wish to add.\n */\nfireauth.object.setReadonlyProperties = function(obj, props) {\n if (!props) {\n return;\n }\n\n for (var key in props) {\n if (props.hasOwnProperty(key)) {\n fireauth.object.setReadonlyProperty(obj, key, props[key]);\n }\n }\n};\n\n\n/**\n * Makes a shallow read-only copy of an object. The writability of any child\n * objects will not be affected.\n * @param {?Object} obj The object that we wish to copy.\n * @return {!Object}\n */\nfireauth.object.makeReadonlyCopy = function(obj) {\n var output = {};\n fireauth.object.setReadonlyProperties(output, obj);\n return output;\n};\n\n\n/**\n * Makes a shallow writable copy of a read-only object. The writability of any\n * child objects will not be affected.\n * @param {?Object} obj The object that we wish to copy.\n * @return {!Object}\n */\nfireauth.object.makeWritableCopy = function(obj) {\n var output = {};\n for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n output[key] = obj[key];\n }\n }\n return output;\n};\n\n\n/**\n * Returns true if the all the specified fields are present in obj and are not\n * null, undefined, or the empty string. If the field list is empty, returns\n * true regardless of the value of obj.\n * @param {?Object=} opt_obj The object.\n * @param {?Array<string>=} opt_fields The desired fields of the object.\n * @return {boolean} True if obj has all the specified fields.\n */\nfireauth.object.hasNonEmptyFields = function(opt_obj, opt_fields) {\n if (!opt_fields || !opt_fields.length) {\n return true;\n }\n if (!opt_obj) {\n return false;\n }\n for (var i = 0; i < opt_fields.length; i++) {\n var field = opt_obj[opt_fields[i]];\n if (field === undefined || field === null || field === '') {\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * Traverses the specified object and creates a read-only deep copy of it.\n * This will fail when circular references are contained within the object.\n * @param {*} obj The object to make a read-only copy from.\n * @return {*} A Read-only copy of the obj specified.\n */\nfireauth.object.unsafeCreateReadOnlyCopy = function(obj) {\n var copy = obj;\n if (typeof obj == 'object' && obj != null) {\n // Make the right type of copy.\n copy = 'length' in obj ? [] : {};\n // Make a deep copy.\n for (var key in obj) {\n fireauth.object.setReadonlyProperty(\n copy, key, fireauth.object.unsafeCreateReadOnlyCopy(obj[key]));\n }\n }\n // Return the copy.\n return copy;\n};\n\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 multi-factor enrollment information.\n */\n\ngoog.provide('fireauth.MultiFactorInfo');\ngoog.provide('fireauth.PhoneMultiFactorInfo');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.object');\n\n\n/**\n * Abstract class representing a `firebase.auth.MultiFactorInfo` interface.\n * This is typically parsed from a server response.\n * @param {?Object} resp The server response.\n * @abstract\n * @constructor\n */\nfireauth.MultiFactorInfo = function(resp) {\n var factorId = resp && this.getFactorId(resp);\n if (factorId && resp &&\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.MFA_ENROLLMENT_ID]) {\n fireauth.object.setReadonlyProperty(\n this,\n 'uid',\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.MFA_ENROLLMENT_ID]);\n fireauth.object.setReadonlyProperty(\n this,\n 'displayName',\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.DISPLAY_NAME] || null);\n var enrollmentTime = null;\n // Encoded using [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format.\n // For example, \"2017-01-15T01:30:15.01Z\".\n // This can be parsed directly in modern browsers via Date constructor.\n // This can be computed using Data.prototype.toISOString.\n if (resp[fireauth.MultiFactorInfo.MfaEnrollmentField.ENROLLED_AT]) {\n enrollmentTime = new Date(\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.ENROLLED_AT])\n .toUTCString();\n }\n fireauth.object.setReadonlyProperty(\n this,\n 'enrollmentTime',\n enrollmentTime);\n fireauth.object.setReadonlyProperty(\n this,\n 'factorId',\n factorId);\n } else {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'Internal assert: invalid MultiFactorInfo object');\n }\n};\n\n\n/** @return {!Object} The plain object representation. */\nfireauth.MultiFactorInfo.prototype.toPlainObject = function() {\n return {\n 'uid': this['uid'],\n 'displayName': this['displayName'],\n 'factorId': this['factorId'],\n 'enrollmentTime': this['enrollmentTime']\n };\n};\n\n\n/**\n * Returns the factor ID based on the server response. This function needs to be\n * implemented by the subclass.\n * @param {!Object} resp The server response.\n * @return {?fireauth.constants.SecondFactorType} The factor ID based on the\n * response type.\n * @protected\n */\nfireauth.MultiFactorInfo.prototype.getFactorId = goog.abstractMethod;\n\n\n/**\n * Returns the corresponding `firebase.auth.MultiFactor` instance if the\n * server response maps to one. Otherwise, null is returned.\n * @param {?Object} resp The server response.\n * @return {?fireauth.MultiFactorInfo} The corresponding\n * `firebase.auth.MultiFactorInfo` instance, null otherwise.\n */\nfireauth.MultiFactorInfo.fromServerResponse = function(resp) {\n var multiFactorInfo;\n // Only PhoneMultiFactorInfo currently available.\n try {\n multiFactorInfo = new fireauth.PhoneMultiFactorInfo(resp);\n } catch (e) {\n multiFactorInfo = null;\n }\n return multiFactorInfo;\n};\n\n\n/**\n * Returns the corresponding `firebase.auth.MultiFactor` instance if the\n * plain object maps to one. Otherwise, null is returned.\n * @param {?Object} obj The plain object representation.\n * @return {?fireauth.MultiFactorInfo} The corresponding\n * `firebase.auth.MultiFactorInfo` instance, null otherwise.\n */\nfireauth.MultiFactorInfo.fromPlainObject = function(obj) {\n var multiFactorInfo = null;\n var resp = {};\n if (!obj) {\n return null;\n }\n if (obj['uid']) {\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.MFA_ENROLLMENT_ID] =\n obj['uid'];\n }\n if (obj['displayName']) {\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.DISPLAY_NAME] =\n obj['displayName'];\n }\n if (obj['enrollmentTime']) {\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.ENROLLED_AT] =\n new Date(obj['enrollmentTime']).toISOString();\n }\n if (obj['phoneNumber']) {\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.PHONE_INFO] =\n obj['phoneNumber'];\n }\n\n // Only PhoneMultiFactorInfo currently available.\n try {\n multiFactorInfo = new fireauth.PhoneMultiFactorInfo(resp);\n } catch (e) {\n // Ignore error.\n }\n return multiFactorInfo;\n};\n\n\n/**\n * MfaEnrollment server side response fields.\n * @enum {string}\n */\nfireauth.MultiFactorInfo.MfaEnrollmentField = {\n DISPLAY_NAME: 'displayName',\n ENROLLED_AT: 'enrolledAt',\n MFA_ENROLLMENT_ID: 'mfaEnrollmentId',\n PHONE_INFO: 'phoneInfo'\n};\n\n\n/**\n * Initializes a `firebase.auth.PhoneMultiFactorInfo` instance from the provided\n * server response.\n * @param {?Object} resp The server response.\n * @constructor\n * @extends {fireauth.MultiFactorInfo}\n */\nfireauth.PhoneMultiFactorInfo = function(resp) {\n fireauth.PhoneMultiFactorInfo.base(this, 'constructor', resp);\n fireauth.object.setReadonlyProperty(\n this,\n 'phoneNumber',\n // PhoneInfo may be masked for security reasons for sign-in flows after\n // the user signs in with the first factor but hasn't yet proven ownership\n // of the second factor yet.\n // For enrollment flows or for a user already signed in with a second\n // factor, this field should not be masked.\n resp[fireauth.MultiFactorInfo.MfaEnrollmentField.PHONE_INFO]);\n};\ngoog.inherits(\n fireauth.PhoneMultiFactorInfo, fireauth.MultiFactorInfo);\n\n\n/**\n * Implements the factor ID getter based on the response. If the response is an\n * invalid PhoneMultiFactorInfo, null is returned.\n * @param {!Object} resp The server response.\n * @return {?fireauth.constants.SecondFactorType} The phone factor ID.\n * @protected\n * @override\n */\nfireauth.PhoneMultiFactorInfo.prototype.getFactorId = function(resp) {\n return !!resp[fireauth.MultiFactorInfo.MfaEnrollmentField.PHONE_INFO] ?\n fireauth.constants.SecondFactorType.PHONE : null;\n};\n\n\n/**\n * @return {!Object} The plain object representation.\n * @override\n */\nfireauth.PhoneMultiFactorInfo.prototype.toPlainObject = function() {\n var obj = fireauth.PhoneMultiFactorInfo.base(this, 'toPlainObject');\n obj['phoneNumber'] = this['phoneNumber'];\n return obj;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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.auth.ActionCodeInfo class that is returned\n * when calling checkActionCode API and is populated from the server response\n * directly.\n */\n\ngoog.provide('fireauth.ActionCodeInfo');\n\ngoog.require('fireauth.MultiFactorInfo');\ngoog.require('fireauth.object');\n\n\n/**\n * Constructs the action code info object which provides metadata corresponding\n * to action codes. This includes the type of operation (RESET_PASSWORD,\n * VERIFY_EMAIL and RECOVER_EMAIL), the email corresponding to the operation\n * and in case of the recover email flow, the old and new email.\n * @param {!Object} response The server response for checkActionCode.\n * @constructor\n */\nfireauth.ActionCodeInfo = function(response) {\n var data = {};\n // Original email for email change revocation.\n var email = response[fireauth.ActionCodeInfo.ServerFieldName.EMAIL];\n // The new email.\n var newEmail = response[fireauth.ActionCodeInfo.ServerFieldName.NEW_EMAIL];\n var operation =\n response[fireauth.ActionCodeInfo.ServerFieldName.REQUEST_TYPE];\n // The multi-factor info for revert second factor addition.\n var mfaInfo =\n fireauth.MultiFactorInfo.fromServerResponse(\n response[fireauth.ActionCodeInfo.ServerFieldName.MFA_INFO]);\n // Email could be empty only if the request type is EMAIL_SIGNIN or\n // VERIFY_AND_CHANGE_EMAIL.\n // New email should not be empty if the request type is\n // VERIFY_AND_CHANGE_EMAIL.\n // Multi-factor info could not be empty if the request type is\n // REVERT_SECOND_FACTOR_ADDITION.\n if (!operation ||\n (operation != fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN &&\n operation != fireauth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL &&\n !email) ||\n (operation == fireauth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL &&\n !newEmail) ||\n (operation ==\n fireauth.ActionCodeInfo.Operation.REVERT_SECOND_FACTOR_ADDITION &&\n !mfaInfo)) {\n // This is internal only.\n throw new Error('Invalid checkActionCode response!');\n }\n if (operation == fireauth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL) {\n data[fireauth.ActionCodeInfo.DataField.FROM_EMAIL] = email || null;\n data[fireauth.ActionCodeInfo.DataField.PREVIOUS_EMAIL] = email || null;\n data[fireauth.ActionCodeInfo.DataField.EMAIL] = newEmail;\n } else {\n data[fireauth.ActionCodeInfo.DataField.FROM_EMAIL] = newEmail || null;\n data[fireauth.ActionCodeInfo.DataField.PREVIOUS_EMAIL] = newEmail || null;\n data[fireauth.ActionCodeInfo.DataField.EMAIL] = email || null;\n }\n data[fireauth.ActionCodeInfo.DataField.MULTI_FACTOR_INFO] = mfaInfo || null;\n fireauth.object.setReadonlyProperty(\n this,\n fireauth.ActionCodeInfo.PropertyName.OPERATION,\n operation);\n fireauth.object.setReadonlyProperty(\n this,\n fireauth.ActionCodeInfo.PropertyName.DATA,\n fireauth.object.unsafeCreateReadOnlyCopy(data));\n};\n\n\n/**\n * Firebase Auth Action Code Info operation possible values.\n * @enum {string}\n */\nfireauth.ActionCodeInfo.Operation = {\n PASSWORD_RESET: 'PASSWORD_RESET',\n RECOVER_EMAIL: 'RECOVER_EMAIL',\n REVERT_SECOND_FACTOR_ADDITION: 'REVERT_SECOND_FACTOR_ADDITION',\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n};\n\n\n/**\n * The checkActionCode endpoint server response field names.\n * @enum {string}\n */\nfireauth.ActionCodeInfo.ServerFieldName = {\n // This is the current email of the account and in email recovery, the email\n // to revert to.\n EMAIL: 'email',\n // The multi-factor info to unenroll for revert second factor addition action.\n MFA_INFO: 'mfaInfo',\n // For email recovery, this is the new email.\n NEW_EMAIL: 'newEmail',\n // The action code request type.\n REQUEST_TYPE: 'requestType'\n};\n\n\n/**\n * The ActionCodeInfo data object field names.\n * @enum {string}\n */\nfireauth.ActionCodeInfo.DataField = {\n EMAIL: 'email',\n // This field will be deprecated in favor of PREVIOUS_EMAIL.\n FROM_EMAIL: 'fromEmail',\n MULTI_FACTOR_INFO: 'multiFactorInfo',\n PREVIOUS_EMAIL: 'previousEmail'\n};\n\n\n/**\n * The ActionCodeInfo main property names\n * @enum {string}\n */\nfireauth.ActionCodeInfo.PropertyName = {\n DATA: 'data',\n OPERATION: 'operation'\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 firebase.auth.ActionCodeURL class which is the utility\n * to parse action code URLs.\n */\n\ngoog.provide('fireauth.ActionCodeURL');\n\ngoog.require('fireauth.ActionCodeInfo');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.object');\ngoog.require('goog.Uri');\n\n\n/**\n * The utility class to help parse action code URLs used for out of band email\n * flows such as password reset, email verification, email link sign in, etc.\n * @param {string} actionLink The action link string.\n * @constructor\n */\nfireauth.ActionCodeURL = function(actionLink) {\n var uri = goog.Uri.parse(actionLink);\n var apiKey = uri.getParameterValue(\n fireauth.ActionCodeURL.QueryField.API_KEY) || null;\n var code = uri.getParameterValue(\n fireauth.ActionCodeURL.QueryField.CODE) || null;\n var mode = uri.getParameterValue(\n fireauth.ActionCodeURL.QueryField.MODE) || null;\n var operation = fireauth.ActionCodeURL.getOperation(mode);\n // Validate API key, code and mode.\n if (!apiKey || !code || !operation) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeURL.QueryField.API_KEY + ', ' +\n fireauth.ActionCodeURL.QueryField.CODE + 'and ' +\n fireauth.ActionCodeURL.QueryField.MODE +\n ' are required in a valid action code URL.');\n }\n fireauth.object.setReadonlyProperties(this, {\n 'apiKey': apiKey,\n 'operation': operation,\n 'code': code,\n 'continueUrl': uri.getParameterValue(\n fireauth.ActionCodeURL.QueryField.CONTINUE_URL) || null,\n 'languageCode': uri.getParameterValue(\n fireauth.ActionCodeURL.QueryField.LANGUAGE_CODE) || null,\n 'tenantId': uri.getParameterValue(\n fireauth.ActionCodeURL.QueryField.TENANT_ID) || null\n });\n};\n\n/**\n * Enums for fields in URL query string.\n * @enum {string}\n */\nfireauth.ActionCodeURL.QueryField = {\n API_KEY: 'apiKey',\n CODE: 'oobCode',\n CONTINUE_URL: 'continueUrl',\n LANGUAGE_CODE: 'languageCode',\n MODE: 'mode',\n TENANT_ID: 'tenantId'\n};\n\n\n/**\n * Map of mode string to Action Code Info operation.\n * @const @private {!Object<string, !fireauth.ActionCodeInfo.Operation>}\n */\nfireauth.ActionCodeURL.ModeToOperationMap_ = {\n 'recoverEmail': fireauth.ActionCodeInfo.Operation.RECOVER_EMAIL,\n 'resetPassword': fireauth.ActionCodeInfo.Operation.PASSWORD_RESET,\n 'revertSecondFactorAddition':\n fireauth.ActionCodeInfo.Operation.REVERT_SECOND_FACTOR_ADDITION,\n 'signIn': fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN,\n 'verifyAndChangeEmail':\n fireauth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL,\n 'verifyEmail': fireauth.ActionCodeInfo.Operation.VERIFY_EMAIL\n};\n\n\n/**\n * Maps the mode string in action code URL to Action Code Info operation.\n * @param {?string} mode The mode string in the URL.\n * @return {?fireauth.ActionCodeInfo.Operation}\n */\nfireauth.ActionCodeURL.getOperation = function(mode) {\n if (!mode) {\n return null;\n }\n return fireauth.ActionCodeURL.ModeToOperationMap_[mode] || null;\n\n};\n\n\n/**\n * Returns an ActionCodeURL instance if the link is valid, otherwise null.\n * @param {string} actionLink The action code link string.\n * @return {?fireauth.ActionCodeURL}\n */\nfireauth.ActionCodeURL.parseLink = function(actionLink) {\n try {\n return new fireauth.ActionCodeURL(actionLink);\n } catch(e) {\n return null;\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Utility for firebase.auth.ActionCodeSettings and its helper\n * functions.\n */\n\ngoog.provide('fireauth.ActionCodeSettings');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\n\n\n/**\n * Defines the action code settings structure used to specify how email action\n * links are handled.\n * @param {!Object} settingsObj The action code settings object used to\n * construct the action code link.\n * @constructor @struct @final\n */\nfireauth.ActionCodeSettings = function(settingsObj) {\n // Validate the settings object passed.\n this.initialize_(settingsObj);\n};\n\n\n/**\n * Validate the action code settings object.\n * @param {!Object} settingsObj The action code settings object to validate.\n * @private\n */\nfireauth.ActionCodeSettings.prototype.initialize_ = function(settingsObj) {\n // URL should be required.\n var continueUrl = settingsObj[fireauth.ActionCodeSettings.RawField.URL];\n if (typeof continueUrl === 'undefined') {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_CONTINUE_URI);\n } else if (typeof continueUrl !== 'string' ||\n (typeof continueUrl === 'string' && !continueUrl.length)) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_CONTINUE_URI);\n }\n /** @const @private {string} The continue URL. */\n this.continueUrl_ = /** @type {string} */ (continueUrl);\n\n // Validate Android parameters.\n /** @private {?string} The Android package name. */\n this.apn_ = null;\n /** @private {?string} The Android minimum version. */\n this.amv_ = null;\n /** @private {boolean} Whether to install the Android app. */\n this.installApp_ = false;\n var androidSettings =\n settingsObj[fireauth.ActionCodeSettings.RawField.ANDROID];\n if (androidSettings && typeof androidSettings === 'object') {\n var apn = androidSettings[\n fireauth.ActionCodeSettings.AndroidRawField.PACKAGE_NAME];\n var installApp = androidSettings[\n fireauth.ActionCodeSettings.AndroidRawField.INSTALL_APP];\n var amv = androidSettings[\n fireauth.ActionCodeSettings.AndroidRawField.MINIMUM_VERSION];\n if (typeof apn === 'string' && apn.length) {\n this.apn_ = /** @type {string} */ (apn);\n if (typeof installApp !== 'undefined' &&\n typeof installApp !== 'boolean') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.AndroidRawField.INSTALL_APP +\n ' property must be a boolean when specified.');\n }\n this.installApp_ = !!installApp;\n if (typeof amv !== 'undefined' &&\n (typeof amv !== 'string' ||\n (typeof amv === 'string' && !amv.length))) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.AndroidRawField.MINIMUM_VERSION +\n ' property must be a non empty string when specified.');\n }\n this.amv_ = /** @type {?string}*/ (amv || null);\n } else if (typeof apn !== 'undefined') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.AndroidRawField.PACKAGE_NAME +\n ' property must be a non empty string when specified.');\n } else if (typeof installApp !== 'undefined' ||\n typeof amv !== 'undefined') {\n // If installApp or amv specified with no valid APN, fail quickly.\n throw new fireauth.AuthError(\n fireauth.authenum.Error.MISSING_ANDROID_PACKAGE_NAME);\n }\n } else if (typeof androidSettings !== 'undefined') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.RawField.ANDROID +\n ' property must be a non null object when specified.');\n }\n\n // Validate iOS parameters.\n /** @private {?string} The iOS bundle ID. */\n this.ibi_ = null;\n var iosSettings = settingsObj[fireauth.ActionCodeSettings.RawField.IOS];\n if (iosSettings && typeof iosSettings === 'object') {\n var ibi = iosSettings[\n fireauth.ActionCodeSettings.IosRawField.BUNDLE_ID];\n if (typeof ibi === 'string' && ibi.length) {\n this.ibi_ = /** @type {string}*/ (ibi);\n } else if (typeof ibi !== 'undefined') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.IosRawField.BUNDLE_ID +\n ' property must be a non empty string when specified.');\n }\n } else if (typeof iosSettings !== 'undefined') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.RawField.IOS +\n ' property must be a non null object when specified.');\n }\n\n // Validate canHandleCodeInApp.\n var canHandleCodeInApp =\n settingsObj[fireauth.ActionCodeSettings.RawField.HANDLE_CODE_IN_APP];\n if (typeof canHandleCodeInApp !== 'undefined' &&\n typeof canHandleCodeInApp !== 'boolean') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.RawField.HANDLE_CODE_IN_APP +\n ' property must be a boolean when specified.');\n }\n /** @const @private {boolean} Whether the code can be handled in app. */\n this.canHandleCodeInApp_ = !!canHandleCodeInApp;\n\n // Validate dynamicLinkDomain.\n var dynamicLinkDomain = settingsObj[\n fireauth.ActionCodeSettings.RawField.DYNAMIC_LINK_DOMAIN];\n if (typeof dynamicLinkDomain !== 'undefined' &&\n (typeof dynamicLinkDomain !== 'string' ||\n (typeof dynamicLinkDomain === 'string' &&\n !dynamicLinkDomain.length))) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.RawField.DYNAMIC_LINK_DOMAIN +\n ' property must be a non empty string when specified.');\n }\n /** @const @private {?string} The FDL domain. */\n this.dynamicLinkDomain_ = dynamicLinkDomain || null;\n};\n\n\n/**\n * Action code settings backend request field names.\n * @enum {string}\n */\nfireauth.ActionCodeSettings.RequestField = {\n ANDROID_INSTALL_APP: 'androidInstallApp',\n ANDROID_MINIMUM_VERSION: 'androidMinimumVersion',\n ANDROID_PACKAGE_NAME: 'androidPackageName',\n CAN_HANDLE_CODE_IN_APP: 'canHandleCodeInApp',\n CONTINUE_URL: 'continueUrl',\n DYNAMIC_LINK_DOMAIN: 'dynamicLinkDomain',\n IOS_BUNDLE_ID: 'iOSBundleId'\n};\n\n\n/**\n * Action code settings raw field names.\n * @enum {string}\n */\nfireauth.ActionCodeSettings.RawField = {\n ANDROID: 'android',\n DYNAMIC_LINK_DOMAIN: 'dynamicLinkDomain',\n HANDLE_CODE_IN_APP: 'handleCodeInApp',\n IOS: 'iOS',\n URL: 'url'\n};\n\n\n/**\n * Action code settings raw Android raw field names.\n * @enum {string}\n */\nfireauth.ActionCodeSettings.AndroidRawField = {\n INSTALL_APP: 'installApp',\n MINIMUM_VERSION: 'minimumVersion',\n PACKAGE_NAME: 'packageName'\n};\n\n\n/**\n * Action code settings raw iOS raw field names.\n * @enum {string}\n */\nfireauth.ActionCodeSettings.IosRawField = {\n BUNDLE_ID: 'bundleId'\n};\n\n\n/**\n * Builds and returns the backend request for the passed action code settings.\n * @return {!Object} The constructed backend request populated with the action\n * code settings parameters.\n */\nfireauth.ActionCodeSettings.prototype.buildRequest = function() {\n // Construct backend request.\n var request = {};\n request[fireauth.ActionCodeSettings.RequestField.CONTINUE_URL] =\n this.continueUrl_;\n request[fireauth.ActionCodeSettings.RequestField.CAN_HANDLE_CODE_IN_APP] =\n this.canHandleCodeInApp_;\n request[fireauth.ActionCodeSettings.RequestField.ANDROID_PACKAGE_NAME] =\n this.apn_;\n if (this.apn_) {\n request[fireauth.ActionCodeSettings.RequestField.ANDROID_MINIMUM_VERSION] =\n this.amv_;\n request[fireauth.ActionCodeSettings.RequestField.ANDROID_INSTALL_APP] =\n this.installApp_;\n }\n request[fireauth.ActionCodeSettings.RequestField.IOS_BUNDLE_ID] = this.ibi_;\n request[fireauth.ActionCodeSettings.RequestField.DYNAMIC_LINK_DOMAIN] =\n this.dynamicLinkDomain_;\n // Remove null fields.\n for (var key in request) {\n if (request[key] === null) {\n delete request[key];\n }\n }\n return request;\n};\n\n\n/**\n * Returns the canHandleCodeInApp setting of ActionCodeSettings.\n * @return {boolean} Whether the code can be handled in app.\n */\nfireauth.ActionCodeSettings.prototype.canHandleCodeInApp = function() {\n return this.canHandleCodeInApp_;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Base64 en/decoding. Not much to say here except that we\n * work with decoded values in arrays of bytes. By \"byte\" I mean a number\n * in [0, 255].\n */\n\ngoog.provide('goog.crypt.base64');\n\ngoog.require('goog.asserts');\ngoog.require('goog.crypt');\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\ngoog.require('goog.userAgent.product');\n\n/**\n * Default alphabet, shared between alphabets. Only 62 characters.\n * @private {string}\n */\ngoog.crypt.base64.DEFAULT_ALPHABET_COMMON_ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +\n 'abcdefghijklmnopqrstuvwxyz' +\n '0123456789';\n\n\n/**\n * Alphabet characters for Alphabet.DEFAULT encoding.\n * For characters without padding, please consider using\n * `goog.crypt.baseN.BASE_64` instead.\n *\n * @type {string}\n */\ngoog.crypt.base64.ENCODED_VALS =\n goog.crypt.base64.DEFAULT_ALPHABET_COMMON_ + '+/=';\n\n\n/**\n * Alphabet characters for Alphabet.WEBSAFE_DOT_PADDING encoding.\n * The dot padding is no Internet Standard, according to RFC 4686.\n * https://tools.ietf.org/html/rfc4648\n * For characters without padding, please consider using\n * `goog.crypt.baseN.BASE_64_URL_SAFE` instead.\n *\n * @type {string}\n */\ngoog.crypt.base64.ENCODED_VALS_WEBSAFE =\n goog.crypt.base64.DEFAULT_ALPHABET_COMMON_ + '-_.';\n\n\n/**\n * Alphabets for Base64 encoding\n * Alphabets with no padding character are for encoding without padding.\n * About the alphabets, please refer to RFC 4686.\n * https://tools.ietf.org/html/rfc4648\n * @enum {number}\n */\ngoog.crypt.base64.Alphabet = {\n DEFAULT: 0,\n NO_PADDING: 1,\n WEBSAFE: 2,\n WEBSAFE_DOT_PADDING: 3,\n WEBSAFE_NO_PADDING: 4,\n};\n\n\n/**\n * Padding chars for Base64 encoding\n * @const {string}\n * @private\n */\ngoog.crypt.base64.paddingChars_ = '=.';\n\n\n/**\n * Check if a character is a padding character\n *\n * @param {string} char\n * @return {boolean}\n * @private\n */\ngoog.crypt.base64.isPadding_ = function(char) {\n return goog.string.contains(goog.crypt.base64.paddingChars_, char);\n};\n\n\n// Static lookup maps, lazily populated by init_()\n\n/**\n * For each `Alphabet`, maps from bytes to characters.\n *\n * @see https://jsperf.com/char-lookups\n * @type {!Object<!goog.crypt.base64.Alphabet, !Array<string>>}\n * @private\n */\ngoog.crypt.base64.byteToCharMaps_ = {};\n\n/**\n * Maps characters to bytes.\n *\n * This map is used for all alphabets since, across alphabets, common chars\n * always map to the same byte.\n *\n * `null` indicates `init` has not yet been called.\n *\n * @type {?Object<string, number>}\n * @private\n */\ngoog.crypt.base64.charToByteMap_ = null;\n\n\n/**\n * White list of implementations with known-good native atob and btoa functions.\n * Listing these explicitly (via the ASSUME_* wrappers) benefits dead-code\n * removal in per-browser compilations.\n * @private {boolean}\n */\ngoog.crypt.base64.ASSUME_NATIVE_SUPPORT_ = goog.userAgent.GECKO ||\n (goog.userAgent.WEBKIT && !goog.userAgent.product.SAFARI) ||\n goog.userAgent.OPERA;\n\n\n/**\n * Does this browser have a working btoa function?\n * @private {boolean}\n */\ngoog.crypt.base64.HAS_NATIVE_ENCODE_ =\n goog.crypt.base64.ASSUME_NATIVE_SUPPORT_ ||\n typeof(goog.global.btoa) == 'function';\n\n\n/**\n * Does this browser have a working atob function?\n * We blacklist known-bad implementations:\n * - IE (10+) added atob() but it does not tolerate whitespace on the input.\n * @private {boolean}\n */\ngoog.crypt.base64.HAS_NATIVE_DECODE_ =\n goog.crypt.base64.ASSUME_NATIVE_SUPPORT_ ||\n (!goog.userAgent.product.SAFARI && !goog.userAgent.IE &&\n typeof(goog.global.atob) == 'function');\n\n\n/**\n * Base64-encode an array of bytes.\n *\n * @param {Array<number>|Uint8Array} input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param {!goog.crypt.base64.Alphabet=} alphabet Base 64 alphabet to\n * use in encoding. Alphabet.DEFAULT is used by default.\n * @return {string} The base64 encoded string.\n */\ngoog.crypt.base64.encodeByteArray = function(input, alphabet) {\n // Assert avoids runtime dependency on goog.isArrayLike, which helps reduce\n // size of jscompiler output, and which yields slight performance increase.\n goog.asserts.assert(\n goog.isArrayLike(input), 'encodeByteArray takes an array as a parameter');\n\n if (alphabet === undefined) {\n alphabet = goog.crypt.base64.Alphabet.DEFAULT;\n }\n\n goog.crypt.base64.init_();\n\n var byteToCharMap = goog.crypt.base64.byteToCharMaps_[alphabet];\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], byteToCharMap[outByte2],\n byteToCharMap[outByte3] || '', byteToCharMap[outByte4] || '');\n }\n\n return output.join('');\n};\n\n\n/**\n * Base64-encode a string.\n *\n * @param {string} input A string to encode.\n * @param {!goog.crypt.base64.Alphabet=} alphabet Base 64 alphabet to\n * use in encoding. Alphabet.DEFAULT is used by default.\n * @return {string} The base64 encoded string.\n */\ngoog.crypt.base64.encodeString = function(input, alphabet) {\n // Shortcut for browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (goog.crypt.base64.HAS_NATIVE_ENCODE_ && !alphabet) {\n return goog.global.btoa(input);\n }\n return goog.crypt.base64.encodeByteArray(\n goog.crypt.stringToByteArray(input), alphabet);\n};\n\n\n/**\n * Base64-decode a string.\n *\n * @param {string} input Input to decode. Any whitespace is ignored, and the\n * input maybe encoded with either supported alphabet (or a mix thereof).\n * @param {boolean=} useCustomDecoder True indicates the custom decoder is used,\n * which supports alternative alphabets. Note that passing false may still\n * use the custom decoder on browsers without native support.\n * @return {string} string representing the decoded value.\n */\ngoog.crypt.base64.decodeString = function(input, useCustomDecoder) {\n // Shortcut for browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (goog.crypt.base64.HAS_NATIVE_DECODE_ && !useCustomDecoder) {\n return goog.global.atob(input);\n }\n var output = '';\n function pushByte(b) {\n output += String.fromCharCode(b);\n }\n\n goog.crypt.base64.decodeStringInternal_(input, pushByte);\n\n return output;\n};\n\n\n/**\n * Base64-decode a string to an Array of numbers.\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. Any whitespace is ignored, and the\n * input maybe encoded with either supported alphabet (or a mix thereof).\n * @param {boolean=} opt_ignored Unused parameter, retained for compatibility.\n * @return {!Array<number>} bytes representing the decoded value.\n */\ngoog.crypt.base64.decodeStringToByteArray = function(input, opt_ignored) {\n var output = [];\n function pushByte(b) { output.push(b); }\n\n goog.crypt.base64.decodeStringInternal_(input, pushByte);\n\n return output;\n};\n\n\n/**\n * Base64-decode a string to a Uint8Array.\n *\n * Note that Uint8Array is not supported on older browsers, e.g. IE < 10.\n * @see http://caniuse.com/uint8array\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. Any whitespace is ignored, and the\n * input maybe encoded with either supported alphabet (or a mix thereof).\n * @return {!Uint8Array} bytes representing the decoded value.\n */\ngoog.crypt.base64.decodeStringToUint8Array = function(input) {\n goog.asserts.assert(\n !goog.userAgent.IE || goog.userAgent.isVersionOrHigher('10'),\n 'Browser does not support typed arrays');\n var len = input.length;\n // Approximate the length of the array needed for output.\n // Our method varies according to the format of the input, which we can\n // consider in three categories:\n // A) well-formed with proper padding\n // B) well-formed without any padding\n // C) not-well-formed, either with extra whitespace in the middle or with\n // extra padding characters.\n //\n // In the case of (A), (length * 3 / 4) will result in an integer number of\n // bytes evenly divisible by 3, and we need only subtract bytes according to\n // the padding observed.\n //\n // In the case of (B), (length * 3 / 4) will result in a non-integer number\n // of bytes, or not evenly divisible by 3. (If the result is evenly divisible\n // by 3, it's well-formed with the proper amount of padding [0 padding]).\n // This approximation can become exact by rounding down.\n //\n // In the case of (C), the only way to get the length is to walk the full\n // length of the string to consider each character. This is handled by\n // tracking the number of bytes added to the array and using subarray to\n // trim the array back down to size.\n var approxByteLength = len * 3 / 4;\n if (approxByteLength % 3) {\n // The string isn't complete, either because it didn't include padding, or\n // because it has extra white space.\n // In either case, we won't generate more bytes than are completely encoded,\n // so rounding down is appropriate to have a buffer at least as large as\n // output.\n approxByteLength = Math.floor(approxByteLength);\n } else if (goog.crypt.base64.isPadding_(input[len - 1])) {\n // The string has a round length, and has some padding.\n // Reduce the byte length according to the quantity of padding.\n if (goog.crypt.base64.isPadding_(input[len - 2])) {\n approxByteLength -= 2;\n } else {\n approxByteLength -= 1;\n }\n }\n var output = new Uint8Array(approxByteLength);\n var outLen = 0;\n function pushByte(b) {\n output[outLen++] = b;\n }\n\n goog.crypt.base64.decodeStringInternal_(input, pushByte);\n\n // Return a subarray to handle the case that input included extra whitespace\n // or extra padding and approxByteLength was incorrect.\n return output.subarray(0, outLen);\n};\n\n\n/**\n * @param {string} input Input to decode.\n * @param {function(number):void} pushByte result accumulator.\n * @private\n */\ngoog.crypt.base64.decodeStringInternal_ = function(input, pushByte) {\n goog.crypt.base64.init_();\n\n var nextCharIndex = 0;\n /**\n * @param {number} default_val Used for end-of-input.\n * @return {number} The next 6-bit value, or the default for end-of-input.\n */\n function getByte(default_val) {\n while (nextCharIndex < input.length) {\n var ch = input.charAt(nextCharIndex++);\n var b = goog.crypt.base64.charToByteMap_[ch];\n if (b != null) {\n return b; // Common case: decoded the char.\n }\n if (!goog.string.isEmptyOrWhitespace(ch)) {\n throw new Error('Unknown base64 encoding at char: ' + ch);\n }\n // We encountered whitespace: loop around to the next input char.\n }\n return default_val; // No more input remaining.\n }\n\n while (true) {\n var byte1 = getByte(-1);\n var byte2 = getByte(0);\n var byte3 = getByte(64);\n var byte4 = getByte(64);\n\n // The common case is that all four bytes are present, so if we have byte4\n // we can skip over the truncated input special case handling.\n if (byte4 === 64) {\n if (byte1 === -1) {\n return; // Terminal case: no input left to decode.\n }\n // Here we know an intermediate number of bytes are missing.\n // The defaults for byte2, byte3 and byte4 apply the inferred padding\n // rules per the public API documentation. i.e: 1 byte\n // missing should yield 2 bytes of output, but 2 or 3 missing bytes yield\n // a single byte of output. (Recall that 64 corresponds the padding char).\n }\n\n var outByte1 = (byte1 << 2) | (byte2 >> 4);\n pushByte(outByte1);\n\n if (byte3 != 64) {\n var outByte2 = ((byte2 << 4) & 0xF0) | (byte3 >> 2);\n pushByte(outByte2);\n\n if (byte4 != 64) {\n var outByte3 = ((byte3 << 6) & 0xC0) | byte4;\n pushByte(outByte3);\n }\n }\n }\n};\n\n\n/**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\ngoog.crypt.base64.init_ = function() {\n if (goog.crypt.base64.charToByteMap_) {\n return;\n }\n goog.crypt.base64.charToByteMap_ = {};\n\n // We want quick mappings back and forth, so we precompute encoding maps.\n\n /** @type {!Array<string>} */\n var commonChars = goog.crypt.base64.DEFAULT_ALPHABET_COMMON_.split('');\n var specialChars = [\n '+/=', // DEFAULT\n '+/', // NO_PADDING\n '-_=', // WEBSAFE\n '-_.', // WEBSAFE_DOT_PADDING\n '-_', // WEBSAFE_NO_PADDING\n ];\n\n for (var i = 0; i < 5; i++) {\n // `i` is each value of the `goog.crypt.base64.Alphabet` enum\n var chars = commonChars.concat(specialChars[i].split(''));\n\n // Sets byte-to-char map\n goog.crypt.base64\n .byteToCharMaps_[/** @type {!goog.crypt.base64.Alphabet} */ (i)] =\n chars;\n\n // Sets char-to-byte map\n for (var j = 0; j < chars.length; j++) {\n var char = chars[j];\n\n var existingByte = goog.crypt.base64.charToByteMap_[char];\n if (existingByte === undefined) {\n goog.crypt.base64.charToByteMap_[char] = j;\n } else {\n goog.asserts.assert(existingByte === j);\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Utility functions to handle Firebase Auth ID tokens.\n */\n\ngoog.provide('fireauth.IdToken');\n\ngoog.require('goog.crypt.base64');\n\n\n/**\n * Parses the token string into a {@code Token} object.\n * @param {?string} tokenString The JWT token string.\n * @constructor\n */\nfireauth.IdToken = function(tokenString) {\n var token = fireauth.IdToken.parseIdTokenClaims(tokenString);\n if (!(token && token['sub'] && token['iss'] &&\n token['aud'] && token['exp'])) {\n throw new Error('Invalid JWT');\n }\n /** @const @private {string} The plain JWT string. */\n this.jwt_ = /** @type {string} */ (tokenString);\n /** @const @private {string} The issuer of the token. */\n this.iss_ = token['iss'];\n /** @const @private {string} The audience of the token. */\n this.aud_ = token['aud'];\n /** @const @private {number} The expire time in seconds of the token. */\n this.exp_ = token['exp'];\n /** @const @private {string} The local user ID of the token. */\n this.localId_ = token['sub'];\n var now = goog.now() / 1000;\n /** @const @private {number} The issue time in seconds of the token. */\n this.iat_ = token['iat'] || (now > this.exp_ ? this.exp_ : now);\n /** @const @private {?string} The email address of the token. */\n this.email_ = token['email'] || null;\n /** @const @private {boolean} Whether the user is verified. */\n this.verified_ = !!token['verified'];\n /** @const @private {?string} The provider ID of the token. */\n this.providerId_ = token['provider_id'] ||\n (token['firebase'] && token['firebase']['sign_in_provider']) ||\n null;\n /** @const @private {?string} The tenant ID of the token. */\n this.tenantId_ = (token['firebase'] && token['firebase']['tenant']) || null;\n /** @const @private {boolean} Whether the user is anonymous. */\n this.anonymous_ = !!token['is_anonymous'] || this.providerId_ == 'anonymous';\n /** @const @private {?string} The federated ID of the token. */\n this.federatedId_ = token['federated_id'] || null;\n /** @const @private {?string} The display name of the token. */\n this.displayName_ = token['display_name'] || null;\n /** @const @private {?string} The photo URL of the token. */\n this.photoURL_ = token['photo_url'] || null;\n /**\n * @const @private {?string} The phone number of the user identified by the\n * token.\n */\n this.phoneNumber_ = token['phone_number'] || null;\n};\n\n\n/**\n * @typedef {{\n * identities: (?Object|undefined),\n * sign_in_provider: (?string|undefined),\n * tenant: (string|undefined)\n * }}\n */\nfireauth.IdToken.Firebase;\n\n\n/**\n * @typedef {{\n * iss: string,\n * aud: string,\n * exp: number,\n * sub: string,\n * iat: (?number|undefined),\n * email: (?string|undefined),\n * verified: (?boolean|undefined),\n * provider_id: (?string|undefined),\n * is_anonymous: (?boolean|undefined),\n * federated_id: (?string|undefined),\n * display_name: (?string|undefined),\n * photo_url: (?string|undefined),\n * phone_number: (?string|undefined),\n * firebase: (?fireauth.IdToken.Firebase|undefined)\n * }}\n */\nfireauth.IdToken.JsonToken;\n\n\n/** @return {?string} The email address of the account. */\nfireauth.IdToken.prototype.getEmail = function() {\n return this.email_;\n};\n\n\n/** @return {number} The expire time in seconds. */\nfireauth.IdToken.prototype.getExp = function() {\n return this.exp_;\n};\n\n\n/** @return {?string} The ID of the identity provider. */\nfireauth.IdToken.prototype.getProviderId = function() {\n return this.providerId_;\n};\n\n\n/** @return {?string} The tenant ID. */\nfireauth.IdToken.prototype.getTenantId = function() {\n return this.tenantId_;\n};\n\n\n/** @return {?string} The display name of the account. */\nfireauth.IdToken.prototype.getDisplayName = function() {\n return this.displayName_;\n};\n\n\n/** @return {?string} The photo URL of the account. */\nfireauth.IdToken.prototype.getPhotoUrl = function() {\n return this.photoURL_;\n};\n\n\n/** @return {string} The user ID of the account. */\nfireauth.IdToken.prototype.getLocalId = function() {\n return this.localId_;\n};\n\n\n/** @return {?string} The federated ID of the account. */\nfireauth.IdToken.prototype.getFederatedId = function() {\n return this.federatedId_;\n};\n\n\n/** @return {boolean} Whether the user is anonymous. */\nfireauth.IdToken.prototype.isAnonymous = function() {\n return this.anonymous_;\n};\n\n\n/** @return {boolean} Whether the user email is verified. */\nfireauth.IdToken.prototype.isVerified = function() {\n return this.verified_;\n};\n\n\n/** @return {boolean} Whether token is expired. */\nfireauth.IdToken.prototype.isExpired = function() {\n var now = Math.floor(goog.now() / 1000);\n // It is expired if token expiration time is less than current time.\n return this.getExp() <= now;\n};\n\n\n/** @return {string} The issuer of the token. */\nfireauth.IdToken.prototype.getIssuer = function() {\n return this.iss_;\n};\n\n\n/** @return {?string} The phone number of the account. */\nfireauth.IdToken.prototype.getPhoneNumber = function() {\n return this.phoneNumber_;\n};\n\n\n/**\n * @return {string} The JWT string.\n * @override\n */\nfireauth.IdToken.prototype.toString = function() {\n return this.jwt_;\n};\n\n\n/**\n * Parses the JWT token and extracts the information part without verifying the\n * token signature.\n * @param {string} tokenString The JWT token.\n * @return {?fireauth.IdToken} The decoded token.\n */\nfireauth.IdToken.parse = function(tokenString) {\n try {\n return new fireauth.IdToken(tokenString);\n } catch (e) {\n return null;\n }\n};\n\n/**\n * Converts the information part of JWT token to plain object format.\n * @param {?string} tokenString The JWT token.\n * @return {?Object}\n */\nfireauth.IdToken.parseIdTokenClaims = function(tokenString) {\n if (!tokenString) {\n return null;\n }\n // Token format is <algorithm>.<info>.<sig>\n var fields = tokenString.split('.');\n if (fields.length != 3) {\n return null;\n }\n var jsonInfo = fields[1];\n // Google base64 library does not handle padding.\n var padLen = (4 - jsonInfo.length % 4) % 4;\n for (var i = 0; i < padLen; i++) {\n jsonInfo += '.';\n }\n try {\n var token = JSON.parse(goog.crypt.base64.decodeString(jsonInfo, true));\n return /** @type {?Object} */ (token);\n } catch (e) {}\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 IdP provider IDs and related settings.\n */\n\ngoog.provide('fireauth.idp');\ngoog.provide('fireauth.idp.IdpSettings');\ngoog.provide('fireauth.idp.ProviderId');\ngoog.provide('fireauth.idp.Settings');\ngoog.provide('fireauth.idp.SignInMethod');\n\ngoog.require('fireauth.constants');\n\n\n/**\n * Enums for supported provider IDs. These provider IDs correspond to the\n * sign_in_provider in the Firebase ID token and do not correspond to the\n * supported client exposed firebase.auth.AuthProviders.\n * @enum {string}\n */\nfireauth.idp.ProviderId = {\n ANONYMOUS: 'anonymous',\n CUSTOM: 'custom',\n FACEBOOK: 'facebook.com',\n FIREBASE: 'firebase',\n GITHUB: 'github.com',\n GOOGLE: 'google.com',\n PASSWORD: 'password',\n PHONE: 'phone',\n TWITTER: 'twitter.com'\n};\n\n\n/**\n * Enums for supported sign in methods.\n * @enum {string}\n */\nfireauth.idp.SignInMethod = {\n EMAIL_LINK: 'emailLink',\n EMAIL_PASSWORD: 'password',\n FACEBOOK: 'facebook.com',\n GITHUB: 'github.com',\n GOOGLE: 'google.com',\n PHONE: 'phone',\n TWITTER: 'twitter.com'\n};\n\n\n/**\n * The settings of an identity provider. The fields are:\n * <ul>\n * <li>languageParam: defines the custom OAuth language parameter.\n * <li>popupWidth: defines the popup recommended width.\n * <li>popupHeight: defines the popup recommended height.\n * <li>providerId: defines the provider ID.\n * <li>reservedOAuthParameters: defines the list of reserved OAuth parameters.\n * </ul>\n * @typedef {{\n * languageParam: (?string|undefined),\n * popupWidth: (?number|undefined),\n * popupHeight: (?number|undefined),\n * providerId: !fireauth.idp.ProviderId,\n * reservedOAuthParameters: !Array<string>\n * }}\n */\nfireauth.idp.IdpSettings;\n\n\n/**\n * The list of reserved OAuth 1.0 parameters.\n * @const {!Array<string>}\n */\nfireauth.idp.RESERVED_OAUTH1_PARAMS =\n ['oauth_consumer_key', 'oauth_nonce', 'oauth_signature',\n 'oauth_signature_method', 'oauth_timestamp', 'oauth_token',\n 'oauth_version'];\n\n\n/**\n * The list of reserved OAuth 2.0 parameters.\n * @const {!Array<string>}\n */\nfireauth.idp.RESERVED_OAUTH2_PARAMS =\n ['client_id', 'response_type', 'scope', 'redirect_uri', 'state'];\n\n\n/**\n * The recommendations for the different IdP display settings.\n * @enum {!fireauth.idp.IdpSettings}\n */\nfireauth.idp.Settings = {\n FACEBOOK: {\n languageParam: 'locale',\n popupWidth: 700,\n popupHeight: 600,\n providerId: fireauth.idp.ProviderId.FACEBOOK,\n reservedOAuthParameters: fireauth.idp.RESERVED_OAUTH2_PARAMS,\n },\n GITHUB: {\n languageParam: null,\n popupWidth: 500,\n popupHeight: 750,\n providerId: fireauth.idp.ProviderId.GITHUB,\n reservedOAuthParameters: fireauth.idp.RESERVED_OAUTH2_PARAMS,\n },\n GOOGLE: {\n languageParam: 'hl',\n popupWidth: 515,\n popupHeight: 680,\n providerId: fireauth.idp.ProviderId.GOOGLE,\n reservedOAuthParameters: fireauth.idp.RESERVED_OAUTH2_PARAMS,\n },\n TWITTER: {\n languageParam: 'lang',\n popupWidth: 485,\n popupHeight: 705,\n providerId: fireauth.idp.ProviderId.TWITTER,\n reservedOAuthParameters: fireauth.idp.RESERVED_OAUTH1_PARAMS,\n },\n APPLE: {\n languageParam: 'locale',\n popupWidth: 600,\n popupHeight: 600,\n providerId: 'apple.com',\n reservedOAuthParameters: [],\n },\n};\n\n\n/**\n * @param {!fireauth.idp.ProviderId} providerId The requested provider ID.\n * @return {?fireauth.idp.Settings} The settings for the requested provider ID.\n */\nfireauth.idp.getIdpSettings = function(providerId) {\n for (var key in fireauth.idp.Settings) {\n if (fireauth.idp.Settings[key].providerId == providerId) {\n return fireauth.idp.Settings[key];\n }\n }\n return null;\n};\n\n\n/**\n * @param {!fireauth.idp.ProviderId} providerId The requested provider ID.\n * @return {!Array<string>} The list of reserved OAuth parameters.\n */\nfireauth.idp.getReservedOAuthParams = function(providerId) {\n var settings = fireauth.idp.getIdpSettings(providerId);\n return (settings && settings.reservedOAuthParameters) || [];\n};\n\n\n/**\n * @param {?string|undefined} identifier The provider identifier.\n * @return {boolean} Whether the identifier provided is a SAML provider ID.\n */\nfireauth.idp.isSaml = function(identifier) {\n return typeof identifier === 'string' &&\n identifier.indexOf(fireauth.constants.SAML_PREFIX) == 0;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 all the fireauth additional user info interfaces,\n * implementations and subclasses.\n */\n\ngoog.provide('fireauth.AdditionalUserInfo');\ngoog.provide('fireauth.FacebookAdditionalUserInfo');\ngoog.provide('fireauth.FederatedAdditionalUserInfo');\ngoog.provide('fireauth.GenericAdditionalUserInfo');\ngoog.provide('fireauth.GithubAdditionalUserInfo');\ngoog.provide('fireauth.GoogleAdditionalUserInfo');\ngoog.provide('fireauth.TwitterAdditionalUserInfo');\n\ngoog.require('fireauth.IdToken');\ngoog.require('fireauth.idp');\ngoog.require('fireauth.object');\ngoog.require('fireauth.util');\n\n\n/**\n * The interface that represents additional user info.\n * @interface\n */\nfireauth.AdditionalUserInfo = function() {};\n\n\n/**\n * Constructs the corresponding additional user info for the backend\n * verifyAssertion response.\n * @param {?Object|undefined} resp The backend verifyAssertion,\n * verifyPhoneNumber or verifyPassword/setAccountInfo response.\n * @return {?fireauth.AdditionalUserInfo} The fireauth.AdditionalUserInfo\n * instance.\n */\nfireauth.AdditionalUserInfo.fromPlainObject = function(resp) {\n var factory = {};\n factory[fireauth.idp.ProviderId.FACEBOOK] =\n fireauth.FacebookAdditionalUserInfo;\n factory[fireauth.idp.ProviderId.GOOGLE] =\n fireauth.GoogleAdditionalUserInfo;\n factory[fireauth.idp.ProviderId.GITHUB] =\n fireauth.GithubAdditionalUserInfo;\n factory[fireauth.idp.ProviderId.TWITTER] =\n fireauth.TwitterAdditionalUserInfo;\n // Provider ID and UID are required.\n var providerId =\n resp &&\n resp[fireauth.AdditionalUserInfo.VerifyAssertionField.PROVIDER_ID];\n try {\n // Provider ID already present.\n if (providerId) {\n if (factory[providerId]) {\n // 1st class supported federated providers.\n return new factory[providerId](resp);\n } else {\n // Generic federated providers.\n return new fireauth.FederatedAdditionalUserInfo(\n /** @type {!Object} */ (resp));\n }\n } else if (typeof resp[fireauth.AdditionalUserInfo.VerifyAssertionField\n .ID_TOKEN] !== 'undefined') {\n // For all other ID token responses with no providerId, get the required\n // providerId from the ID token itself.\n return new fireauth.GenericAdditionalUserInfo(\n /** @type {!Object} */ (resp));\n }\n } catch (e) {\n // Do nothing, null will be returned.\n }\n return null;\n};\n\n\n\n/**\n * verifyAssertion response additional user info fields.\n * @enum {string}\n */\nfireauth.AdditionalUserInfo.VerifyAssertionField = {\n ID_TOKEN: 'idToken',\n IS_NEW_USER: 'isNewUser',\n KIND: 'kind',\n PROVIDER_ID: 'providerId',\n RAW_USER_INFO: 'rawUserInfo',\n SCREEN_NAME: 'screenName'\n};\n\n\n/**\n * Constructs a generic additional user info object from the backend\n * verifyPhoneNumber and verifyPassword provider response.\n * @param {!Object} info The verifyPhoneNumber/verifyPassword/setAccountInfo\n * response data object.\n * @constructor\n * @implements {fireauth.AdditionalUserInfo}\n */\nfireauth.GenericAdditionalUserInfo = function(info) {\n // Federated provider profile data.\n var providerId =\n info[fireauth.AdditionalUserInfo.VerifyAssertionField.PROVIDER_ID];\n // Try to get providerId from the ID token if available.\n if (!providerId &&\n info[fireauth.AdditionalUserInfo.VerifyAssertionField.ID_TOKEN]) {\n // verifyPassword/setAccountInfo and verifyPhoneNumber return an ID token\n // but no providerId. Get providerId from the token itself.\n // isNewUser will be returned for verifyPhoneNumber.\n var idToken = fireauth.IdToken.parse(\n info[fireauth.AdditionalUserInfo.VerifyAssertionField.ID_TOKEN]);\n if (idToken && idToken.getProviderId()) {\n providerId = idToken.getProviderId();\n }\n }\n if (!providerId) {\n // This is internal only.\n throw new Error('Invalid additional user info!');\n }\n // For custom token and anonymous token, set provider ID to null.\n if (providerId == fireauth.idp.ProviderId.ANONYMOUS ||\n providerId == fireauth.idp.ProviderId.CUSTOM) {\n providerId = null;\n }\n // Check whether user is new. Temporary Solution since backend does not return\n // isNewUser field for SignupNewUserResponse.\n var isNewUser = false;\n if (typeof info[fireauth.AdditionalUserInfo.VerifyAssertionField.IS_NEW_USER]\n !== 'undefined') {\n isNewUser =\n !!info[fireauth.AdditionalUserInfo.VerifyAssertionField.IS_NEW_USER];\n } else if (info[fireauth.AdditionalUserInfo.VerifyAssertionField.KIND]\n === 'identitytoolkit#SignupNewUserResponse') {\n //For SignupNewUserResponse, always set isNewUser to true.\n isNewUser = true;\n }\n // Set required providerId.\n fireauth.object.setReadonlyProperty(this, 'providerId', providerId);\n // Set read-only isNewUser property.\n fireauth.object.setReadonlyProperty(this, 'isNewUser', isNewUser);\n};\n\n\n/**\n * Constructs a federated additional user info object from the backend\n * verifyAssertion federated provider response.\n * @param {!Object} info The verifyAssertion response data object.\n * @constructor\n * @extends {fireauth.GenericAdditionalUserInfo}\n */\nfireauth.FederatedAdditionalUserInfo = function(info) {\n fireauth.FederatedAdditionalUserInfo.base(this, 'constructor', info);\n // Federated provider profile data.\n // This structure will also be used for generic IdPs.\n var profile = fireauth.util.parseJSON(\n info[fireauth.AdditionalUserInfo.VerifyAssertionField.RAW_USER_INFO] ||\n '{}');\n // Set read-only profile property.\n fireauth.object.setReadonlyProperty(\n this,\n 'profile',\n fireauth.object.unsafeCreateReadOnlyCopy(profile || {}));\n};\ngoog.inherits(\n fireauth.FederatedAdditionalUserInfo, fireauth.GenericAdditionalUserInfo);\n\n\n/**\n * Constructs a Facebook additional user info object from the backend\n * verifyAssertion Facebook provider response.\n * @param {!Object} info The verifyAssertion response data object.\n * @constructor\n * @extends {fireauth.FederatedAdditionalUserInfo}\n */\nfireauth.FacebookAdditionalUserInfo = function(info) {\n fireauth.FacebookAdditionalUserInfo.base(this, 'constructor', info);\n // This should not happen as this object is initialized via fromPlainObject.\n if (this['providerId'] != fireauth.idp.ProviderId.FACEBOOK) {\n throw new Error('Invalid provider ID!');\n }\n};\ngoog.inherits(\n fireauth.FacebookAdditionalUserInfo, fireauth.FederatedAdditionalUserInfo);\n\n\n\n/**\n * Constructs a GitHub additional user info object from the backend\n * verifyAssertion GitHub provider response.\n * @param {!Object} info The verifyAssertion response data object.\n * @constructor\n * @extends {fireauth.FederatedAdditionalUserInfo}\n */\nfireauth.GithubAdditionalUserInfo = function(info) {\n fireauth.GithubAdditionalUserInfo.base(this, 'constructor', info);\n // This should not happen as this object is initialized via fromPlainObject.\n if (this['providerId'] != fireauth.idp.ProviderId.GITHUB) {\n throw new Error('Invalid provider ID!');\n }\n // GitHub username.\n fireauth.object.setReadonlyProperty(\n this,\n 'username',\n (this['profile'] && this['profile']['login']) || null);\n};\ngoog.inherits(\n fireauth.GithubAdditionalUserInfo, fireauth.FederatedAdditionalUserInfo);\n\n\n\n/**\n * Constructs a Google additional user info object from the backend\n * verifyAssertion Google provider response.\n * @param {!Object} info The verifyAssertion response data object.\n * @constructor\n * @extends {fireauth.FederatedAdditionalUserInfo}\n */\nfireauth.GoogleAdditionalUserInfo = function(info) {\n fireauth.GoogleAdditionalUserInfo.base(this, 'constructor', info);\n // This should not happen as this object is initialized via fromPlainObject.\n if (this['providerId'] != fireauth.idp.ProviderId.GOOGLE) {\n throw new Error('Invalid provider ID!');\n }\n};\ngoog.inherits(\n fireauth.GoogleAdditionalUserInfo, fireauth.FederatedAdditionalUserInfo);\n\n\n\n/**\n * Constructs a Twitter additional user info object from the backend\n * verifyAssertion Twitter provider response.\n * @param {!Object} info The verifyAssertion response data object.\n * @constructor\n * @extends {fireauth.FederatedAdditionalUserInfo}\n */\nfireauth.TwitterAdditionalUserInfo = function(info) {\n fireauth.TwitterAdditionalUserInfo.base(this, 'constructor', info);\n // This should not happen as this object is initialized via fromPlainObject.\n if (this['providerId'] != fireauth.idp.ProviderId.TWITTER) {\n throw new Error('Invalid provider ID!');\n }\n // Twitter user name.\n fireauth.object.setReadonlyProperty(\n this,\n 'username',\n info[fireauth.AdditionalUserInfo.VerifyAssertionField.SCREEN_NAME] ||\n null);\n};\ngoog.inherits(\n fireauth.TwitterAdditionalUserInfo, fireauth.FederatedAdditionalUserInfo);\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 dynamic link constructor.\n */\n\ngoog.provide('fireauth.DynamicLink');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.object');\ngoog.require('fireauth.util');\ngoog.require('goog.Uri');\n\n\n/**\n * Dynamic link builder used to help build the FDL link to redirect to an app\n * while passing some payload or error.\n * @param {?string} fdlDomain The FDL domain. If none is available, custom\n * scheme redirects are used.\n * @param {!fireauth.DynamicLink.Platform} platform The FDL supported\n * platform (Android or iOS).\n * @param {string} appIdentifier The app identifier (iOS bundle ID or Android\n * package name).\n * @param {string} authDomain The Firebase application authDomain.\n * @param {string} payload The FDL deep link content.\n * @param {?string=} opt_clientId The optional OAuth client ID.\n * @constructor\n */\nfireauth.DynamicLink = function(fdlDomain, platform, appIdentifier, authDomain,\n payload, opt_clientId) {\n // The fallback error when the app is not installed on the device.\n var defaultError =\n new fireauth.AuthError(fireauth.authenum.Error.APP_NOT_INSTALLED);\n /** @private {string} The fallback URL when the app is not installed. */\n this.fallbackUrl_ = 'https://' + authDomain + '/__/auth/handler?' +\n 'firebaseError=' + encodeURIComponent(/** @type {string} */ (\n fireauth.util.stringifyJSON(defaultError.toPlainObject())));\n fireauth.object.setReadonlyProperty(this, 'fallbackUrl', this.fallbackUrl_);\n /** @private {?string} The FDL domain if available. */\n this.fdlDomain_ = fdlDomain;\n fireauth.object.setReadonlyProperty(this, 'fdlDomain', fdlDomain);\n /** @private {!fireauth.DynamicLink.Platform} The FDL link platform. */\n this.platform_ = platform;\n fireauth.object.setReadonlyProperty(this, 'platform', platform);\n /** @private {string} The app identifier. */\n this.appIdentifier_ = appIdentifier;\n fireauth.object.setReadonlyProperty(this, 'appIdentifier', appIdentifier);\n /** @private {string} The Firebase application authDomain. */\n this.authDomain_ = authDomain;\n fireauth.object.setReadonlyProperty(this, 'authDomain', authDomain);\n /** @private {string} The FDL deep link content. */\n this.link_ = payload;\n fireauth.object.setReadonlyProperty(this, 'payload', payload);\n /** @private {?string} The application display name. */\n this.appName_ = null;\n fireauth.object.setReadonlyProperty(this, 'appName', null);\n /** @private {?string} The client ID if available. */\n this.clientId_ = opt_clientId || null;\n fireauth.object.setReadonlyProperty(this, 'clientId', this.clientId_);\n};\n\n\n/**\n * Sets the app name for the current dynamic link.\n * @param {?string|undefined} appName The app name typically displayed in an FDL\n * button.\n */\nfireauth.DynamicLink.prototype.setAppName = function(appName) {\n this.appName_ = appName || null;\n fireauth.object.setReadonlyProperty(this, 'appName', appName);\n};\n\n\n/**\n * Sets the dynamic link fallback URL overriding the default one.\n * @param {string} fallbackUrl The dynamic link fallback URL.\n */\nfireauth.DynamicLink.prototype.setFallbackUrl = function(fallbackUrl) {\n this.fallbackUrl_ = fallbackUrl;\n fireauth.object.setReadonlyProperty(this, 'fallbackUrl', fallbackUrl);\n};\n\n\n/**\n * Parses a dynamic link object from an automatic FDL redirect link.\n * @param {string} url The URL string to parse and convert to a dynamic link.\n * @return {?fireauth.DynamicLink} The corresponding dynamic link if applicable.\n */\nfireauth.DynamicLink.fromURL = function(url) {\n // This constructs the Dynamic link from the URL provided.\n var uri = goog.Uri.parse(url);\n var fdlDomain = uri.getParameterValue('fdlDomain');\n var platform = uri.getParameterValue('platform');\n var appIdentifier = uri.getParameterValue('appIdentifier');\n var authDomain = uri.getParameterValue('authDomain');\n var payload = uri.getParameterValue('link');\n var appName = uri.getParameterValue('appName');\n if (fdlDomain && platform && appIdentifier && authDomain && payload &&\n appName) {\n var dl = new fireauth.DynamicLink(\n /** @type {string} */ (fdlDomain),\n /** @type {!fireauth.DynamicLink.Platform} */ (platform),\n /** @type {string} */ (appIdentifier),\n /** @type {string} */ (authDomain),\n /** @type {string} */ (payload));\n dl.setAppName(appName);\n return dl;\n }\n return null;\n};\n\n\n/**\n * @param {string} url The dynamic link URL.\n * @return {string} The deep link embedded within the dynamic link.\n */\nfireauth.DynamicLink.parseDeepLink = function(url) {\n var uri = goog.Uri.parse(url);\n var link = uri.getParameterValue('link');\n // Double link case (automatic redirect).\n var doubleDeepLink = goog.Uri.parse(link).getParameterValue('link');\n // iOS custom scheme links.\n var iOSdeepLink = uri.getParameterValue('deep_link_id');\n var iOSDoubledeepLink = goog.Uri.parse(iOSdeepLink).getParameterValue('link');\n var callbackUrl =\n iOSDoubledeepLink || iOSdeepLink || doubleDeepLink || link || url;\n return callbackUrl;\n};\n\n\n/**\n * The supported FDL platforms.\n * @enum {string}\n */\nfireauth.DynamicLink.Platform = {\n ANDROID: 'android',\n IOS: 'ios'\n};\n\n\n/**\n * Constructs the common FDL link base used for building the button link or the\n * automatic redirect link.\n * @param {string} fallbackUrl The fallback URL to use.\n * @return {!goog.Uri} The partial URI of the FDL link used to build the final\n * button link or the automatic redirect link.\n * @private\n */\nfireauth.DynamicLink.prototype.constructFdlBase_ = function(fallbackUrl) {\n var uri = goog.Uri.create(\n 'https',\n null,\n this.fdlDomain_,\n null,\n '/');\n if (this.platform_ == fireauth.DynamicLink.Platform.ANDROID) {\n uri.setParameterValue('apn', this.appIdentifier_);\n uri.setParameterValue('afl', fallbackUrl);\n } else if (this.platform_ == fireauth.DynamicLink.Platform.IOS) {\n uri.setParameterValue('ibi', this.appIdentifier_);\n uri.setParameterValue('ifl', fallbackUrl);\n }\n return uri;\n};\n\n\n/**\n * Constructs the custom scheme URL. This is used when no FDL domain is\n * available.\n * @return {!goog.Uri} The uri of the dynamic link used to build the final\n * button link or the automatic redirect link.\n * @private\n */\nfireauth.DynamicLink.prototype.constructCustomSchemeUrl_ = function() {\n // This mimics the FDL custom scheme URL format.\n var uri = goog.Uri.create(\n this.clientId_ ? this.clientId_.split('.').reverse().join('.') :\n this.appIdentifier_,\n null,\n // 'firebaseauth' is used in the app verification flow.\n // 'google' is used for the Cordova iOS flow.\n this.clientId_ ? 'firebaseauth' : 'google',\n null,\n '/link');\n uri.setParameterValue('deep_link_id', this.link_);\n return uri;\n};\n\n\n/**\n * @param {boolean=} opt_isAutoRedirect Whether the link is an auto redirect\n * link.\n * @return {string} The generated dynamic link string.\n * @override\n */\nfireauth.DynamicLink.prototype.toString = function(opt_isAutoRedirect) {\n // When FDL domain is not available, always returns the custom scheme URL.\n if (!this.fdlDomain_) {\n return this.constructCustomSchemeUrl_().toString();\n }\n if (!!opt_isAutoRedirect) {\n return this.generateAutomaticRedirectLink_();\n }\n return this.generateButtonLink_();\n};\n\n\n/**\n * @return {string} The final FDL button link.\n * @private\n */\nfireauth.DynamicLink.prototype.generateButtonLink_ = function() {\n var fdlLink = this.constructFdlBase_(this.fallbackUrl_);\n fdlLink.setParameterValue('link', this.link_);\n return fdlLink.toString();\n};\n\n\n/**\n * @return {string} The final FDL automatic redirect link.\n * @private\n */\nfireauth.DynamicLink.prototype.generateAutomaticRedirectLink_ =\n function() {\n var doubleDeeplink = goog.Uri.create(\n 'https',\n null,\n this.authDomain_,\n null,\n '/__/auth/callback');\n doubleDeeplink.setParameterValue('fdlDomain', this.fdlDomain_);\n doubleDeeplink.setParameterValue('platform', this.platform_);\n doubleDeeplink.setParameterValue('appIdentifier', this.appIdentifier_);\n doubleDeeplink.setParameterValue('authDomain', this.authDomain_);\n doubleDeeplink.setParameterValue('link', this.link_);\n doubleDeeplink.setParameterValue('appName', this.appName_ || '');\n // The fallback URL is the deep link itself.\n // This is in case the link fails to be intercepted by the app, FDL will\n // redirect to the fallback URL.\n var fdlLink = this.constructFdlBase_(doubleDeeplink.toString());\n fdlLink.setParameterValue('link', doubleDeeplink.toString());\n return fdlLink.toString();\n};\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 multi-factor session object used for enrolling a\n * second factor on a user or helping sign in an enrolled user with a second\n * factor.\n */\n\ngoog.provide('fireauth.MultiFactorSession');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('goog.Promise');\n\n\n/**\n * Initializes an instance of a multi-factor session object used for enrolling\n * a second factor on a user or helping sign in an enrolled user with a second\n * factor.\n * This will be constructed either after calling `user.getIdToken()` or from the\n * error containing the pending MFA credential after sign-in.\n * @param {?string} idToken The ID token for an enroll flow. This has to be\n * retrieved after recent authentication.\n * @param {?string=} mfaPendingCredential The pending credential after an\n * enrolled second factor user signs in successfully with the first factor.\n * @constructor\n */\nfireauth.MultiFactorSession = function(idToken, mfaPendingCredential) {\n if (!idToken && !mfaPendingCredential) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'Internal assert: no raw session string available');\n }\n // Both fields should never be passed at the same time.\n if (idToken && mfaPendingCredential) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'Internal assert: unable to determine the session type');\n }\n /** @const @private {?string} The ID token for an enroll flow. */\n this.idToken_ = idToken || null;\n /** @const @private {?string} The pending credential for a sign-in flow. */\n this.mfaPendingCredential_ = mfaPendingCredential || null;\n /** @const @public {!fireauth.MultiFactorSession.Type} The session type.*/\n this.type = this.idToken_ ?\n fireauth.MultiFactorSession.Type.ENROLL :\n fireauth.MultiFactorSession.Type.SIGN_IN;\n};\n\n\n/**\n * Enum representing the type of multi-factor session.\n * @enum {string}\n */\nfireauth.MultiFactorSession.Type = {\n ENROLL: 'enroll',\n SIGN_IN: 'signin'\n};\n\n\n/**\n * Returns a promise that resolves with the raw session string.\n * @return {!goog.Promise<string>} A promise that resolves with the raw session\n * string.\n */\nfireauth.MultiFactorSession.prototype.getRawSession = function() {\n return this.idToken_ ?\n goog.Promise.resolve(this.idToken_) :\n goog.Promise.resolve(this.mfaPendingCredential_);\n};\n\n\n/**\n * Returns the plain object representation of the session object.\n * @return {!Object} The plain object representation of the session object.\n */\nfireauth.MultiFactorSession.prototype.toPlainObject = function() {\n if (this.type == fireauth.MultiFactorSession.Type.ENROLL) {\n return {\n 'multiFactorSession': {\n 'idToken': this.idToken_\n }\n };\n } else {\n return {\n 'multiFactorSession': {\n 'pendingCredential': this.mfaPendingCredential_\n }\n };\n }\n};\n\n\n/**\n * Converts a plain object to a `fireauth.MultiFactorSession` if applicable.\n * @param {?Object} obj The plain object to convert to a\n * `fireauth.MultiFactorSession`.\n * @return {?fireauth.MultiFactorSession} The corresponding\n * `fireauth.MultiFactorSession` representation, null otherwise.\n */\nfireauth.MultiFactorSession.fromPlainObject = function(obj) {\n if (obj && obj['multiFactorSession']) {\n if (obj['multiFactorSession']['pendingCredential']) {\n return new fireauth.MultiFactorSession(\n null, obj['multiFactorSession']['pendingCredential']);\n } else if (obj['multiFactorSession']['idToken']) {\n return new fireauth.MultiFactorSession(\n obj['multiFactorSession']['idToken'], null);\n }\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Auth credentials used for signInWithCredential.\n */\n\ngoog.provide('fireauth.AuthCredential');\ngoog.provide('fireauth.AuthProvider');\ngoog.provide('fireauth.EmailAuthCredential');\ngoog.provide('fireauth.EmailAuthProvider');\ngoog.provide('fireauth.FacebookAuthProvider');\ngoog.provide('fireauth.FederatedProvider');\ngoog.provide('fireauth.GithubAuthProvider');\ngoog.provide('fireauth.GoogleAuthProvider');\ngoog.provide('fireauth.OAuthCredential');\ngoog.provide('fireauth.OAuthProvider');\ngoog.provide('fireauth.OAuthResponse');\ngoog.provide('fireauth.PhoneAuthCredential');\ngoog.provide('fireauth.PhoneAuthProvider');\ngoog.provide('fireauth.SAMLAuthCredential');\ngoog.provide('fireauth.SAMLAuthProvider');\ngoog.provide('fireauth.TwitterAuthProvider');\n\ngoog.requireType('fireauth.RpcHandler');\ngoog.require('fireauth.ActionCodeInfo');\ngoog.require('fireauth.ActionCodeURL');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.DynamicLink');\ngoog.require('fireauth.IdToken');\ngoog.require('fireauth.MultiFactorAuthCredential');\ngoog.require('fireauth.MultiFactorEnrollmentRequestIdentifier');\ngoog.require('fireauth.MultiFactorSession');\ngoog.require('fireauth.MultiFactorSignInRequestIdentifier');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.idp');\ngoog.require('fireauth.object');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n\n/**\n * The interface that represents Auth credential. It provides the underlying\n * implementation for retrieving the ID token depending on the type of\n * credential.\n * @interface\n */\nfireauth.AuthCredential = function() {};\n\n\n/**\n * Returns a promise to retrieve ID token using the underlying RPC handler API\n * for the current credential.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @return {!goog.Promise<!Object, !fireauth.AuthError>}\n * idTokenPromise The RPC handler method that returns a promise which\n * resolves with an ID token.\n */\nfireauth.AuthCredential.prototype.getIdTokenProvider = function(rpcHandler) {};\n\n\n/**\n * Links the credential to an existing account, identified by an ID token.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @param {string} idToken The ID token of the existing account.\n * @return {!goog.Promise<!Object>} A Promise that resolves when the accounts\n * are linked.\n */\nfireauth.AuthCredential.prototype.linkToIdToken =\n function(rpcHandler, idToken) {};\n\n\n/**\n * Tries to match the credential's idToken with the provided UID.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @param {string} uid The UID of the user to reauthenticate.\n * @return {!goog.Promise<!Object>} A Promise that resolves when\n * idToken UID match succeeds and returns the server response.\n */\nfireauth.AuthCredential.prototype.matchIdTokenWithUid =\n function(rpcHandler, uid) {};\n\n\n/**\n * @return {!Object} The plain object representation of an Auth credential. This\n * will be exposed as toJSON() externally.\n */\nfireauth.AuthCredential.prototype.toPlainObject = function() {};\n\n\n/**\n * @param {!goog.Promise<!Object>} idTokenResolver A promise that resolves with\n * the ID token response.\n * @param {string} uid The UID to match in the token response.\n * @return {!goog.Promise<!Object>} A promise that resolves with the same\n * response if the UID matches.\n */\nfireauth.AuthCredential.verifyTokenResponseUid =\n function(idTokenResolver, uid) {\n return idTokenResolver.then(function(response) {\n // This should not happen as rpcHandler verifyAssertion and verifyPassword\n // always guarantee an ID token is available.\n if (response[fireauth.RpcHandler.AuthServerField.ID_TOKEN]) {\n // Parse the token object.\n var parsedIdToken = fireauth.IdToken.parse(\n response[fireauth.RpcHandler.AuthServerField.ID_TOKEN]);\n // Confirm token localId matches the provided UID. If not, throw the user\n // mismatch error.\n if (!parsedIdToken || uid != parsedIdToken.getLocalId()) {\n throw new fireauth.AuthError(fireauth.authenum.Error.USER_MISMATCH);\n }\n return response;\n }\n throw new fireauth.AuthError(fireauth.authenum.Error.USER_MISMATCH);\n })\n .thenCatch(function(error) {\n // Translate auth/user-not-found error directly to auth/user-mismatch.\n throw fireauth.AuthError.translateError(\n error,\n fireauth.authenum.Error.USER_DELETED,\n fireauth.authenum.Error.USER_MISMATCH);\n });\n};\n\n\n\n/**\n * The interface that represents the Auth provider.\n * @interface\n */\nfireauth.AuthProvider = function() {};\n\n\n/**\n * @param {...*} var_args The credential data.\n * @return {!fireauth.AuthCredential} The Auth provider credential.\n */\nfireauth.AuthProvider.credential;\n\n\n/**\n * @typedef {{\n * accessToken: (?string|undefined),\n * idToken: (?string|undefined),\n * nonce: (?string|undefined),\n * oauthToken: (?string|undefined),\n * oauthTokenSecret: (?string|undefined),\n * pendingToken: (?string|undefined)\n * }}\n */\nfireauth.OAuthResponse;\n\n\n/**\n * The SAML Auth credential class. The Constructor is not publicly visible.\n * This is constructed by the SDK on successful or failure after SAML sign-in\n * and returned to developer.\n * @param {!fireauth.idp.ProviderId} providerId The provider ID.\n * @param {string} pendingToken The SAML response pending token.\n * @constructor\n * @implements {fireauth.AuthCredential}\n */\nfireauth.SAMLAuthCredential = function(providerId, pendingToken) {\n if (pendingToken) {\n /** @private {string} The pending token where SAML response is encrypted. */\n this.pendingToken_ = pendingToken;\n } else {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'failed to construct a credential');\n }\n\n fireauth.object.setReadonlyProperty(this, 'providerId', providerId);\n fireauth.object.setReadonlyProperty(this, 'signInMethod', providerId);\n};\n\n\n/**\n * Returns a promise to retrieve ID token using the underlying RPC handler API\n * for the current credential.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @return {!goog.Promise<!Object, !fireauth.AuthError>}\n * idTokenPromise The RPC handler method that returns a promise which\n * resolves with an ID token.\n * @override\n */\nfireauth.SAMLAuthCredential.prototype.getIdTokenProvider =\n function(rpcHandler) {\n return rpcHandler.verifyAssertion(\n /** @type {!fireauth.RpcHandler.VerifyAssertionData} */ (\n this.makeVerifyAssertionRequest_()));\n};\n\n\n/**\n * Links the credential to an existing account, identified by an ID token.\n * @param {!fireauth.RpcHandler} rpcHandler The rpc handler.\n * @param {string} idToken The ID token of the existing account.\n * @return {!goog.Promise<!Object>} A Promise that resolves when the accounts\n * are linked, returning the backend response.\n * @override\n */\nfireauth.SAMLAuthCredential.prototype.linkToIdToken =\n function(rpcHandler, idToken) {\n var request = this.makeVerifyAssertionRequest_();\n request['idToken'] = idToken;\n return rpcHandler.verifyAssertionForLinking(\n /** @type {!fireauth.RpcHandler.VerifyAssertionData} */ (request));\n};\n\n\n/**\n * Tries to match the credential's idToken with the provided UID.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @param {string} uid The UID of the user to reauthenticate.\n * @return {!goog.Promise<!Object>} A Promise that resolves when\n * idToken UID match succeeds and returns the server response.\n * @override\n */\nfireauth.SAMLAuthCredential.prototype.matchIdTokenWithUid =\n function(rpcHandler, uid) {\n var request = this.makeVerifyAssertionRequest_();\n // Do not create a new account if the user doesn't exist.\n return fireauth.AuthCredential.verifyTokenResponseUid(\n rpcHandler.verifyAssertionForExisting(\n /** @type {!fireauth.RpcHandler.VerifyAssertionData} */ (request)),\n uid);\n};\n\n\n/**\n * @return {!Object} A request to the VerifyAssertion endpoint, populated with\n * the assertion data from this credential.\n * @private\n */\nfireauth.SAMLAuthCredential.prototype.makeVerifyAssertionRequest_ =\n function() {\n return {\n 'pendingToken': this.pendingToken_,\n // Always use http://localhost.\n 'requestUri': 'http://localhost'\n };\n};\n\n\n/**\n * @return {!Object} The plain object representation of an Auth credential.\n * @override\n */\nfireauth.SAMLAuthCredential.prototype.toPlainObject = function() {\n return {\n 'providerId': this['providerId'],\n 'signInMethod': this['signInMethod'],\n 'pendingToken': this.pendingToken_\n };\n};\n\n\n/**\n * @param {?Object|undefined} json The plain object representation of a\n * SAMLAuthCredential.\n * @return {?fireauth.SAMLAuthCredential} The SAML credential if the object\n * is a JSON representation of a SAMLAuthCredential, null otherwise.\n */\nfireauth.SAMLAuthCredential.fromJSON = function(json) {\n if (json &&\n json['providerId'] &&\n json['signInMethod'] &&\n json['providerId'].indexOf(fireauth.constants.SAML_PREFIX) == 0 &&\n json['pendingToken']) {\n try {\n return new fireauth.SAMLAuthCredential(\n json['providerId'], json['pendingToken']);\n } catch (e) {\n return null;\n }\n }\n return null;\n};\n\n\n/**\n * The OAuth credential class.\n * @param {!fireauth.idp.ProviderId} providerId The provider ID.\n * @param {!fireauth.OAuthResponse} oauthResponse The OAuth\n * response object containing token information.\n * @param {!fireauth.idp.SignInMethod} signInMethod The sign in method.\n * @constructor\n * @implements {fireauth.AuthCredential}\n */\nfireauth.OAuthCredential = function(providerId, oauthResponse, signInMethod) {\n /**\n * @private {?string} The pending token where the IdP response is encrypted.\n */\n this.pendingToken_ = null;\n if (oauthResponse['idToken'] || oauthResponse['accessToken']) {\n // OAuth 2 and either ID token or access token.\n if (oauthResponse['idToken']) {\n fireauth.object.setReadonlyProperty(\n this, 'idToken', oauthResponse['idToken']);\n }\n if (oauthResponse['accessToken']) {\n fireauth.object.setReadonlyProperty(\n this, 'accessToken', oauthResponse['accessToken']);\n }\n // Add nonce if available and no pendingToken is present.\n if (oauthResponse['nonce'] && !oauthResponse['pendingToken']) {\n fireauth.object.setReadonlyProperty(\n this, 'nonce', oauthResponse['nonce']);\n }\n if (oauthResponse['pendingToken']) {\n this.pendingToken_ = oauthResponse['pendingToken'];\n }\n } else if (oauthResponse['oauthToken'] &&\n oauthResponse['oauthTokenSecret']) {\n // OAuth 1 and OAuth token with OAuth token secret.\n fireauth.object.setReadonlyProperty(\n this, 'accessToken', oauthResponse['oauthToken']);\n fireauth.object.setReadonlyProperty(\n this, 'secret', oauthResponse['oauthTokenSecret']);\n } else {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'failed to construct a credential');\n }\n\n fireauth.object.setReadonlyProperty(this, 'providerId', providerId);\n fireauth.object.setReadonlyProperty(this, 'signInMethod', signInMethod);\n};\n\n\n/**\n * Returns a promise to retrieve ID token using the underlying RPC handler API\n * for the current credential.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @return {!goog.Promise<!Object, !fireauth.AuthError>}\n * idTokenPromise The RPC handler method that returns a promise which\n * resolves with an ID token.\n * @override\n */\nfireauth.OAuthCredential.prototype.getIdTokenProvider = function(rpcHandler) {\n return rpcHandler.verifyAssertion(\n /** @type {!fireauth.RpcHandler.VerifyAssertionData} */ (\n this.makeVerifyAssertionRequest_()));\n};\n\n\n/**\n * Links the credential to an existing account, identified by an ID token.\n * @param {!fireauth.RpcHandler} rpcHandler The rpc handler.\n * @param {string} idToken The ID token of the existing account.\n * @return {!goog.Promise<!Object>} A Promise that resolves when the accounts\n * are linked, returning the backend response.\n * @override\n */\nfireauth.OAuthCredential.prototype.linkToIdToken =\n function(rpcHandler, idToken) {\n var request = this.makeVerifyAssertionRequest_();\n request['idToken'] = idToken;\n return rpcHandler.verifyAssertionForLinking(\n /** @type {!fireauth.RpcHandler.VerifyAssertionData} */ (request));\n};\n\n\n/**\n * Tries to match the credential's idToken with the provided UID.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @param {string} uid The UID of the user to reauthenticate.\n * @return {!goog.Promise<!Object>} A Promise that resolves when\n * idToken UID match succeeds and returns the server response.\n * @override\n */\nfireauth.OAuthCredential.prototype.matchIdTokenWithUid =\n function(rpcHandler, uid) {\n var request = this.makeVerifyAssertionRequest_();\n // Do not create a new account if the user doesn't exist.\n return fireauth.AuthCredential.verifyTokenResponseUid(\n rpcHandler.verifyAssertionForExisting(\n /** @type {!fireauth.RpcHandler.VerifyAssertionData} */ (request)),\n uid);\n};\n\n\n/**\n * @return {!Object} A request to the VerifyAssertion endpoint, populated with\n * the OAuth data from this credential.\n * @private\n */\nfireauth.OAuthCredential.prototype.makeVerifyAssertionRequest_ = function() {\n var postBody = {};\n if (this['idToken']) {\n postBody['id_token'] = this['idToken'];\n }\n if (this['accessToken']) {\n postBody['access_token'] = this['accessToken'];\n }\n if (this['secret']) {\n postBody['oauth_token_secret'] = this['secret'];\n }\n postBody['providerId'] = this['providerId'];\n // Pass nonce in postBody if available.\n if (this['nonce'] && !this.pendingToken_) {\n postBody['nonce'] = this['nonce'];\n }\n var request = {\n 'postBody': goog.Uri.QueryData.createFromMap(postBody).toString(),\n // Always use http://localhost.\n 'requestUri': 'http://localhost'\n };\n if (this.pendingToken_) {\n // For pendingToken, just pass it through and drop postBody.\n delete request['postBody'];\n request['pendingToken'] = this.pendingToken_;\n }\n return request;\n};\n\n\n/**\n * @return {!Object} The plain object representation of an Auth credential.\n * @override\n */\nfireauth.OAuthCredential.prototype.toPlainObject = function() {\n var obj = {\n 'providerId': this['providerId'],\n 'signInMethod': this['signInMethod']\n };\n if (this['idToken']) {\n obj['oauthIdToken'] = this['idToken'];\n }\n if (this['accessToken']) {\n obj['oauthAccessToken'] = this['accessToken'];\n }\n if (this['secret']) {\n obj['oauthTokenSecret'] = this['secret'];\n }\n if (this['nonce']) {\n obj['nonce'] = this['nonce'];\n }\n if (this.pendingToken_) {\n obj['pendingToken'] = this.pendingToken_;\n }\n return obj;\n};\n\n\n/**\n * @param {?Object|undefined} json The plain object representation of an\n * OAuthCredential.\n * @return {?fireauth.OAuthCredential} The OAuth/OIDC credential if the object\n * is a JSON representation of an OAuthCredential, null otherwise.\n */\nfireauth.OAuthCredential.fromJSON = function(json) {\n if (json &&\n json['providerId'] &&\n json['signInMethod']) {\n // Convert to OAuthResponse format.\n var oauthResponse = {\n // OIDC && google.com.\n 'idToken': json['oauthIdToken'],\n // OAuth 2.0 providers.\n 'accessToken': json['oauthTokenSecret'] ? null : json['oauthAccessToken'],\n // OAuth 1.0 provider, eg. Twitter.\n 'oauthTokenSecret': json['oauthTokenSecret'],\n 'oauthToken': json['oauthTokenSecret'] && json['oauthAccessToken'],\n 'nonce': json['nonce'],\n 'pendingToken': json['pendingToken']\n };\n try {\n // Constructor will validate the OAuthResponse.\n return new fireauth.OAuthCredential(\n json['providerId'], oauthResponse, json['signInMethod']);\n } catch (e) {\n return null;\n }\n }\n return null;\n};\n\n\n/**\n * A generic OAuth provider (OAuth1 or OAuth2).\n * @param {string} providerId The IdP provider ID (e.g. google.com,\n * facebook.com) registered with the backend.\n * @param {?Array<string>=} opt_reservedParams The backlist of parameters that\n * cannot be set through setCustomParameters.\n * @constructor\n */\nfireauth.FederatedProvider = function(providerId, opt_reservedParams) {\n /** @private {!Array<string>} */\n this.reservedParams_ = opt_reservedParams || [];\n\n // Set read only instance providerId property.\n // Set read only instance isOAuthProvider property.\n fireauth.object.setReadonlyProperties(this, {\n 'providerId': providerId,\n 'isOAuthProvider': true\n });\n\n /** @private {!Object} The OAuth custom parameters for current provider. */\n this.customParameters_ = {};\n /** @protected {?string} The custom OAuth language parameter. */\n this.languageParameter =\n (fireauth.idp.getIdpSettings(/** @type {!fireauth.idp.ProviderId} */ (\n providerId)) || {}).languageParam || null;\n /** @protected {?string} The default language. */\n this.defaultLanguageCode = null;\n};\n\n/**\n * @param {!Object} customParameters The custom OAuth parameters to pass\n * in OAuth request.\n * @return {!fireauth.FederatedProvider} The FederatedProvider instance, for\n * chaining method calls.\n */\nfireauth.FederatedProvider.prototype.setCustomParameters =\n function(customParameters) {\n this.customParameters_ = goog.object.clone(customParameters);\n return this;\n};\n\n\n/**\n * Set the default language code on the provider instance.\n * @param {?string} languageCode The default language code to set if not already\n * provided in the custom parameters.\n */\nfireauth.FederatedProvider.prototype.setDefaultLanguage =\n function(languageCode) {\n this.defaultLanguageCode = languageCode;\n};\n\n\n/**\n * @return {!Object} The custom OAuth parameters to pass in OAuth request.\n */\nfireauth.FederatedProvider.prototype.getCustomParameters = function() {\n // The backend already checks for these values and makes sure no reserved\n // fields like client ID, redirect URI, state are overwritten by these\n // fields.\n var params =\n fireauth.util.copyWithoutNullsOrUndefined(this.customParameters_);\n // Convert to strings.\n for (var key in params) {\n params[key] = params[key].toString();\n }\n // Remove blacklisted OAuth custom parameters.\n var customParams =\n fireauth.util.removeEntriesWithKeys(params, this.reservedParams_);\n // If language param supported and not already provided, use default language.\n if (this.languageParameter &&\n this.defaultLanguageCode &&\n !customParams[this.languageParameter]) {\n customParams[this.languageParameter] = this.defaultLanguageCode;\n }\n return customParams;\n};\n\n\n/**\n * Generic SAML auth provider.\n * @param {string} providerId The SAML IdP provider ID (e.g. saml.saml2rp)\n * registered with the backend.\n * @constructor\n * @extends {fireauth.FederatedProvider}\n * @implements {fireauth.AuthProvider}\n */\nfireauth.SAMLAuthProvider = function(providerId) {\n // SAML provider IDs must be prefixed with the SAML_PREFIX.\n if (!fireauth.idp.isSaml(providerId)) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n 'SAML provider IDs must be prefixed with \"' +\n fireauth.constants.SAML_PREFIX + '\"');\n }\n // isOAuthProvider is true even though this is not an OAuth provider.\n // This can be confusing as this is a SAML provider. However, this property\n // is needed to allow signInWithPopup/Redirect. We should rename it to\n // something more accurate: isFederatedProvider.\n fireauth.SAMLAuthProvider.base(this, 'constructor', providerId, []);\n};\ngoog.inherits(fireauth.SAMLAuthProvider, fireauth.FederatedProvider);\n\n\n/**\n * Generic OAuth2 Auth provider.\n * @param {string} providerId The IdP provider ID (e.g. google.com,\n * facebook.com) registered with the backend.\n * @constructor\n * @extends {fireauth.FederatedProvider}\n * @implements {fireauth.AuthProvider}\n */\nfireauth.OAuthProvider = function(providerId) {\n fireauth.OAuthProvider.base(this, 'constructor', providerId,\n fireauth.idp.RESERVED_OAUTH2_PARAMS);\n\n /** @private {!Array<string>} The list of OAuth2 scopes to request. */\n this.scopes_ = [];\n};\ngoog.inherits(fireauth.OAuthProvider, fireauth.FederatedProvider);\n\n\n/**\n * @param {string} scope The OAuth scope to request.\n * @return {!fireauth.OAuthProvider} The OAuthProvider instance, for chaining\n * method calls.\n */\nfireauth.OAuthProvider.prototype.addScope = function(scope) {\n // If not already added, add scope to list.\n if (!goog.array.contains(this.scopes_, scope)) {\n this.scopes_.push(scope);\n }\n return this;\n};\n\n\n/** @return {!Array<string>} The Auth provider's list of scopes. */\nfireauth.OAuthProvider.prototype.getScopes = function() {\n return goog.array.clone(this.scopes_);\n};\n\n\n/**\n * Initializes an OAuth AuthCredential. At least one of ID token or access token\n * must be defined. When providing an OIDC ID token with a nonce encoded, the\n * raw nonce must also be provided.\n * @param {?Object|string} optionsOrIdToken Either the options object containing\n * the ID token, access token and raw nonce or the ID token string.\n * @param {?string=} opt_accessToken The optional OAuth access token.\n * @return {!fireauth.AuthCredential} The Auth credential object.\n */\nfireauth.OAuthProvider.prototype.credential =\n function(optionsOrIdToken, opt_accessToken) {\n var oauthResponse;\n if (goog.isObject(optionsOrIdToken)) {\n oauthResponse = {\n 'idToken': optionsOrIdToken['idToken'] || null,\n 'accessToken': optionsOrIdToken['accessToken'] || null,\n 'nonce': optionsOrIdToken['rawNonce'] || null\n };\n } else {\n oauthResponse = {\n 'idToken': optionsOrIdToken || null,\n 'accessToken': opt_accessToken || null\n };\n }\n if (!oauthResponse['idToken'] && !oauthResponse['accessToken']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n 'credential failed: must provide the ID token and/or the access ' +\n 'token.');\n }\n // For OAuthCredential, sign in method is same as providerId.\n return new fireauth.OAuthCredential(this['providerId'],\n oauthResponse,\n this['providerId']);\n};\n\n\n/**\n * Facebook Auth provider.\n * @constructor\n * @extends {fireauth.OAuthProvider}\n * @implements {fireauth.AuthProvider}\n */\nfireauth.FacebookAuthProvider = function() {\n fireauth.FacebookAuthProvider.base(this, 'constructor',\n fireauth.idp.ProviderId.FACEBOOK);\n};\ngoog.inherits(fireauth.FacebookAuthProvider, fireauth.OAuthProvider);\n\nfireauth.object.setReadonlyProperty(fireauth.FacebookAuthProvider,\n 'PROVIDER_ID', fireauth.idp.ProviderId.FACEBOOK);\n\nfireauth.object.setReadonlyProperty(fireauth.FacebookAuthProvider,\n 'FACEBOOK_SIGN_IN_METHOD', fireauth.idp.SignInMethod.FACEBOOK);\n\n\n/**\n * Initializes a Facebook AuthCredential.\n * @param {string} accessTokenOrObject The Facebook access token, or object\n * containing the token for FirebaseUI backwards compatibility.\n * @return {!fireauth.AuthCredential} The Auth credential object.\n */\nfireauth.FacebookAuthProvider.credential = function(accessTokenOrObject) {\n if (!accessTokenOrObject) {\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n 'credential failed: expected 1 argument (the OAuth access token).');\n }\n var accessToken = accessTokenOrObject;\n if (goog.isObject(accessTokenOrObject)) {\n accessToken = accessTokenOrObject['accessToken'];\n }\n return new fireauth.FacebookAuthProvider().credential({\n 'accessToken': /** @type {string} */ (accessToken)\n });\n};\n\n\n/**\n * GitHub Auth provider.\n * @constructor\n * @extends {fireauth.OAuthProvider}\n * @implements {fireauth.AuthProvider}\n */\nfireauth.GithubAuthProvider = function() {\n fireauth.GithubAuthProvider.base(this, 'constructor',\n fireauth.idp.ProviderId.GITHUB);\n};\ngoog.inherits(fireauth.GithubAuthProvider, fireauth.OAuthProvider);\n\nfireauth.object.setReadonlyProperty(fireauth.GithubAuthProvider,\n 'PROVIDER_ID', fireauth.idp.ProviderId.GITHUB);\n\nfireauth.object.setReadonlyProperty(fireauth.GithubAuthProvider,\n 'GITHUB_SIGN_IN_METHOD', fireauth.idp.SignInMethod.GITHUB);\n\n\n/**\n * Initializes a GitHub AuthCredential.\n * @param {string} accessTokenOrObject The GitHub access token, or object\n * containing the token for FirebaseUI backwards compatibility.\n * @return {!fireauth.AuthCredential} The Auth credential object.\n */\nfireauth.GithubAuthProvider.credential = function(accessTokenOrObject) {\n if (!accessTokenOrObject) {\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n 'credential failed: expected 1 argument (the OAuth access token).');\n }\n var accessToken = accessTokenOrObject;\n if (goog.isObject(accessTokenOrObject)) {\n accessToken = accessTokenOrObject['accessToken'];\n }\n return new fireauth.GithubAuthProvider().credential({\n 'accessToken': /** @type {string} */ (accessToken)\n });\n};\n\n\n/**\n * Google Auth provider.\n * @constructor\n * @extends {fireauth.OAuthProvider}\n * @implements {fireauth.AuthProvider}\n */\nfireauth.GoogleAuthProvider = function() {\n fireauth.GoogleAuthProvider.base(this, 'constructor',\n fireauth.idp.ProviderId.GOOGLE);\n\n // Add profile scope to Google Auth provider as default scope.\n // This is to ensure profile info is populated in current user.\n this.addScope('profile');\n};\ngoog.inherits(fireauth.GoogleAuthProvider, fireauth.OAuthProvider);\n\nfireauth.object.setReadonlyProperty(fireauth.GoogleAuthProvider,\n 'PROVIDER_ID', fireauth.idp.ProviderId.GOOGLE);\n\nfireauth.object.setReadonlyProperty(fireauth.GoogleAuthProvider,\n 'GOOGLE_SIGN_IN_METHOD', fireauth.idp.SignInMethod.GOOGLE);\n\n\n/**\n * Initializes a Google AuthCredential.\n * @param {?string=} idTokenOrObject The Google ID token. If null or undefined,\n * we expect the access token to be passed. It can also be an object\n * containing the tokens for FirebaseUI backwards compatibility.\n * @param {?string=} accessToken The Google access token. If null or\n * undefined, we expect the ID token to have been passed.\n * @return {!fireauth.AuthCredential} The Auth credential object.\n */\nfireauth.GoogleAuthProvider.credential =\n function(idTokenOrObject, accessToken) {\n var idToken = idTokenOrObject;\n if (goog.isObject(idTokenOrObject)) {\n idToken = idTokenOrObject['idToken'];\n accessToken = idTokenOrObject['accessToken'];\n }\n return new fireauth.GoogleAuthProvider().credential({\n 'idToken': /** @type {string} */ (idToken),\n 'accessToken': /** @type {string} */ (accessToken)\n });\n};\n\n\n/**\n * Twitter Auth provider.\n * @constructor\n * @extends {fireauth.FederatedProvider}\n * @implements {fireauth.AuthProvider}\n */\nfireauth.TwitterAuthProvider = function() {\n fireauth.TwitterAuthProvider.base(this, 'constructor',\n fireauth.idp.ProviderId.TWITTER,\n fireauth.idp.RESERVED_OAUTH1_PARAMS);\n};\ngoog.inherits(fireauth.TwitterAuthProvider, fireauth.FederatedProvider);\n\nfireauth.object.setReadonlyProperty(fireauth.TwitterAuthProvider,\n 'PROVIDER_ID', fireauth.idp.ProviderId.TWITTER);\n\nfireauth.object.setReadonlyProperty(fireauth.TwitterAuthProvider,\n 'TWITTER_SIGN_IN_METHOD', fireauth.idp.SignInMethod.TWITTER);\n\n\n/**\n * Initializes a Twitter AuthCredential.\n * @param {string} tokenOrObject The Twitter access token, or object\n * containing the token for FirebaseUI backwards compatibility.\n * @param {string} secret The Twitter secret.\n * @return {!fireauth.AuthCredential} The Auth credential object.\n */\nfireauth.TwitterAuthProvider.credential = function(tokenOrObject, secret) {\n var tokenObject = tokenOrObject;\n if (!goog.isObject(tokenObject)) {\n tokenObject = {\n 'oauthToken': tokenOrObject,\n 'oauthTokenSecret': secret\n };\n }\n\n if (!tokenObject['oauthToken'] || !tokenObject['oauthTokenSecret']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n 'credential failed: expected 2 arguments (the OAuth access token ' +\n 'and secret).');\n }\n\n return new fireauth.OAuthCredential(fireauth.idp.ProviderId.TWITTER,\n /** @type {!fireauth.OAuthResponse} */ (tokenObject),\n fireauth.idp.SignInMethod.TWITTER);\n};\n\n\n/**\n * The email and password credential class.\n * @param {string} email The credential email.\n * @param {string} password The credential password.\n * @param {string=} opt_signInMethod The credential sign in method can be either\n * 'password' or 'emailLink'\n * @constructor\n * @implements {fireauth.AuthCredential}\n */\nfireauth.EmailAuthCredential = function(email, password, opt_signInMethod) {\n this.email_ = email;\n this.password_ = password;\n fireauth.object.setReadonlyProperty(this, 'providerId',\n fireauth.idp.ProviderId.PASSWORD);\n var signInMethod = opt_signInMethod ===\n fireauth.EmailAuthProvider['EMAIL_LINK_SIGN_IN_METHOD'] ?\n fireauth.EmailAuthProvider['EMAIL_LINK_SIGN_IN_METHOD'] :\n fireauth.EmailAuthProvider['EMAIL_PASSWORD_SIGN_IN_METHOD'];\n fireauth.object.setReadonlyProperty(this, 'signInMethod', signInMethod);\n};\n\n\n/**\n * Returns a promise to retrieve ID token using the underlying RPC handler API\n * for the current credential.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @return {!goog.Promise<!Object, !fireauth.AuthError>}\n * idTokenPromise The RPC handler method that returns a promise which\n * resolves with an ID token.\n * @override\n */\nfireauth.EmailAuthCredential.prototype.getIdTokenProvider =\n function(rpcHandler) {\n if (this['signInMethod'] ==\n fireauth.EmailAuthProvider['EMAIL_LINK_SIGN_IN_METHOD']) {\n return rpcHandler.emailLinkSignIn(this.email_, this.password_);\n }\n return rpcHandler.verifyPassword(this.email_, this.password_);\n};\n\n\n/**\n * Adds an email and password account to an existing account, identified by an\n * ID token.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @param {string} idToken The ID token of the existing account.\n * @return {!goog.Promise<!Object>} A Promise that resolves when the accounts\n * are linked, returning the backend response.\n * @override\n */\nfireauth.EmailAuthCredential.prototype.linkToIdToken =\n function(rpcHandler, idToken) {\n if (this['signInMethod'] ==\n fireauth.EmailAuthProvider['EMAIL_LINK_SIGN_IN_METHOD']) {\n return rpcHandler.emailLinkSignInForLinking(\n idToken, this.email_, this.password_);\n }\n return rpcHandler.updateEmailAndPassword(\n idToken, this.email_, this.password_);\n};\n\n\n/**\n * Tries to match the credential's idToken with the provided UID.\n * @param {!fireauth.RpcHandler} rpcHandler The rpc handler.\n * @param {string} uid The UID of the user to reauthenticate.\n * @return {!goog.Promise<!Object>} A Promise that resolves when\n * reauthentication succeeds.\n * @override\n */\nfireauth.EmailAuthCredential.prototype.matchIdTokenWithUid =\n function(rpcHandler, uid) {\n // Do not create a new account if the user doesn't exist.\n return fireauth.AuthCredential.verifyTokenResponseUid(\n // This shouldn't create a new email/password account.\n this.getIdTokenProvider(rpcHandler),\n uid);\n};\n\n\n/**\n * @return {!Object} The plain object representation of an Auth credential.\n * @override\n */\nfireauth.EmailAuthCredential.prototype.toPlainObject = function() {\n return {\n 'email': this.email_,\n 'password': this.password_,\n 'signInMethod': this['signInMethod']\n };\n};\n\n\n/**\n * @param {?Object|undefined} json The plain object representation of a\n * EmailAuthCredential.\n * @return {?fireauth.EmailAuthCredential} The email credential if the object\n * is a JSON representation of an EmailAuthCredential, null otherwise.\n */\nfireauth.EmailAuthCredential.fromJSON = function(json) {\n if (json && json['email'] && json['password']) {\n return new fireauth.EmailAuthCredential(\n json['email'],\n json['password'],\n json['signInMethod']);\n }\n return null;\n};\n\n\n/**\n * Email password Auth provider implementation.\n * @constructor\n * @implements {fireauth.AuthProvider}\n */\nfireauth.EmailAuthProvider = function() {\n // Set read-only instance providerId and isOAuthProvider property.\n fireauth.object.setReadonlyProperties(this, {\n 'providerId': fireauth.idp.ProviderId.PASSWORD,\n 'isOAuthProvider': false\n });\n};\n\n\n/**\n * Initializes an instance of an email/password Auth credential.\n * @param {string} email The credential email.\n * @param {string} password The credential password.\n * @return {!fireauth.EmailAuthCredential} The Auth credential object.\n */\nfireauth.EmailAuthProvider.credential = function(email, password) {\n return new fireauth.EmailAuthCredential(email, password);\n};\n\n\n/**\n * @param {string} email The credential email.\n * @param {string} emailLink The credential email link.\n * @return {!fireauth.EmailAuthCredential} The Auth credential object.\n */\nfireauth.EmailAuthProvider.credentialWithLink = function(email, emailLink) {\n var actionCodeUrl = fireauth.EmailAuthProvider\n .getActionCodeUrlFromSignInEmailLink(emailLink);\n if (!actionCodeUrl) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR, 'Invalid email link!');\n }\n return new fireauth.EmailAuthCredential(email, actionCodeUrl['code'],\n fireauth.EmailAuthProvider['EMAIL_LINK_SIGN_IN_METHOD']);\n};\n\n\n/**\n * @param {string} emailLink The sign in email link to be validated.\n * @return {?fireauth.ActionCodeURL} The sign in email link action code URL.\n * Returns null if the email link is invalid.\n */\nfireauth.EmailAuthProvider.getActionCodeUrlFromSignInEmailLink =\n function(emailLink) {\n emailLink = fireauth.DynamicLink.parseDeepLink(emailLink);\n var actionCodeUrl = fireauth.ActionCodeURL.parseLink(emailLink);\n if (actionCodeUrl && (actionCodeUrl['operation'] ===\n fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN)) {\n return actionCodeUrl;\n }\n return null;\n};\n\n\n// Set read only PROVIDER_ID property.\nfireauth.object.setReadonlyProperties(fireauth.EmailAuthProvider, {\n 'PROVIDER_ID': fireauth.idp.ProviderId.PASSWORD\n});\n\n// Set read only EMAIL_LINK_SIGN_IN_METHOD property.\nfireauth.object.setReadonlyProperties(fireauth.EmailAuthProvider, {\n 'EMAIL_LINK_SIGN_IN_METHOD': fireauth.idp.SignInMethod.EMAIL_LINK\n});\n\n// Set read only EMAIL_PASSWORD_SIGN_IN_METHOD property.\nfireauth.object.setReadonlyProperties(fireauth.EmailAuthProvider, {\n 'EMAIL_PASSWORD_SIGN_IN_METHOD': fireauth.idp.SignInMethod.EMAIL_PASSWORD\n});\n\n\n/**\n * A credential for phone number sign-in. Phone credentials can also be used as\n * second factor assertions.\n * A `PhoneAuthCredential` is also a `MultiFactorAuthCredential`. A\n * `PhoneMultiFactorAssertion` requires a `PhoneAuthCredential`.\n * @param {!fireauth.PhoneAuthCredential.Parameters_} params The credential\n * parameters that prove the user owns the claimed phone number.\n * @constructor\n * @implements {fireauth.MultiFactorAuthCredential}\n */\nfireauth.PhoneAuthCredential = function(params) {\n // Either verification ID and code, or phone number temporary proof must be\n // provided.\n if (!(params.verificationId && params.verificationCode) &&\n !(params.temporaryProof && params.phoneNumber)) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n\n /**\n * The phone Auth parameters that prove ownership of a phone number, either\n * through completion of a phone verification flow, or by referencing a\n * previously completed verification flow (\"temporaryProof\").\n * @private {!fireauth.PhoneAuthCredential.Parameters_}\n */\n this.params_ = params;\n\n fireauth.object.setReadonlyProperty(this, 'providerId',\n fireauth.idp.ProviderId.PHONE);\n /**\n * @public {string} The provider ID required by the\n * `fireauth.MultiFactorAuthCredential` interface.\n */\n this.providerId = fireauth.idp.ProviderId.PHONE;\n\n fireauth.object.setReadonlyProperty(\n this, 'signInMethod', fireauth.idp.SignInMethod.PHONE);\n};\n\n\n/**\n * Parameters that prove ownership of a phone number via a ID \"verificationId\"\n * of a request to send a code to the phone number, with the code\n * \"verificationCode\" that the user received on their phone.\n * @private\n * @typedef {{\n * verificationId: string,\n * verificationCode: string\n * }}\n */\nfireauth.PhoneAuthCredential.VerificationParameters_;\n\n\n/**\n * Parameters that prove ownership of a phone number by referencing a previously\n * completed phone Auth flow.\n * @private\n * @typedef {{\n * temporaryProof: string,\n * phoneNumber: string\n * }}\n */\nfireauth.PhoneAuthCredential.TemporaryProofParameters_;\n\n\n/**\n * @private\n * @typedef {\n * !fireauth.PhoneAuthCredential.VerificationParameters_|\n * !fireauth.PhoneAuthCredential.TemporaryProofParameters_\n * }\n */\nfireauth.PhoneAuthCredential.Parameters_;\n\n\n/**\n * Retrieves an ID token from the backend given the current credential.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @return {!goog.Promise<!Object>} A Promise that resolves with the\n * backend response.\n * @override\n */\nfireauth.PhoneAuthCredential.prototype.getIdTokenProvider =\n function(rpcHandler) {\n return rpcHandler.verifyPhoneNumber(this.makeVerifyPhoneNumberRequest_());\n};\n\n\n/**\n * Adds a phone credential to an existing account identified by an ID token.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @param {string} idToken The ID token of the existing account.\n * @return {!goog.Promise<!Object>} A Promise that resolves when the accounts\n * are linked, returning the backend response.\n * @override\n */\nfireauth.PhoneAuthCredential.prototype.linkToIdToken =\n function(rpcHandler, idToken) {\n var request = this.makeVerifyPhoneNumberRequest_();\n request['idToken'] = idToken;\n return rpcHandler.verifyPhoneNumberForLinking(request);\n};\n\n\n/**\n * Tries to match the credential's idToken with the provided UID.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler.\n * @param {string} uid The UID of the user to reauthenticate.\n * @return {!goog.Promise<!Object>} A Promise that resolves when\n * reauthentication succeeds.\n * @override\n */\nfireauth.PhoneAuthCredential.prototype.matchIdTokenWithUid =\n function(rpcHandler, uid) {\n var request = this.makeVerifyPhoneNumberRequest_();\n return fireauth.AuthCredential.verifyTokenResponseUid(\n rpcHandler.verifyPhoneNumberForExisting(request),\n uid);\n};\n\n\n/**\n * Converts a PhoneAuthCredential to a plain object.\n * @return {!Object}\n * @override\n */\nfireauth.PhoneAuthCredential.prototype.toPlainObject = function() {\n var obj = {\n 'providerId': fireauth.idp.ProviderId.PHONE\n };\n if (this.params_.verificationId) {\n obj['verificationId'] = this.params_.verificationId;\n }\n if (this.params_.verificationCode) {\n obj['verificationCode'] = this.params_.verificationCode;\n }\n if (this.params_.temporaryProof) {\n obj['temporaryProof'] = this.params_.temporaryProof;\n }\n if (this.params_.phoneNumber) {\n obj['phoneNumber'] = this.params_.phoneNumber;\n }\n return obj;\n};\n\n\n/**\n * @param {?Object|undefined} json The plain object representation of a\n * PhoneAuthCredential.\n * @return {?fireauth.PhoneAuthCredential} The phone credential if the object\n * is a JSON representation of an PhoneAuthCredential, null otherwise.\n */\nfireauth.PhoneAuthCredential.fromJSON = function(json) {\n if (json &&\n json['providerId'] === fireauth.idp.ProviderId.PHONE &&\n ((json['verificationId'] && json['verificationCode']) ||\n (json['temporaryProof'] && json['phoneNumber']))) {\n var params = {};\n var allowedKeys = [\n 'verificationId', 'verificationCode', 'temporaryProof', 'phoneNumber'\n ];\n goog.array.forEach(allowedKeys, function(key) {\n if (json[key]) {\n params[key] = json[key];\n }\n });\n return new fireauth.PhoneAuthCredential(\n /** @type {!fireauth.PhoneAuthCredential.Parameters_} */ (params));\n }\n return null;\n};\n\n\n/**\n * @return {!Object} A request to the verifyPhoneNumber endpoint based on the\n * current state of the object.\n * @private\n */\nfireauth.PhoneAuthCredential.prototype.makeVerifyPhoneNumberRequest_ =\n function() {\n if (this.params_.temporaryProof && this.params_.phoneNumber) {\n return {\n 'temporaryProof': this.params_.temporaryProof,\n 'phoneNumber': this.params_.phoneNumber\n };\n }\n\n return {\n 'sessionInfo': this.params_.verificationId,\n 'code': this.params_.verificationCode\n };\n};\n\n\n/**\n * Finalizes the 2nd factor enrollment flow with the current AuthCredential\n * using the enrollment request identifier.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorEnrollmentRequestIdentifier} enrollmentRequest\n * The enrollment request identifying the user.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the updated ID and refresh tokens.\n * @override\n */\nfireauth.PhoneAuthCredential.prototype.finalizeMfaEnrollment =\n function(rpcHandler, enrollmentRequest) {\n goog.object.extend(\n enrollmentRequest,\n {\n 'phoneVerificationInfo': this.makeVerifyPhoneNumberRequest_()\n });\n return /** @type {!goog.Promise<{idToken: string, refreshToken: string}>} */ (\n rpcHandler.finalizePhoneMfaEnrollment(enrollmentRequest));\n};\n\n\n/**\n * Finalizes the 2nd factor sign-in flow with the current AuthCredential\n * using the sign-in request identifier.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorSignInRequestIdentifier} signInRequest\n * The sign-in request identifying the user.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the signed in user's ID and refresh tokens.\n * @override\n */\nfireauth.PhoneAuthCredential.prototype.finalizeMfaSignIn =\n function(rpcHandler, signInRequest) {\n goog.object.extend(\n signInRequest,\n {\n 'phoneVerificationInfo': this.makeVerifyPhoneNumberRequest_()\n });\n return /** @type {!goog.Promise<{idToken: string, refreshToken: string}>} */ (\n rpcHandler.finalizePhoneMfaSignIn(signInRequest));\n};\n\n\n/**\n * Phone Auth provider implementation.\n * @param {?fireauth.Auth=} opt_auth The Firebase Auth instance.\n * @constructor\n * @implements {fireauth.AuthProvider}\n */\nfireauth.PhoneAuthProvider = function(opt_auth) {\n try {\n /** @private {!fireauth.Auth} */\n this.auth_ = opt_auth || firebase['auth']();\n } catch (e) {\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n 'Either an instance of firebase.auth.Auth must be passed as an ' +\n 'argument to the firebase.auth.PhoneAuthProvider constructor, or the ' +\n 'default firebase App instance must be initialized via ' +\n 'firebase.initializeApp().');\n }\n fireauth.object.setReadonlyProperties(this, {\n 'providerId': fireauth.idp.ProviderId.PHONE,\n 'isOAuthProvider': false\n });\n};\n\n\n/**\n * The phone info options for single-factor sign-in. Only phone number is\n * required.\n * @private\n * @typedef {{\n * phoneNumber: string\n * }}\n */\nfireauth.PhoneAuthProvider.PhoneSingleFactorInfoOptions_;\n\n/**\n * The phone info options for multi-factor enrollment. Phone number and\n * multi-factor session are required.\n * @private\n * @typedef {{\n * phoneNumber: string,\n * session: !fireauth.MultiFactorSession\n * }}\n */\nfireauth.PhoneAuthProvider.PhoneMultiFactorEnrollInfoOptions_;\n\n\n/**\n * The phone info options for multi-factor sign-in. Either multi-factor hint or\n * multi-factor UID and multi-factor session are required.\n * @private\n * @typedef {{\n * multiFactorHint: !fireauth.MultiFactorInfo,\n * session: !fireauth.MultiFactorSession\n * }|{\n * multiFactorUid: string,\n * session: !fireauth.MultiFactorSession\n * }}\n */\nfireauth.PhoneAuthProvider.PhoneMultiFactorSignInInfoOptions_;\n\n\n/**\n * The options for verifying the ownership of the phone number. It could be\n * used for single-factor sign-in, multi-factor enrollment or multi-factor\n * sign-in.\n * @typedef {\n * !fireauth.PhoneAuthProvider.PhoneSingleFactorInfoOptions_|\n * !fireauth.PhoneAuthProvider.PhoneMultiFactorEnrollInfoOptions_|\n * !fireauth.PhoneAuthProvider.PhoneMultiFactorSignInInfoOptions_\n * }\n */\nfireauth.PhoneAuthProvider.PhoneInfoOptions;\n\n\n/**\n * Initiates a phone number confirmation flow. If session is provided, it is\n * used to verify ownership of the second factor phone number.\n *\n * @param {string|!fireauth.PhoneAuthProvider.PhoneInfoOptions} phoneInfoOptions\n * The user's phone options for verifying the ownship of the phone number.\n * @param {!firebase.auth.ApplicationVerifier} applicationVerifier The\n * application verifier for anti-abuse purposes.\n * @return {!goog.Promise<string>} A Promise that resolves with the\n * verificationId of the phone number confirmation flow.\n */\nfireauth.PhoneAuthProvider.prototype.verifyPhoneNumber =\n function(phoneInfoOptions, applicationVerifier) {\n var rpcHandler = this.auth_.getRpcHandler();\n\n // Convert the promise into a goog.Promise. If the applicationVerifier throws\n // an error, just propagate it to the client. Reset the reCAPTCHA widget every\n // time after sending the token to the server.\n return goog.Promise.resolve(applicationVerifier['verify']())\n .then(function(assertion) {\n if (typeof assertion !== 'string') {\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n 'An implementation of firebase.auth.ApplicationVerifier' +\n '.prototype.verify() must return a firebase.Promise ' +\n 'that resolves with a string.');\n }\n\n switch (applicationVerifier['type']) {\n case 'recaptcha':\n var session = goog.isObject(phoneInfoOptions) ?\n phoneInfoOptions['session'] : null;\n // PhoneInfoOptions can be a phone number string for backward\n // compatibility.\n var phoneNumber = goog.isObject(phoneInfoOptions) ?\n phoneInfoOptions['phoneNumber'] : phoneInfoOptions;\n var verifyPromise;\n if (session &&\n session.type == fireauth.MultiFactorSession.Type.ENROLL) {\n verifyPromise = session.getRawSession()\n .then(function(rawSession) {\n return rpcHandler.startPhoneMfaEnrollment({\n 'idToken': rawSession,\n 'phoneEnrollmentInfo': {\n 'phoneNumber': phoneNumber,\n 'recaptchaToken': assertion\n }\n });\n });\n } else if (session &&\n session.type ==\n fireauth.MultiFactorSession.Type.SIGN_IN) {\n verifyPromise = session.getRawSession()\n .then(function(rawSession) {\n var mfaEnrollmentId =\n (phoneInfoOptions['multiFactorHint'] &&\n phoneInfoOptions['multiFactorHint']['uid']) ||\n phoneInfoOptions['multiFactorUid'];\n return rpcHandler.startPhoneMfaSignIn({\n 'mfaPendingCredential': rawSession,\n 'mfaEnrollmentId': mfaEnrollmentId,\n 'phoneSignInInfo': {\n 'recaptchaToken': assertion\n }\n });\n });\n } else {\n verifyPromise = rpcHandler.sendVerificationCode({\n 'phoneNumber': phoneNumber,\n 'recaptchaToken': assertion\n });\n }\n // Reset the applicationVerifier after code is sent.\n return verifyPromise.then(function(verificationId) {\n if (typeof applicationVerifier.reset === 'function') {\n applicationVerifier.reset();\n }\n return verificationId;\n }, function(error) {\n if (typeof applicationVerifier.reset === 'function') {\n applicationVerifier.reset();\n }\n throw error;\n });\n default:\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n 'Only firebase.auth.ApplicationVerifiers with ' +\n 'type=\"recaptcha\" are currently supported.');\n }\n });\n};\n\n\n/**\n * Creates a PhoneAuthCredential.\n * @param {string} verificationId The ID of the phone number flow, to correlate\n * this request with a previous call to\n * PhoneAuthProvider.prototype.verifyPhoneNumber.\n * @param {string} verificationCode The verification code that was sent to the\n * user's phone.\n * @return {!fireauth.PhoneAuthCredential}\n */\nfireauth.PhoneAuthProvider.credential =\n function(verificationId, verificationCode) {\n if (!verificationId) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_SESSION_INFO);\n }\n if (!verificationCode) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_CODE);\n }\n return new fireauth.PhoneAuthCredential({\n verificationId: verificationId,\n verificationCode: verificationCode\n });\n};\n\n\n// Set read only PROVIDER_ID property.\nfireauth.object.setReadonlyProperties(fireauth.PhoneAuthProvider, {\n 'PROVIDER_ID': fireauth.idp.ProviderId.PHONE\n});\n\n\n// Set read only PHONE_SIGN_IN_METHOD property.\nfireauth.object.setReadonlyProperties(fireauth.PhoneAuthProvider, {\n 'PHONE_SIGN_IN_METHOD': fireauth.idp.SignInMethod.PHONE\n});\n\n\n/**\n * Constructs an Auth credential from a backend response.\n * Note, unlike fromJSON which constructs the AuthCredential from a toJSON()\n * response, this helper constructs the credential from the server response.\n * @param {?Object} response The backend response to build a credential from.\n * @return {?fireauth.AuthCredential} The corresponding AuthCredential.\n */\nfireauth.AuthProvider.getCredentialFromResponse = function(response) {\n // Handle phone Auth credential responses, as they have a different format\n // from other backend responses (i.e. no providerId).\n if (response['temporaryProof'] && response['phoneNumber']) {\n return new fireauth.PhoneAuthCredential({\n temporaryProof: response['temporaryProof'],\n phoneNumber: response['phoneNumber']\n });\n }\n\n // Get all OAuth response parameters from response.\n var providerId = response && response['providerId'];\n\n // Email and password is not supported as there is no situation where the\n // server would return the password to the client.\n if (!providerId || providerId === fireauth.idp.ProviderId.PASSWORD) {\n return null;\n }\n\n var accessToken = response && response['oauthAccessToken'];\n var accessTokenSecret = response && response['oauthTokenSecret'];\n // Note this is not actually returned by the backend. It is introduced in\n // rpcHandler.\n var rawNonce = response && response['nonce'];\n // Google Id Token returned when no additional scopes provided.\n var idToken = response && response['oauthIdToken'];\n // Pending token for SAML and OAuth/OIDC providers.\n var pendingToken = response && response['pendingToken'];\n try {\n switch (providerId) {\n case fireauth.idp.ProviderId.GOOGLE:\n return fireauth.GoogleAuthProvider.credential(\n idToken, accessToken);\n\n case fireauth.idp.ProviderId.FACEBOOK:\n return fireauth.FacebookAuthProvider.credential(\n accessToken);\n\n case fireauth.idp.ProviderId.GITHUB:\n return fireauth.GithubAuthProvider.credential(\n accessToken);\n\n case fireauth.idp.ProviderId.TWITTER:\n return fireauth.TwitterAuthProvider.credential(\n accessToken, accessTokenSecret);\n\n default:\n if (!accessToken && !accessTokenSecret && !idToken && !pendingToken) {\n return null;\n }\n if (pendingToken) {\n if (providerId.indexOf(fireauth.constants.SAML_PREFIX) == 0) {\n return new fireauth.SAMLAuthCredential(providerId, pendingToken);\n } else {\n // OIDC and non-default providers excluding Twitter.\n return new fireauth.OAuthCredential(\n providerId,\n {\n 'pendingToken': pendingToken,\n 'idToken': response['oauthIdToken'],\n 'accessToken': response['oauthAccessToken']\n },\n providerId);\n }\n }\n return new fireauth.OAuthProvider(providerId).credential({\n 'idToken': idToken,\n 'accessToken': accessToken,\n 'rawNonce': rawNonce\n });\n }\n } catch (e) {\n return null;\n }\n};\n\n\n/**\n * Constructs an Auth credential from a JSON representation.\n * Note, unlike getCredentialFromResponse which constructs the AuthCredential\n * from a server response, this helper constructs credential from the toJSON()\n * result.\n * @param {!Object|string} json The JSON representation to construct credential\n * from.\n * @return {?fireauth.AuthCredential} The corresponding AuthCredential.\n */\nfireauth.AuthProvider.getCredentialFromJSON = function(json) {\n var obj = typeof json === 'string' ? JSON.parse(json) : json;\n var credential;\n var fromJSON = [\n fireauth.OAuthCredential.fromJSON,\n fireauth.EmailAuthCredential.fromJSON,\n fireauth.PhoneAuthCredential.fromJSON,\n fireauth.SAMLAuthCredential.fromJSON\n ];\n for (var i = 0; i < fromJSON.length; i++) {\n credential = fromJSON[i](obj);\n if (credential) {\n return credential;\n }\n }\n return null;\n};\n\n\n/**\n * Constructs an Auth credential from a JSON representation.\n * @param {!Object|string} json The JSON representation to construct credential from.\n * @return {?fireauth.AuthCredential} The corresponding AuthCredential.\n */\nfireauth.AuthCredential.fromPlainObject =\n fireauth.AuthProvider.getCredentialFromJSON;\n\n\n/**\n * Checks if OAuth is supported by provider, if not throws an error.\n * @param {!fireauth.AuthProvider} provider The provider to check.\n */\nfireauth.AuthProvider.checkIfOAuthSupported =\n function(provider) {\n if (!provider['isOAuthProvider']) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INVALID_OAUTH_PROVIDER);\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Auth event object.\n */\n\ngoog.provide('fireauth.AuthEvent');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\n\n\n/**\n * Defines the authentication event.\n * @param {!fireauth.AuthEvent.Type} type The Auth event type.\n * @param {?string=} opt_eventId The event identifier.\n * @param {?string=} opt_urlResponse The URL with IdP response.\n * @param {?string=} opt_sessionId The session ID used to prevent session\n * fixation attacks.\n * @param {?fireauth.AuthError=} opt_error The optional error encountered.\n * @param {?string=} opt_postBody The optional POST body.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @constructor\n */\nfireauth.AuthEvent = function(\n type, opt_eventId, opt_urlResponse, opt_sessionId, opt_error,\n opt_postBody, opt_tenantId) {\n /** @const @private {!fireauth.AuthEvent.Type} The Auth event type. */\n this.type_ = type;\n /** @const @private {?string} The Auth event ID. */\n this.eventId_ = opt_eventId || null;\n /** @const @private {?string} The callback URL with the sign in response. */\n this.urlResponse_ = opt_urlResponse || null;\n /** @const @private {?string} The sign in operation session ID. */\n this.sessionId_ = opt_sessionId || null;\n /** @const @private {?string} The POST body string if available. */\n this.postBody_ = opt_postBody || null;\n /** @const @private {?string} The tenant ID if available. */\n this.tenantId_ = opt_tenantId || null;\n /**\n * @const @private {?fireauth.AuthError} The Auth event error if available.\n */\n this.error_ = opt_error || null;\n if (!this.urlResponse_ && !this.error_) {\n // Either URL or error is required. They can't be both null.\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT);\n } else if (this.urlResponse_ && this.error_) {\n // An error must not be provided when a URL is available.\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT);\n } else if (this.urlResponse_ && !this.sessionId_) {\n // A session ID must accompany a URL response.\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT);\n }\n};\n\n\n\n/**\n * Auth event operation types.\n * All Auth event types that are used for popup operations should be suffixed\n * with `Popup`, whereas those used for redirect operations should be suffixed\n * with `Redirect`.\n * TODO: consider changing the type from a string to an object with ID\n * and some metadata for determining mode: redirect, popup or none.\n * @enum {string}\n */\nfireauth.AuthEvent.Type = {\n LINK_VIA_POPUP: 'linkViaPopup',\n LINK_VIA_REDIRECT: 'linkViaRedirect',\n REAUTH_VIA_POPUP: 'reauthViaPopup',\n REAUTH_VIA_REDIRECT: 'reauthViaRedirect',\n SIGN_IN_VIA_POPUP: 'signInViaPopup',\n SIGN_IN_VIA_REDIRECT: 'signInViaRedirect',\n UNKNOWN: 'unknown',\n VERIFY_APP: 'verifyApp'\n};\n\n\n/**\n * @param {!fireauth.AuthEvent} event The Auth event.\n * @return {boolean} Whether the event is a redirect type.\n */\nfireauth.AuthEvent.isRedirect = function(event) {\n return !!event.getType().match(/Redirect$/);\n};\n\n\n/**\n * @param {!fireauth.AuthEvent} event The Auth event.\n * @return {boolean} Whether the event is a popup type.\n */\nfireauth.AuthEvent.isPopup = function(event) {\n return !!event.getType().match(/Popup$/);\n};\n\n\n/** @return {!fireauth.AuthEvent.Type} The type of Auth event. */\nfireauth.AuthEvent.prototype.getType = function() {\n return this.type_;\n};\n\n\n/** @return {?string} The Auth event identifier. */\nfireauth.AuthEvent.prototype.getEventId = function() {\n return this.eventId_;\n};\n\n\n/** @return {string} The event unique identifier. */\nfireauth.AuthEvent.prototype.getUid = function() {\n var components = [];\n components.push(this.type_);\n if (this.eventId_) {\n components.push(this.eventId_);\n }\n if (this.sessionId_) {\n components.push(this.sessionId_);\n }\n if (this.tenantId_) {\n components.push(this.tenantId_);\n }\n return components.join('-');\n};\n\n\n/** @return {?string} The url response of Auth event. */\nfireauth.AuthEvent.prototype.getUrlResponse = function() {\n return this.urlResponse_;\n};\n\n\n/** @return {?string} The session ID Auth event. */\nfireauth.AuthEvent.prototype.getSessionId = function() {\n return this.sessionId_;\n};\n\n\n/** @return {?string} The POST body of the Auth event, if available. */\nfireauth.AuthEvent.prototype.getPostBody = function() {\n return this.postBody_;\n};\n\n\n/** @return {?string} The tenant ID of the Auth event, if available. */\nfireauth.AuthEvent.prototype.getTenantId = function() {\n return this.tenantId_;\n};\n\n\n/** @return {?fireauth.AuthError} The error of Auth event. */\nfireauth.AuthEvent.prototype.getError = function() {\n return this.error_;\n};\n\n\n/** @return {boolean} Whether Auth event has an error. */\nfireauth.AuthEvent.prototype.hasError = function() {\n return !!this.error_;\n};\n\n\n/** @return {!Object} The plain object representation of event. */\nfireauth.AuthEvent.prototype.toPlainObject = function() {\n return {\n 'type': this.type_,\n 'eventId': this.eventId_,\n 'urlResponse': this.urlResponse_,\n 'sessionId': this.sessionId_,\n 'postBody': this.postBody_,\n 'tenantId': this.tenantId_,\n 'error': this.error_ && this.error_.toPlainObject()\n };\n};\n\n\n/**\n * @param {?Object} rawResponse The plain object representation of Auth event.\n * @return {?fireauth.AuthEvent} The Auth event representation of plain object.\n */\nfireauth.AuthEvent.fromPlainObject = function(rawResponse) {\n var response = rawResponse || {};\n if (response['type']) {\n return new fireauth.AuthEvent(\n response['type'],\n response['eventId'],\n response['urlResponse'],\n response['sessionId'],\n response['error'] &&\n fireauth.AuthError.fromPlainObject(response['error']),\n response['postBody'],\n response['tenantId']\n );\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 the universal link subscriber utility to allow\n * multiple subscriptions for incoming universal link detection.\n */\ngoog.provide('fireauth.UniversalLinkSubscriber');\n\ngoog.require('fireauth.util');\ngoog.require('goog.array');\n\n/**\n * Defines the universal link subscriber class used to allow multiple universal\n * link subscriptions since the underlying plugin only works with one.\n * This utility is needed since the universal link cordova plugin can only allow\n * one subscriber and multiple app instances can subscribe to this.\n * @constructor @final @struct\n */\nfireauth.UniversalLinkSubscriber = function() {\n /**\n * @private {?function(?Object)} The master callback that subscribes directly\n * to universalLinks.\n */\n this.masterCb_ = null;\n /**\n * @private {!Array<function(?Object)>} The list of external subscribers that\n * are triggered every time the master callback is triggered.\n */\n this.cb_ = [];\n};\n\n\n/**\n * @return {!fireauth.UniversalLinkSubscriber} The default universal link\n * subscriber instance.\n */\nfireauth.UniversalLinkSubscriber.getInstance = function() {\n if (!fireauth.UniversalLinkSubscriber.instance_) {\n fireauth.UniversalLinkSubscriber.instance_ =\n new fireauth.UniversalLinkSubscriber();\n }\n return fireauth.UniversalLinkSubscriber.instance_;\n};\n\n\n/** Clears singleton instance. Useful for testing. */\nfireauth.UniversalLinkSubscriber.clear = function() {\n fireauth.UniversalLinkSubscriber.instance_ = null;\n};\n\n\n/**\n * @private {?fireauth.UniversalLinkSubscriber} The singleton universal\n * link subscriber instance.\n */\nfireauth.UniversalLinkSubscriber.instance_ = null;\n\n\n/**\n * Subscribes a callback to the universal link plugin listener.\n * @param {function(?Object)} cb The callback to subscribe to the universal\n * link plugin.\n */\nfireauth.UniversalLinkSubscriber.prototype.subscribe = function(cb) {\n var self = this;\n this.cb_.push(cb);\n if (!this.masterCb_) {\n this.masterCb_ = function(event) {\n for (var i = 0; i < self.cb_.length; i++) {\n self.cb_[i](event);\n }\n };\n var subscribe = fireauth.util.getObjectRef(\n 'universalLinks.subscribe', goog.global);\n // For iOS environments, this plugin is not used, therefore this is a no-op\n // and no error needs to be thrown.\n if (typeof subscribe === 'function') {\n subscribe(null, this.masterCb_);\n }\n }\n};\n\n\n/**\n * Unsubscribes a callback from the universal link plugin listener.\n * @param {function(?Object)} cb The callback to unsubscribe from the universal\n * link plugin.\n */\nfireauth.UniversalLinkSubscriber.prototype.unsubscribe = function(cb) {\n goog.array.removeAllIf(this.cb_, function(ele) {\n return ele == cb;\n });\n};\n\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Utility for handling RPC requests to server.\n */\ngoog.provide('fireauth.RpcHandler');\ngoog.provide('fireauth.RpcHandler.ApiMethodHandler');\ngoog.provide('fireauth.RpcHandler.VerifyAssertionData');\ngoog.provide('fireauth.XmlHttpFactory');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthErrorWithCredential');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.idp');\ngoog.require('fireauth.idp.ProviderId');\ngoog.require('fireauth.object');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.Uri');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.json');\ngoog.require('goog.net.CorsXmlHttpFactory');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.net.XhrIo');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.require('goog.net.jsloader');\ngoog.require('goog.object');\ngoog.require('goog.string.Const');\n\n\n\n/**\n * Firebase Auth XmlHttpRequest factory. This is useful for environments like\n * Node.js where XMLHttpRequest does not exist. XmlHttpFactory would be\n * initialized using the polyfill XMLHttpRequest module.\n * @param {function(new:XMLHttpRequest)} xmlHttpRequest The xmlHttpRequest\n * constructor.\n * @constructor\n * @extends {goog.net.XmlHttpFactory}\n * @final\n */\nfireauth.XmlHttpFactory = function(xmlHttpRequest) {\n /**\n * @private {function(new:XMLHttpRequest)} The underlying XHR reference.\n */\n this.xmlHttpRequest_ = xmlHttpRequest;\n fireauth.XmlHttpFactory.base(this, 'constructor');\n};\ngoog.inherits(fireauth.XmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/**\n * @return {!goog.net.XhrLike|!XMLHttpRequest} A new XhrLike instance.\n * @override\n */\nfireauth.XmlHttpFactory.prototype.createInstance = function() {\n return new this.xmlHttpRequest_();\n};\n\n\n/**\n * @return {!Object} Options describing how XHR objects obtained from this\n * factory should be used.\n * @override\n */\nfireauth.XmlHttpFactory.prototype.internalGetOptions = function() {\n return {};\n};\n\n\n\n/**\n * Creates an RPC request handler for the project specified by the API key.\n *\n * @param {string} apiKey The API key.\n * @param {?Object=} opt_config The RPC request processor configuration.\n * @param {?string=} opt_firebaseClientVersion The optional Firebase client\n * version to log with requests to Firebase Auth server.\n * @constructor\n */\nfireauth.RpcHandler = function(apiKey, opt_config, opt_firebaseClientVersion) {\n /** @private {string} The project API key. */\n this.apiKey_ = apiKey;\n var config = opt_config || {};\n this.secureTokenEndpoint_ = config['secureTokenEndpoint'] ||\n fireauth.RpcHandler.SECURE_TOKEN_ENDPOINT_;\n /**\n * @private @const {!fireauth.util.Delay} The delay for secure token endpoint\n * network timeout.\n */\n this.secureTokenTimeout_ = config['secureTokenTimeout'] ||\n fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_TIMEOUT_;\n /** @private @const {!Object} The secure token server headers. */\n this.secureTokenHeaders_ = goog.object.clone(\n config['secureTokenHeaders'] ||\n fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_HEADERS_);\n /** @private @const {string} The Firebase Auth endpoint. */\n this.firebaseEndpoint_ = config['firebaseEndpoint'] ||\n fireauth.RpcHandler.FIREBASE_ENDPOINT_;\n /** @private @const {string} The identity platform endpoint. */\n this.identityPlatformEndpoint_ = config['identityPlatformEndpoint'] ||\n fireauth.RpcHandler.IDENTITY_PLATFORM_ENDPOINT_;\n /**\n * @private @const {!fireauth.util.Delay} The delay for Firebase Auth endpoint\n * network timeout.\n */\n this.firebaseTimeout_ = config['firebaseTimeout'] ||\n fireauth.RpcHandler.DEFAULT_FIREBASE_TIMEOUT_;\n this.firebaseHeaders_ = goog.object.clone(\n config['firebaseHeaders'] ||\n fireauth.RpcHandler.DEFAULT_FIREBASE_HEADERS_);\n // If Firebase client version needs to be logged too.\n if (opt_firebaseClientVersion) {\n // Log client version for Firebase Auth server.\n this.firebaseHeaders_['X-Client-Version'] = opt_firebaseClientVersion;\n // Log client version for securetoken server.\n this.secureTokenHeaders_['X-Client-Version'] = opt_firebaseClientVersion;\n }\n\n // Get XMLHttpRequest reference.\n var XMLHttpRequest = fireauth.RpcHandler.getXMLHttpRequest();\n if (!XMLHttpRequest && !fireauth.util.isWorker()) {\n // In a Node.js environment, xmlhttprequest module needs to be required.\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'The XMLHttpRequest compatibility library was not found.');\n }\n /** @private {!goog.net.XmlHttpFactory|undefined} The XHR factory. */\n this.rpcHandlerXhrFactory_ = undefined;\n // Initialize XHR factory. CORS does not apply in native environments or\n // workers so don't use CorsXmlHttpFactory in those cases.\n if (fireauth.util.isWorker()) {\n // For worker environment use FetchXmlHttpFactory.\n this.rpcHandlerXhrFactory_ = new goog.net.FetchXmlHttpFactory(\n /** @type {!WorkerGlobalScope} */ (self));\n } else if (fireauth.util.isNativeEnvironment()) {\n // For Node.js, this is the polyfill library. For other environments,\n // this is the native global XMLHttpRequest.\n this.rpcHandlerXhrFactory_ = new fireauth.XmlHttpFactory(\n /** @type {function(new:XMLHttpRequest)} */ (XMLHttpRequest));\n } else {\n // CORS Browser environment.\n this.rpcHandlerXhrFactory_ = new goog.net.CorsXmlHttpFactory();\n }\n /** @private {?string} The tenant ID. */\n this.tenantId_ = null;\n};\n\n\n/**\n * @return {?function(new:XMLHttpRequest)|undefined} The current environment\n * XMLHttpRequest. This is undefined for worker environment.\n */\nfireauth.RpcHandler.getXMLHttpRequest = function() {\n // In Node.js XMLHttpRequest is polyfilled.\n var isNode = fireauth.util.getEnvironment() == fireauth.util.Env.NODE;\n var XMLHttpRequest = goog.global['XMLHttpRequest'] ||\n (isNode &&\n firebase.INTERNAL['node'] &&\n firebase.INTERNAL['node']['XMLHttpRequest']);\n return XMLHttpRequest;\n};\n\n\n/**\n * Enums for HTTP request methods.\n * @enum {string}\n */\nfireauth.RpcHandler.HttpMethod = {\n POST: 'POST',\n GET: 'GET'\n};\n\n\n/**\n * Firebase Auth server error codes.\n * @enum {string}\n */\nfireauth.RpcHandler.ServerError = {\n ADMIN_ONLY_OPERATION: 'ADMIN_ONLY_OPERATION',\n CAPTCHA_CHECK_FAILED: 'CAPTCHA_CHECK_FAILED',\n CORS_UNSUPPORTED: 'CORS_UNSUPPORTED',\n CREDENTIAL_MISMATCH: 'CREDENTIAL_MISMATCH',\n CREDENTIAL_TOO_OLD_LOGIN_AGAIN: 'CREDENTIAL_TOO_OLD_LOGIN_AGAIN',\n DYNAMIC_LINK_NOT_ACTIVATED: 'DYNAMIC_LINK_NOT_ACTIVATED',\n EMAIL_CHANGE_NEEDS_VERIFICATION: 'EMAIL_CHANGE_NEEDS_VERIFICATION',\n EMAIL_EXISTS: 'EMAIL_EXISTS',\n EMAIL_NOT_FOUND: 'EMAIL_NOT_FOUND',\n EXPIRED_OOB_CODE: 'EXPIRED_OOB_CODE',\n FEDERATED_USER_ID_ALREADY_LINKED: 'FEDERATED_USER_ID_ALREADY_LINKED',\n INVALID_APP_CREDENTIAL: 'INVALID_APP_CREDENTIAL',\n INVALID_APP_ID: 'INVALID_APP_ID',\n INVALID_CERT_HASH: 'INVALID_CERT_HASH',\n INVALID_CODE: 'INVALID_CODE',\n INVALID_CONTINUE_URI: 'INVALID_CONTINUE_URI',\n INVALID_CUSTOM_TOKEN: 'INVALID_CUSTOM_TOKEN',\n INVALID_DYNAMIC_LINK_DOMAIN: 'INVALID_DYNAMIC_LINK_DOMAIN',\n INVALID_EMAIL: 'INVALID_EMAIL',\n INVALID_ID_TOKEN: 'INVALID_ID_TOKEN',\n INVALID_IDP_RESPONSE: 'INVALID_IDP_RESPONSE',\n INVALID_IDENTIFIER: 'INVALID_IDENTIFIER',\n INVALID_MESSAGE_PAYLOAD: 'INVALID_MESSAGE_PAYLOAD',\n INVALID_MFA_PENDING_CREDENTIAL: 'INVALID_MFA_PENDING_CREDENTIAL',\n INVALID_OAUTH_CLIENT_ID: 'INVALID_OAUTH_CLIENT_ID',\n INVALID_OOB_CODE: 'INVALID_OOB_CODE',\n INVALID_PASSWORD: 'INVALID_PASSWORD',\n INVALID_PENDING_TOKEN: 'INVALID_PENDING_TOKEN',\n INVALID_PHONE_NUMBER: 'INVALID_PHONE_NUMBER',\n INVALID_PROVIDER_ID: 'INVALID_PROVIDER_ID',\n INVALID_RECIPIENT_EMAIL: 'INVALID_RECIPIENT_EMAIL',\n INVALID_SENDER: 'INVALID_SENDER',\n INVALID_SESSION_INFO: 'INVALID_SESSION_INFO',\n INVALID_TEMPORARY_PROOF: 'INVALID_TEMPORARY_PROOF',\n INVALID_TENANT_ID: 'INVALID_TENANT_ID',\n MFA_ENROLLMENT_NOT_FOUND: 'MFA_ENROLLMENT_NOT_FOUND',\n MISSING_ANDROID_PACKAGE_NAME: 'MISSING_ANDROID_PACKAGE_NAME',\n MISSING_APP_CREDENTIAL: 'MISSING_APP_CREDENTIAL',\n MISSING_CODE: 'MISSING_CODE',\n MISSING_CONTINUE_URI: 'MISSING_CONTINUE_URI',\n MISSING_CUSTOM_TOKEN: 'MISSING_CUSTOM_TOKEN',\n MISSING_IOS_BUNDLE_ID: 'MISSING_IOS_BUNDLE_ID',\n MISSING_MFA_ENROLLMENT_ID: 'MISSING_MFA_ENROLLMENT_ID',\n MISSING_MFA_PENDING_CREDENTIAL: 'MISSING_MFA_PENDING_CREDENTIAL',\n MISSING_OOB_CODE: 'MISSING_OOB_CODE',\n MISSING_OR_INVALID_NONCE: 'MISSING_OR_INVALID_NONCE',\n MISSING_PASSWORD: 'MISSING_PASSWORD',\n MISSING_PHONE_NUMBER: 'MISSING_PHONE_NUMBER',\n MISSING_SESSION_INFO: 'MISSING_SESSION_INFO',\n OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',\n PASSWORD_LOGIN_DISABLED: 'PASSWORD_LOGIN_DISABLED',\n QUOTA_EXCEEDED: 'QUOTA_EXCEEDED',\n RESET_PASSWORD_EXCEED_LIMIT: 'RESET_PASSWORD_EXCEED_LIMIT',\n REJECTED_CREDENTIAL: 'REJECTED_CREDENTIAL',\n SECOND_FACTOR_EXISTS: 'SECOND_FACTOR_EXISTS',\n SECOND_FACTOR_LIMIT_EXCEEDED: 'SECOND_FACTOR_LIMIT_EXCEEDED',\n SESSION_EXPIRED: 'SESSION_EXPIRED',\n TENANT_ID_MISMATCH: 'TENANT_ID_MISMATCH',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n TOO_MANY_ATTEMPTS_TRY_LATER: 'TOO_MANY_ATTEMPTS_TRY_LATER',\n UNSUPPORTED_FIRST_FACTOR: 'UNSUPPORTED_FIRST_FACTOR',\n UNSUPPORTED_TENANT_OPERATION: 'UNSUPPORTED_TENANT_OPERATION',\n UNVERIFIED_EMAIL: 'UNVERIFIED_EMAIL',\n UNAUTHORIZED_DOMAIN: 'UNAUTHORIZED_DOMAIN',\n USER_CANCELLED: 'USER_CANCELLED',\n USER_DISABLED: 'USER_DISABLED',\n USER_NOT_FOUND: 'USER_NOT_FOUND',\n WEAK_PASSWORD: 'WEAK_PASSWORD'\n};\n\n\n/**\n * A map of server error codes to client errors.\n * @typedef {!Object<\n * !fireauth.RpcHandler.ServerError, !fireauth.authenum.Error>}\n */\nfireauth.RpcHandler.ServerErrorMap;\n\n\n/**\n * Firebase Auth response field names.\n * @enum {string}\n */\nfireauth.RpcHandler.AuthServerField = {\n ALL_PROVIDERS: 'allProviders',\n AUTH_URI: 'authUri',\n AUTHORIZED_DOMAINS: 'authorizedDomains',\n DYNAMIC_LINKS_DOMAIN: 'dynamicLinksDomain',\n EMAIL: 'email',\n ERROR_MESSAGE: 'errorMessage',\n EXPIRES_IN: 'expiresIn',\n ID_TOKEN: 'idToken',\n MFA_PENDING_CREDENTIAL: 'mfaPendingCredential',\n NEED_CONFIRMATION: 'needConfirmation',\n OAUTH_ID_TOKEN: 'oauthIdToken',\n PENDING_TOKEN: 'pendingToken',\n PHONE_RESPONSE_INFO: 'phoneResponseInfo',\n PHONE_SESSION_INFO: 'phoneSessionInfo',\n POST_BODY: 'postBody',\n PROVIDER_ID: 'providerId',\n RECAPTCHA_SITE_KEY: 'recaptchaSiteKey',\n REQUEST_URI: 'requestUri',\n REFRESH_TOKEN: 'refreshToken',\n SESSION_ID: 'sessionId',\n SESSION_INFO: 'sessionInfo',\n SIGNIN_METHODS: 'signinMethods',\n TEMPORARY_PROOF: 'temporaryProof'\n};\n\n\n/**\n * Firebase Auth response injected fields.\n * @enum {string}\n */\nfireauth.RpcHandler.InjectedResponseField = {\n NONCE: 'nonce'\n};\n\n\n/**\n * Firebase Auth getOobConfirmationCode requestType possible values.\n * @enum {string}\n */\nfireauth.RpcHandler.GetOobCodeRequestType = {\n EMAIL_SIGNIN: 'EMAIL_SIGNIN',\n NEW_EMAIL_ACCEPT: 'NEW_EMAIL_ACCEPT',\n PASSWORD_RESET: 'PASSWORD_RESET',\n VERIFY_AND_CHANGE_EMAIL: 'VERIFY_AND_CHANGE_EMAIL',\n VERIFY_EMAIL: 'VERIFY_EMAIL'\n};\n\n\n/**\n * Firebase Auth response field names.\n * @enum {string}\n */\nfireauth.RpcHandler.StsServerField = {\n ACCESS_TOKEN: 'access_token',\n EXPIRES_IN: 'expires_in',\n REFRESH_TOKEN: 'refresh_token'\n};\n\n\n/**\n * @return {string} The API key.\n */\nfireauth.RpcHandler.prototype.getApiKey = function() {\n return this.apiKey_;\n};\n\n\n/**\n * The Firebase custom locale header.\n * @const {string}\n * @private\n */\nfireauth.RpcHandler.FIREBASE_LOCALE_KEY_ = 'X-Firebase-Locale';\n\n\n/**\n * The secure token endpoint.\n * @const {string}\n * @private\n */\nfireauth.RpcHandler.SECURE_TOKEN_ENDPOINT_ =\n 'https://securetoken.googleapis.com/v1/token';\n\n\n/**\n * The default timeout delay (units in milliseconds) for requests sending to\n * STS token endpoint.\n * @const {!fireauth.util.Delay}\n * @private\n */\nfireauth.RpcHandler.DEFAULT_SECURE_TOKEN_TIMEOUT_ =\n new fireauth.util.Delay(30000, 60000);\n\n\n/**\n * The STS token RPC content headers.\n * @const {!Object}\n * @private\n */\nfireauth.RpcHandler.DEFAULT_SECURE_TOKEN_HEADERS_ = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\n\n/**\n * The Firebase endpoint.\n * @const {string}\n * @private\n */\nfireauth.RpcHandler.FIREBASE_ENDPOINT_ =\n 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/';\n\n\n/**\n * The Identity Platform endpoint.\n * @const {string}\n * @private\n */\nfireauth.RpcHandler.IDENTITY_PLATFORM_ENDPOINT_ =\n 'https://identitytoolkit.googleapis.com/v2/';\n\n\n/**\n * The default timeout delay (units in milliseconds) for requests sending to\n * Firebase endpoint.\n * @const {!fireauth.util.Delay}\n * @private\n */\nfireauth.RpcHandler.DEFAULT_FIREBASE_TIMEOUT_ =\n new fireauth.util.Delay(30000, 60000);\n\n\n/**\n * The Firebase RPC content headers.\n * @const {!Object}\n * @private\n */\nfireauth.RpcHandler.DEFAULT_FIREBASE_HEADERS_ = {\n 'Content-Type': 'application/json'\n};\n\n\n/**\n * Updates the custom locale header.\n * @param {?string} languageCode The new languageCode.\n */\nfireauth.RpcHandler.prototype.updateCustomLocaleHeader =\n function(languageCode) {\n if (languageCode) {\n // If a language code is provided, add it to the header.\n this.firebaseHeaders_[fireauth.RpcHandler.FIREBASE_LOCALE_KEY_] =\n languageCode;\n } else {\n // Otherwise remove the custom locale header.\n delete this.firebaseHeaders_[fireauth.RpcHandler.FIREBASE_LOCALE_KEY_];\n }\n};\n\n\n/**\n * Updates the X-Client-Version in the header.\n * @param {?string} clientVersion The new client version.\n */\nfireauth.RpcHandler.prototype.updateClientVersion = function(clientVersion) {\n if (clientVersion) {\n // Update client version for Firebase Auth server.\n this.firebaseHeaders_['X-Client-Version'] = clientVersion;\n // Update client version for securetoken server.\n this.secureTokenHeaders_['X-Client-Version'] = clientVersion;\n } else {\n // Remove client version from header.\n delete this.firebaseHeaders_['X-Client-Version'];\n delete this.secureTokenHeaders_['X-Client-Version'];\n }\n};\n\n\n/**\n * Updates the tenant ID in the request.\n * @param {?string} tenantId The new tenant ID.\n */\nfireauth.RpcHandler.prototype.updateTenantId = function(tenantId) {\n this.tenantId_ = tenantId;\n};\n\n\n/**\n * Returns the tenant ID.\n * @return {?string} The tenant ID.\n */\nfireauth.RpcHandler.prototype.getTenantId = function() {\n return this.tenantId_;\n};\n\n\n/**\n * Sends XhrIo request using goog.net.XhrIo.\n * @param {string} url The URL to make a request to.\n * @param {function(?Object)=} opt_callback The callback to run on completion.\n * @param {fireauth.RpcHandler.HttpMethod=} opt_httpMethod The HTTP send method.\n * @param {?ArrayBuffer|?ArrayBufferView|?Blob|?Document|?FormData|string=}\n * opt_data The request content.\n * @param {?Object=} opt_headers The request content headers.\n * @param {number=} opt_timeout The request timeout.\n * @private\n */\nfireauth.RpcHandler.prototype.sendXhr_ = function(\n url,\n opt_callback,\n opt_httpMethod,\n opt_data,\n opt_headers,\n opt_timeout) {\n var sendXhr;\n if (fireauth.util.supportsCors() || fireauth.util.isWorker()) {\n // If supports CORS use goog.net.XhrIo.\n sendXhr = goog.bind(this.sendXhrUsingXhrIo_, this);\n } else {\n // Load gapi.client.request and gapi.auth dependency dynamically.\n if (!fireauth.RpcHandler.loadGApi_) {\n fireauth.RpcHandler.loadGApi_ =\n new goog.Promise(function(resolve, reject) {\n // On load, resolve.\n fireauth.RpcHandler.loadGApiJs_(resolve, reject);\n });\n }\n // If does not support CORS, use gapi.client.request.\n sendXhr = goog.bind(this.sendXhrUsingGApiClient_, this);\n }\n sendXhr(\n url, opt_callback, opt_httpMethod, opt_data, opt_headers, opt_timeout);\n};\n\n\n/**\n * Sends XhrIo request using goog.net.XhrIo.\n * @param {string} url The URL to make a request to.\n * @param {function(?Object)=} opt_callback The callback to run on completion.\n * @param {fireauth.RpcHandler.HttpMethod=} opt_httpMethod The HTTP send method.\n * @param {?ArrayBuffer|?ArrayBufferView|?Blob|?Document|?FormData|string=}\n * opt_data The request content.\n * @param {?Object=} opt_headers The request content headers.\n * @param {number=} opt_timeout The request timeout.\n * @private\n */\nfireauth.RpcHandler.prototype.sendXhrUsingXhrIo_ = function(\n url,\n opt_callback,\n opt_httpMethod,\n opt_data,\n opt_headers,\n opt_timeout) {\n if (fireauth.util.isWorker() && !fireauth.util.isFetchSupported()) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED,\n 'fetch, Headers and Request native APIs or equivalent Polyfills ' +\n 'must be available to support HTTP requests from a Worker ' +\n 'environment.');\n }\n var xhrIo = new goog.net.XhrIo(this.rpcHandlerXhrFactory_);\n\n // xhrIo.setTimeoutInterval not working in IE10 and IE11, handle manually.\n var requestTimeout;\n if (opt_timeout) {\n xhrIo.setTimeoutInterval(opt_timeout);\n requestTimeout = setTimeout(function() {\n xhrIo.dispatchEvent(goog.net.EventType.TIMEOUT);\n }, opt_timeout);\n }\n // Run callback function on completion.\n xhrIo.listen(\n goog.net.EventType.COMPLETE,\n /** @this {goog.net.XhrIo} */\n function() {\n // Clear timeout timer.\n if (requestTimeout) {\n clearTimeout(requestTimeout);\n }\n // Response assumed to be in json format. If not, catch, log error and\n // pass null to callback.\n var response = null;\n try {\n // Do not use this.responseJson() as it uses goog.json.parse\n // underneath. Internal goog.json.parse parsing uses eval and since\n // recommended Content Security Policy does not allow unsafe-eval,\n // this is failing and throwing an error in chrome extensions and\n // warnings else where. Use native parsing instead via JSON.parse.\n response = JSON.parse(this.getResponseText()) || null;\n } catch (e) {\n response = null;\n }\n if (opt_callback) {\n opt_callback(/** @type {?Object} */ (response));\n }\n });\n // Dispose xhrIo on ready.\n xhrIo.listenOnce(\n goog.net.EventType.READY,\n /** @this {goog.net.XhrIo} */\n function() {\n // Clear timeout timer.\n if (requestTimeout) {\n clearTimeout(requestTimeout);\n }\n // Dispose xhrIo.\n this.dispose();\n });\n // Listen to timeout error.\n // This should work when request is aborted too.\n xhrIo.listenOnce(\n goog.net.EventType.TIMEOUT,\n /** @this {goog.net.XhrIo} */\n function() {\n // Clear timeout timer.\n if (requestTimeout) {\n clearTimeout(requestTimeout);\n }\n // Dispose xhrIo.\n this.dispose();\n // The request timed out.\n if (opt_callback) {\n opt_callback(null);\n }\n });\n xhrIo.send(url, opt_httpMethod, opt_data, opt_headers);\n};\n\n\n/**\n * @const {!goog.string.Const} The GApi client library URL.\n * @private\n */\nfireauth.RpcHandler.GAPI_SRC_ = goog.string.Const.from(\n 'https://apis.google.com/js/client.js?onload=%{onload}');\n\n\n/**\n * @const {string}\n * @private\n */\nfireauth.RpcHandler.GAPI_CALLBACK_NAME_ =\n '__fcb' + Math.floor(Math.random() * 1000000).toString();\n\n\n/**\n * Loads the GApi client library if it is not loaded.\n * @param {function()} callback The callback to invoke once it's loaded.\n * @param {function(?Object)} errback The error callback.\n * @private\n */\nfireauth.RpcHandler.loadGApiJs_ = function(callback, errback) {\n // If gapi.client.request not available, load it dynamically.\n if (!((window['gapi'] || {})['client'] || {})['request']) {\n goog.global[fireauth.RpcHandler.GAPI_CALLBACK_NAME_] = function() {\n // Callback will be called by GApi, test properly loaded here instead of\n // after jsloader resolves.\n if (!((window['gapi'] || {})['client'] || {})['request']) {\n errback(new Error(fireauth.RpcHandler.ServerError.CORS_UNSUPPORTED));\n } else {\n callback();\n }\n };\n var url = goog.html.TrustedResourceUrl.format(\n fireauth.RpcHandler.GAPI_SRC_,\n {'onload': fireauth.RpcHandler.GAPI_CALLBACK_NAME_});\n // TODO: replace goog.net.jsloader with our own script includer.\n var result = goog.net.jsloader.safeLoad(url);\n result.addErrback(function() {\n // In case file fails to load.\n errback(new Error(fireauth.RpcHandler.ServerError.CORS_UNSUPPORTED));\n });\n } else {\n callback();\n }\n};\n\n\n/**\n * Sends XhrIo request using gapi.client.\n * @param {string} url The URL to make a request to.\n * @param {function(?Object)=} opt_callback The callback to run on completion.\n * @param {fireauth.RpcHandler.HttpMethod=} opt_httpMethod The HTTP send method.\n * @param {?ArrayBuffer|?ArrayBufferView|?Blob|?Document|?FormData|string=}\n * opt_data The request content.\n * @param {?Object=} opt_headers The request content headers.\n * @param {number=} opt_timeout The request timeout.\n * @private\n */\nfireauth.RpcHandler.prototype.sendXhrUsingGApiClient_ = function(\n url,\n opt_callback,\n opt_httpMethod,\n opt_data,\n opt_headers,\n opt_timeout) {\n var self = this;\n // Wait for GApi dependency to load.\n fireauth.RpcHandler.loadGApi_.then(function() {\n window['gapi']['client']['setApiKey'](self.getApiKey());\n // GApi maintains the Auth result and automatically append the Auth token to\n // all outgoing requests. Firebase Auth requests will be rejected if there\n // are others scopes (e.g. google plus) for the Auth token. Need to empty\n // the token before call gitkit api. Restored in callback.\n var oauth2Token = window['gapi']['auth']['getToken']();\n window['gapi']['auth']['setToken'](null);\n window['gapi']['client']['request']({\n 'path': url,\n 'method': opt_httpMethod,\n 'body': opt_data,\n 'headers': opt_headers,\n // This needs to be set to none, otherwise the access token will be passed\n // in the header field causing apiary to complain.\n 'authType': 'none',\n 'callback': function(response) {\n window['gapi']['auth']['setToken'](oauth2Token);\n if (opt_callback) {\n opt_callback(response);\n }\n }\n });\n }).thenCatch(function(error) {\n // Catches failure to support CORS and propagates it.\n if (opt_callback) {\n // Simulate backend server error to be caught by upper layer.\n opt_callback({\n 'error': {\n 'message': (error && error['message']) ||\n fireauth.RpcHandler.ServerError.CORS_UNSUPPORTED\n }\n });\n }\n });\n};\n\n\n/**\n * Validates the request for the STS access token.\n *\n * @param {?Object} data The STS token request body.\n * @return {boolean} Whether the request is valid.\n * @private\n */\nfireauth.RpcHandler.prototype.validateStsTokenRequest_ = function(data) {\n if (data['grant_type'] == 'refresh_token' && data['refresh_token']) {\n // Exchange refresh token.\n return true;\n } else if (data['grant_type'] == 'authorization_code' && data['code']) {\n // Exchange ID token.\n return true;\n } else {\n // Invalid.\n return false;\n }\n};\n\n\n/**\n * Handles the request for the STS access token.\n *\n * @param {!Object} data The STS token request body.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.requestStsToken = function(data) {\n var self = this;\n return new goog.Promise(function(resolve, reject) {\n if (self.validateStsTokenRequest_(data)) {\n self.sendXhr_(\n self.secureTokenEndpoint_ + '?key=' +\n encodeURIComponent(self.getApiKey()),\n function(response) {\n if (!response) {\n // An unparseable response from the XHR most likely indicates some\n // problem with the network.\n reject(new fireauth.AuthError(\n fireauth.authenum.Error.NETWORK_REQUEST_FAILED));\n } else if (fireauth.RpcHandler.hasError_(response)) {\n reject(fireauth.RpcHandler.getDeveloperError_(response));\n } else if (\n !response[fireauth.RpcHandler.StsServerField.ACCESS_TOKEN] ||\n !response[fireauth.RpcHandler.StsServerField.REFRESH_TOKEN]) {\n reject(new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR));\n } else {\n resolve(response);\n }\n },\n fireauth.RpcHandler.HttpMethod.POST,\n goog.Uri.QueryData.createFromMap(data).toString(),\n self.secureTokenHeaders_,\n self.secureTokenTimeout_.get());\n } else {\n reject(new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR));\n }\n });\n};\n\n\n/**\n * @param {!Object} data The object to serialize.\n * @return {string} The serialized object with null, undefined and empty string\n * values removed.\n * @private\n */\nfireauth.RpcHandler.serialize_ = function(data) {\n // goog.json.serialize converts undefined values to null.\n // This helper removes all empty strings, nulls and undefined from serialized\n // object.\n // Serialize trimmed data.\n return goog.json.serialize(fireauth.util.copyWithoutNullsOrUndefined(data));\n};\n\n\n/**\n * Creates and executes a request for the given API method using the legacy\n * Firebase Auth endpoint.\n * @param {string} method The API method.\n * @param {!fireauth.RpcHandler.HttpMethod} httpMethod The http request method.\n * @param {!Object} data The data for the API request. In the case of a GET\n * request, the contents of this object will be form encoded and appended\n * to the query string of the URL. No post body is sent in that case. If an\n * object value is specified, it will be converted to a string:\n * encodeURIComponent(String(value)).\n * @param {?fireauth.RpcHandler.ServerErrorMap=} opt_customErrorMap A map\n * of server error codes to client errors to override default error\n * handling.\n * @param {boolean=} opt_cachebuster Whether to append a unique string to\n * request to force backend to return an uncached response to request.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.requestFirebaseEndpoint = function(\n method, httpMethod, data, opt_customErrorMap, opt_cachebuster) {\n return this.requestAuthEndpoint_(\n this.firebaseEndpoint_, method, httpMethod, data, opt_customErrorMap,\n opt_cachebuster);\n};\n\n\n/**\n * Creates and executes a request for the given API method using the identity\n * platform endpoint.\n * @param {string} method The API method.\n * @param {!fireauth.RpcHandler.HttpMethod} httpMethod The http request method.\n * @param {!Object} data The data for the API request. In the case of a GET\n * request, the contents of this object will be form encoded and appended\n * to the query string of the URL. No post body is sent in that case. If an\n * object value is specified, it will be converted to a string:\n * encodeURIComponent(String(value)).\n * @param {?fireauth.RpcHandler.ServerErrorMap=} opt_customErrorMap A map\n * of server error codes to client errors to override default error\n * handling.\n * @param {boolean=} opt_cachebuster Whether to append a unique string to\n * request to force backend to return an uncached response to request.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.requestIdentityPlatformEndpoint = function(\n method, httpMethod, data, opt_customErrorMap, opt_cachebuster) {\n return this.requestAuthEndpoint_(\n this.identityPlatformEndpoint_, method, httpMethod, data,\n opt_customErrorMap, opt_cachebuster);\n};\n\n\n/**\n * Creates and executes a request for the given API method and Auth endpoint.\n * @param {string} endpoint The Auth endpoint to use.\n * @param {string} method The API method.\n * @param {!fireauth.RpcHandler.HttpMethod} httpMethod The http request method.\n * @param {!Object} data The data for the API request. In the case of a GET\n * request, the contents of this object will be form encoded and appended\n * to the query string of the URL. No post body is sent in that case. If an\n * object value is specified, it will be converted to a string:\n * encodeURIComponent(String(value)).\n * @param {?fireauth.RpcHandler.ServerErrorMap=} opt_customErrorMap A map\n * of server error codes to client errors to override default error\n * handling.\n * @param {boolean=} opt_cachebuster Whether to append a unique string to\n * request to force backend to return an uncached response to request.\n * @return {!goog.Promise<!Object>}\n * @private\n */\nfireauth.RpcHandler.prototype.requestAuthEndpoint_ = function(\n endpoint, method, httpMethod, data, opt_customErrorMap, opt_cachebuster) {\n var self = this;\n // Construct endpoint URL.\n var uri = goog.Uri.parse(endpoint + method);\n uri.setParameterValue('key', this.getApiKey());\n // Check whether to append cachebuster to request.\n if (opt_cachebuster) {\n uri.setParameterValue('cb', goog.now().toString());\n }\n // Firebase allows GET endpoints.\n var isGet = httpMethod == fireauth.RpcHandler.HttpMethod.GET;\n if (isGet) {\n // For GET HTTP method, append data to query string.\n for (var key in data) {\n if (data.hasOwnProperty(key)) {\n uri.setParameterValue(key, data[key]);\n }\n }\n }\n return new goog.Promise(function(resolve, reject) {\n self.sendXhr_(\n uri.toString(),\n function(response) {\n if (!response) {\n // An unparseable response from the XHR most likely indicates some\n // problem with the network.\n reject(new fireauth.AuthError(\n fireauth.authenum.Error.NETWORK_REQUEST_FAILED));\n } else if (fireauth.RpcHandler.hasError_(response)) {\n reject(fireauth.RpcHandler.getDeveloperError_(response,\n opt_customErrorMap || {}));\n } else {\n resolve(response);\n }\n },\n httpMethod,\n // No post body data in GET requests.\n isGet ? undefined : fireauth.RpcHandler.serialize_(data),\n self.firebaseHeaders_,\n self.firebaseTimeout_.get());\n });\n};\n\n\n/**\n * Verifies that the request has a valid email set.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateRequestHasEmail_ = function(request) {\n if (!fireauth.util.isValidEmailAddress(request['email'])) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_EMAIL);\n }\n};\n\n\n/**\n * Verifies that the response has a valid email set.\n * @param {!Object} response\n * @private\n */\nfireauth.RpcHandler.validateResponseHasEmail_ = function(response) {\n if (!fireauth.util.isValidEmailAddress(response['email'])) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Verifies that the an email is valid, if it is there.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateEmailIfPresent_ = function(request) {\n if ('email' in request) {\n fireauth.RpcHandler.validateRequestHasEmail_(request);\n }\n};\n\n\n/**\n * @param {string} providerId The provider ID.\n * @param {?Array<string>=} opt_additionalScopes The list of scope strings.\n * @return {?string} The IDP and its comma separated scope strings serialized.\n * @private\n */\nfireauth.RpcHandler.getAdditionalScopes_ =\n function(providerId, opt_additionalScopes) {\n var scopes = {};\n if (opt_additionalScopes && opt_additionalScopes.length) {\n scopes[providerId] = opt_additionalScopes.join(',');\n // Return stringified scopes.\n return goog.json.serialize(scopes);\n }\n return null;\n};\n\n\n/**\n * Validates a response from getAuthUri.\n * @param {?Object} response The getAuthUri response data.\n * @private\n */\nfireauth.RpcHandler.validateGetAuthResponse_ = function(response) {\n if (!response[fireauth.RpcHandler.AuthServerField.AUTH_URI]) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'Unable to determine the authorization endpoint for the specified '+\n 'provider. This may be an issue in the provider configuration.');\n } else if ( !response[fireauth.RpcHandler.AuthServerField.SESSION_ID]) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Requests createAuthUri endpoint to retrieve the authUri and session ID for\n * the start of an OAuth handshake.\n * @param {string} providerId The provider ID.\n * @param {string} continueUri The IdP callback URL.\n * @param {?Object=} opt_customParameters The optional OAuth custom parameters\n * plain object.\n * @param {?Array<string>=} opt_additionalScopes The list of scope strings.\n * @param {?string=} opt_email The optional email.\n * @param {?string=} opt_sessionId The optional session ID.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.getAuthUri = function(\n providerId,\n continueUri,\n opt_customParameters,\n opt_additionalScopes,\n opt_email,\n opt_sessionId) {\n // SAML provider request is constructed differently than OAuth requests.\n var isSaml = fireauth.idp.isSaml(providerId);\n var request = {\n 'identifier': opt_email,\n 'providerId': providerId,\n 'continueUri': continueUri,\n 'customParameter': opt_customParameters || {},\n 'oauthScope': fireauth.RpcHandler.getAdditionalScopes_(\n providerId, opt_additionalScopes),\n 'sessionId': opt_sessionId\n };\n // Custom parameters and OAuth scopes should be ignored.\n if (isSaml) {\n delete request['customParameter'];\n delete request['oauthScope'];\n }\n // When sessionId is provided, mobile flow (Cordova) is being used, force\n // code flow and not implicit flow. All other providers use code flow by\n // default.\n if (opt_sessionId && providerId == fireauth.idp.ProviderId.GOOGLE) {\n request['authFlowType'] = 'CODE_FLOW';\n }\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.GET_AUTH_URI,\n request);\n};\n\n\n/**\n * Gets the list of IDPs that can be used to log in for the given identifier.\n * @param {string} identifier The identifier, such as an email address.\n * @return {!goog.Promise<!Array<string>>}\n */\nfireauth.RpcHandler.prototype.fetchProvidersForIdentifier =\n function(identifier) {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n var continueUri = fireauth.util.isHttpOrHttps() ?\n fireauth.util.getCurrentUrl() : 'http://localhost';\n var request = {\n 'identifier': identifier,\n 'continueUri': continueUri\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.CREATE_AUTH_URI, request)\n .then(function(response) {\n return response[fireauth.RpcHandler.AuthServerField.ALL_PROVIDERS] ||\n [];\n });\n};\n\n\n/**\n * Returns the list of sign in methods for the given identifier.\n * @param {string} identifier The identifier, such as an email address.\n * @return {!goog.Promise<!Array<string>>}\n */\nfireauth.RpcHandler.prototype.fetchSignInMethodsForIdentifier = function(\n identifier) {\n // createAuthUri returns an error if continue URI is not http or https.\n // For environments like Cordova, Chrome extensions, native frameworks, file\n // systems, etc, use http://localhost as continue URL.\n var continueUri = fireauth.util.isHttpOrHttps() ?\n fireauth.util.getCurrentUrl() :\n 'http://localhost';\n var request = {\n 'identifier': identifier,\n 'continueUri': continueUri\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.CREATE_AUTH_URI, request)\n .then(function(response) {\n return response[fireauth.RpcHandler.AuthServerField.SIGNIN_METHODS] ||\n [];\n });\n};\n\n\n/**\n * Gets the list of authorized domains for the specified project.\n * @return {!goog.Promise<!Array<string>>}\n */\nfireauth.RpcHandler.prototype.getAuthorizedDomains = function() {\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.GET_PROJECT_CONFIG, {})\n .then(function(response) {\n return response[\n fireauth.RpcHandler.AuthServerField.AUTHORIZED_DOMAINS] || [];\n });\n};\n\n\n/**\n * Gets the reCAPTCHA parameters needed to render the project's provisioned\n * reCAPTCHA.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.getRecaptchaParam = function() {\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.GET_RECAPTCHA_PARAM, {});\n};\n\n\n/**\n * Gets the list of authorized domains for the specified project.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.getDynamicLinkDomain = function() {\n var request = {\n 'returnDynamicLink': true\n };\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.RETURN_DYNAMIC_LINK, request);\n};\n\n\n/**\n * Checks if the provided iOS bundle ID belongs to the project as specified by\n * the API key.\n * @param {string} iosBundleId The iOS bundle ID to check.\n * @return {!goog.Promise<void>}\n */\nfireauth.RpcHandler.prototype.isIosBundleIdValid = function(iosBundleId) {\n var request = {\n 'iosBundleId': iosBundleId\n };\n // This will either resolve if the identifier is valid or throw INVALID_APP_ID\n // if not.\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.GET_PROJECT_CONFIG, request)\n .then(function(result) {\n // Do not return anything.\n });\n};\n\n\n/**\n * Checks if the provided Android package name belongs to the project as\n * specified by the API key.\n * @param {string} androidPackageName The iOS bundle ID to check.\n * @param {?string=} opt_sha1Cert The optional SHA-1 Android cert to check.\n * @return {!goog.Promise<void>}\n */\nfireauth.RpcHandler.prototype.isAndroidPackageNameValid =\n function(androidPackageName, opt_sha1Cert) {\n var request = {\n 'androidPackageName': androidPackageName\n };\n // This is relevant for the native Android SDK flow.\n // This will redirect to an FDL domain owned by GMScore instead of\n // the developer's FDL domain as is done for Cordova apps.\n if (!!opt_sha1Cert) {\n request['sha1Cert'] = opt_sha1Cert;\n }\n // When no sha1Cert is passed, this will either resolve if the identifier is\n // valid or throw INVALID_APP_ID if not.\n // When sha1Cert is also passed, this will either resolve or fail with an\n // INVALID_CERT_HASH error.\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.GET_PROJECT_CONFIG, request)\n .then(function(result) {\n // Do not return anything.\n });\n};\n\n\n/**\n * Checks if the provided OAuth client ID belongs to the project as specified by\n * the API key.\n * @param {string} clientId The OAuth client ID to check.\n * @return {!goog.Promise<void>}\n */\nfireauth.RpcHandler.prototype.isOAuthClientIdValid = function(clientId) {\n var request = {\n 'clientId': clientId\n };\n // This will either resolve if the client ID is valid or throw\n // INVALID_OAUTH_CLIENT_ID if not.\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.GET_PROJECT_CONFIG, request)\n .then(function(result) {\n // Do not return anything.\n });\n};\n\n\n/**\n * Requests getAccountInfo endpoint using an ID token.\n * @param {string} idToken The ID token.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.getAccountInfoByIdToken = function(idToken) {\n var request = {'idToken': idToken};\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.GET_ACCOUNT_INFO,\n request);\n};\n\n\n/**\n * Validates a request to sign in with email and password.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateVerifyCustomTokenRequest_ = function(request) {\n if (!request['token']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_CUSTOM_TOKEN);\n }\n};\n\n\n/**\n * Verifies a custom token and returns a Promise that resolves with the ID\n * token.\n * @param {string} token The custom token.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyCustomToken = function(token) {\n var request = {'token': token};\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.VERIFY_CUSTOM_TOKEN,\n request);\n};\n\n\n/**\n * Validates a request to sign in with email and password.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateVerifyPasswordRequest_ = function(request) {\n fireauth.RpcHandler.validateRequestHasEmail_(request);\n if (!request['password']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_PASSWORD);\n }\n};\n\n\n/**\n * Verifies a password and returns a Promise that resolves with the ID\n * token.\n * @param {string} email The email address.\n * @param {string} password The entered password.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyPassword = function(email, password) {\n var request = {\n 'email': email,\n 'password': password\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.VERIFY_PASSWORD,\n request);\n};\n\n\n/**\n * Verifies an email link OTP for sign-in and returns a Promise that resolves\n * with the ID token.\n * @param {string} email The email address.\n * @param {string} oobCode The email action OTP.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.emailLinkSignIn = function(email, oobCode) {\n var request = {\n 'email': email,\n 'oobCode': oobCode\n };\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.EMAIL_LINK_SIGNIN, request);\n};\n\n\n/**\n * Verifies an email link OTP for linking and returns a Promise that resolves\n * with the ID token.\n * @param {string} idToken The ID token.\n * @param {string} email The email address.\n * @param {string} oobCode The email action OTP.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.emailLinkSignInForLinking =\n function(idToken, email, oobCode) {\n var request = {\n 'idToken': idToken,\n 'email': email,\n 'oobCode': oobCode\n };\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.EMAIL_LINK_SIGNIN_FOR_LINKING,\n request);\n};\n\n\n/**\n * Validates a response that should contain an ID token.\n * If no ID token is available, it checks if a multi-factor pending credential\n * is available instead. In that case, it throws the MFA_REQUIRED error code.\n * @param {?Object} response The server response data.\n * @private\n */\nfireauth.RpcHandler.validateIdTokenResponse_ = function(response) {\n if (!response[fireauth.RpcHandler.AuthServerField.ID_TOKEN]) {\n // User could be a second factor user.\n // When second factor is required, a pending credential is returned.\n if (response[fireauth.RpcHandler.AuthServerField.MFA_PENDING_CREDENTIAL]) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.MFA_REQUIRED,\n null,\n goog.object.clone(response));\n }\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Validates a getRecaptchaParam response.\n * @param {?Object} response The server response data.\n * @private\n */\nfireauth.RpcHandler.validateGetRecaptchaParamResponse_ = function(response) {\n // Both are required. This could change though.\n if (!response[fireauth.RpcHandler.AuthServerField.RECAPTCHA_SITE_KEY]) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Validates a request that sends the verification ID and code for a sign in/up\n * phone Auth flow.\n * @param {!Object} request The server request object.\n * @private\n */\nfireauth.RpcHandler.validateVerifyPhoneNumberRequest_ = function(request) {\n // There are 2 cases here:\n // case 1: sessionInfo and code\n // case 2: phoneNumber and temporaryProof\n if (request['phoneNumber'] || request['temporaryProof']) {\n // Case 2. Both phoneNumber and temporaryProof should be set.\n if (!request['phoneNumber'] || !request['temporaryProof']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n } else {\n // Otherwise it's case 1, so we expect sessionInfo and code.\n if (!request['sessionInfo']) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.MISSING_SESSION_INFO);\n }\n if (!request['code']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_CODE);\n }\n }\n};\n\n\n/**\n * Validates a request that sends the verification ID and code for a link/update\n * phone Auth flow.\n * @param {!Object} request The server request object.\n * @private\n */\nfireauth.RpcHandler.validateVerifyPhoneNumberLinkRequest_ = function(request) {\n // idToken should be required here.\n if (!request['idToken']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n // The other request parameters match the sign in flow.\n fireauth.RpcHandler.validateVerifyPhoneNumberRequest_(request);\n};\n\n\n/**\n * Validates a request to create an email and password account.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateCreateAccountRequest_ = function(request) {\n fireauth.RpcHandler.validateRequestHasEmail_(request);\n if (!request['password']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.WEAK_PASSWORD);\n }\n};\n\n\n/**\n * Validates a request to createAuthUri.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateGetAuthUriRequest_ = function(request) {\n if (!request['continueUri']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_CONTINUE_URI);\n }\n // Either a SAML or non SAML providerId must be provided.\n if (!request['providerId']) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'A provider ID must be provided in the request.');\n }\n};\n\n\n/**\n * Creates an email/password account. Returns a Promise that resolves with the\n * ID token.\n * @param {string} email The email address of the account.\n * @param {string} password The password.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.createAccount = function(email, password) {\n var request = {\n 'email': email,\n 'password': password\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.CREATE_ACCOUNT,\n request);\n};\n\n\n/**\n * Signs in a user as anonymous. Returns a Promise that resolves with the\n * ID token.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.signInAnonymously = function() {\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.SIGN_IN_ANONYMOUSLY, {});\n};\n\n\n/**\n * Deletes the user's account corresponding to the idToken given.\n * @param {string} idToken The idToken of the user.\n * @return {!goog.Promise<undefined>}\n */\nfireauth.RpcHandler.prototype.deleteAccount = function(idToken) {\n var request = {\n 'idToken': idToken\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.DELETE_ACCOUNT,\n request);\n};\n\n\n/**\n * Requests setAccountInfo endpoint for updateEmail operation.\n * @param {string} idToken The ID token.\n * @param {string} newEmail The new email.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.updateEmail = function(idToken, newEmail) {\n var request = {\n 'idToken': idToken,\n 'email': newEmail\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.SET_ACCOUNT_INFO,\n request);\n};\n\n\n/**\n * Validates a setAccountInfo request that updates the password.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateSetAccountInfoSensitive_ = function(request) {\n fireauth.RpcHandler.validateEmailIfPresent_(request);\n if (!request['password']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.WEAK_PASSWORD);\n }\n};\n\n\n/**\n * Requests setAccountInfo endpoint for updatePassword operation.\n * @param {string} idToken The ID token.\n * @param {string} newPassword The new password.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.updatePassword = function(idToken, newPassword) {\n var request = {\n 'idToken': idToken,\n 'password': newPassword\n };\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.SET_ACCOUNT_INFO_SENSITIVE, request);\n};\n\n\n/**\n * Requests setAccountInfo endpoint to set the email and password. This can be\n * used to link an existing account to a new email and password account.\n * @param {string} idToken The ID token.\n * @param {string} newEmail The new email.\n * @param {string} newPassword The new password.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.updateEmailAndPassword = function(idToken,\n newEmail, newPassword) {\n var request = {\n 'idToken': idToken,\n 'email': newEmail,\n 'password': newPassword\n };\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.SET_ACCOUNT_INFO_SENSITIVE, request);\n};\n\n\n/**\n * Maps the name of a field in the account info object to the backend enum\n * value, for deletion of profile fields.\n * @private {!Object<string, string>}\n */\nfireauth.RpcHandler.PROFILE_FIELD_TO_ENUM_NAME_ = {\n 'displayName': 'DISPLAY_NAME',\n 'photoUrl': 'PHOTO_URL'\n};\n\n\n/**\n * Updates the profile of the user. When resolved, promise returns a response\n * similar to that of getAccountInfo.\n * @param {string} idToken The ID token of the user whose profile is changing.\n * @param {!Object} profileData The new profile data.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.updateProfile = function(idToken, profileData) {\n var data = {\n 'idToken': idToken\n };\n var fieldsToDelete = [];\n\n // Copy over the relevant fields from profileData, or explicitly flag a field\n // for deletion if null is passed as the value. Note that this currently only\n // checks profileData to the first level.\n goog.object.forEach(fireauth.RpcHandler.PROFILE_FIELD_TO_ENUM_NAME_,\n function(enumName, fieldName) {\n var fieldValue = profileData[fieldName];\n if (fieldValue === null) {\n // If null is explicitly provided, delete the field.\n fieldsToDelete.push(enumName);\n } else if (fieldName in profileData) {\n // If the field is explicitly set, send it to the backend.\n data[fieldName] = fieldValue;\n }\n });\n if (fieldsToDelete.length) {\n data['deleteAttribute'] = fieldsToDelete;\n }\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.SET_ACCOUNT_INFO, data);\n};\n\n\n/**\n * Validates a request for an email action code for password reset.\n * @param {!Object} request The getOobCode request data for password reset.\n * @private\n */\nfireauth.RpcHandler.validateOobCodeRequest_ = function(request) {\n if (request['requestType'] !=\n fireauth.RpcHandler.GetOobCodeRequestType.PASSWORD_RESET) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n fireauth.RpcHandler.validateRequestHasEmail_(request);\n};\n\n\n/**\n * Validates a request for an email action for passwordless email sign-in.\n * @param {!Object} request The getOobCode request data for email sign-in.\n * @private\n */\nfireauth.RpcHandler.validateEmailSignInCodeRequest_ = function(request) {\n if (request['requestType'] !=\n fireauth.RpcHandler.GetOobCodeRequestType.EMAIL_SIGNIN) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n fireauth.RpcHandler.validateRequestHasEmail_(request);\n};\n\n\n/**\n * Validates a request for an email action for email verification.\n * @param {!Object} request The getOobCode request data for email verification.\n * @private\n */\nfireauth.RpcHandler.validateEmailVerificationCodeRequest_ = function(request) {\n if (request['requestType'] !=\n fireauth.RpcHandler.GetOobCodeRequestType.VERIFY_EMAIL) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Validates a request for an email action for email verification before update.\n * @param {!Object} request The getOobCode request data for email verification\n * before update.\n * @private\n */\nfireauth.RpcHandler.validateEmailVerificationCodeBeforeUpdateRequest_ =\n function(request) {\n if (request['requestType'] !=\n fireauth.RpcHandler.GetOobCodeRequestType.VERIFY_AND_CHANGE_EMAIL) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Requests getOobCode endpoint for password reset, returns promise that\n * resolves with user's email.\n * @param {string} email The email account with the password to be reset.\n * @param {!Object} additionalRequestData Additional data to add to the request.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.sendPasswordResetEmail =\n function(email, additionalRequestData) {\n var request = {\n 'requestType': fireauth.RpcHandler.GetOobCodeRequestType.PASSWORD_RESET,\n 'email': email\n };\n // Extend the original request with the additional data.\n goog.object.extend(request, additionalRequestData);\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.GET_OOB_CODE, request);\n};\n\n\n/**\n * Requests getOobCode endpoint for passwordless email sign-in, returns promise\n * that resolves with user's email.\n * @param {string} email The email account to sign in with.\n * @param {!Object} additionalRequestData Additional data to add to the request.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.sendSignInLinkToEmail = function(\n email, additionalRequestData) {\n var request = {\n 'requestType': fireauth.RpcHandler.GetOobCodeRequestType.EMAIL_SIGNIN,\n 'email': email\n };\n // Extend the original request with the additional data.\n goog.object.extend(request, additionalRequestData);\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.GET_EMAIL_SIGNIN_CODE, request);\n};\n\n\n/**\n * Requests getOobCode endpoint for email verification, returns promise that\n * resolves with user's email.\n * @param {string} idToken The idToken of the user confirming his email.\n * @param {!Object} additionalRequestData Additional data to add to the request.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.sendEmailVerification =\n function(idToken, additionalRequestData) {\n var request = {\n 'requestType': fireauth.RpcHandler.GetOobCodeRequestType.VERIFY_EMAIL,\n 'idToken': idToken\n };\n // Extend the original request with the additional data.\n goog.object.extend(request, additionalRequestData);\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.GET_EMAIL_VERIFICATION_CODE, request);\n};\n\n\n/**\n * Requests getOobCode endpoint for email verification before updating the\n * email.\n * @param {string} idToken The idToken of the user updating his email.\n * @param {string} newEmail The new email.\n * @param {!Object} additionalRequestData Additional data to add to the request.\n * @return {!goog.Promise<void>}\n */\nfireauth.RpcHandler.prototype.verifyBeforeUpdateEmail =\n function(idToken, newEmail, additionalRequestData) {\n var request = {\n 'requestType':\n fireauth.RpcHandler.GetOobCodeRequestType.VERIFY_AND_CHANGE_EMAIL,\n 'idToken': idToken,\n 'newEmail': newEmail\n };\n // Extend the original request with the additional data.\n goog.object.extend(request, additionalRequestData);\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.GET_EMAIL_VERIFICATION_CODE_BEFORE_UPDATE,\n request);\n};\n\n\n/**\n * Requests sendVerificationCode endpoint for verifying the user's ownership of\n * a phone number. It resolves with a sessionInfo (verificationId).\n * @param {!Object} request The verification request which contains a phone\n * number and an assertion.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.sendVerificationCode = function(request) {\n // In the future, we could support other types of assertions so for now,\n // we are keeping the request an object.\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.SEND_VERIFICATION_CODE, request);\n};\n\n\n/**\n * Requests verifyPhoneNumber endpoint for sign in/sign up phone number\n * authentication flow and resolves with the STS token response.\n * @param {!Object} request The phone number ID and code to exchange for a\n * Firebase Auth session.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyPhoneNumber = function(request) {\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.VERIFY_PHONE_NUMBER, request);\n};\n\n\n/**\n * Requests verifyPhoneNumber endpoint for link/update phone number\n * authentication flow and resolves with the STS token response.\n * @param {!Object} request The phone number ID and code to exchange for a\n * Firebase Auth session.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyPhoneNumberForLinking = function(request) {\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.VERIFY_PHONE_NUMBER_FOR_LINKING, request);\n};\n\n\n/**\n * Validates a response to a phone number linking request.\n * @param {?Object} response The server response data.\n * @private\n */\nfireauth.RpcHandler.validateVerifyPhoneNumberForLinkingResponse_ =\n function(response) {\n if (response[fireauth.RpcHandler.AuthServerField.TEMPORARY_PROOF]) {\n response['code'] = fireauth.authenum.Error.CREDENTIAL_ALREADY_IN_USE;\n throw fireauth.AuthErrorWithCredential.fromPlainObject(response);\n }\n\n // If there's no temporary proof, then we expect the request to have\n // succeeded and returned an ID token.\n fireauth.RpcHandler.validateIdTokenResponse_(response);\n};\n\n\n/**\n * Requests verifyPhoneNumber endpoint for reauthenticating with a phone number\n * and resolves with the STS token response.\n * @param {!Object} request The phone number ID, code, and current ID token to\n * exchange for a refreshed Firebase Auth session.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyPhoneNumberForExisting = function(request) {\n request['operation'] = 'REAUTH';\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.VERIFY_PHONE_NUMBER_FOR_EXISTING,\n request);\n};\n\n\n/**\n * Validates a request for starting phone MFA enrollment.\n * @param {!Object} request The startPhoneMfaEnrollment request data.\n * @private\n */\nfireauth.RpcHandler.validateStartPhoneMfaEnrollmentRequest_ =\n function(request) {\n if (!request['phoneEnrollmentInfo']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n if (!request['phoneEnrollmentInfo']['phoneNumber']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_PHONE_NUMBER);\n }\n if (!request['phoneEnrollmentInfo']['recaptchaToken']) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.MISSING_APP_CREDENTIAL);\n }\n};\n\n\n/**\n * Validates a response to a start phone MFA enrollment request.\n * @param {!Object} response The server response data.\n * @private\n */\nfireauth.RpcHandler.validateStartPhoneMfaEnrollmentResponse_ =\n function(response) {\n if (!response[fireauth.RpcHandler.AuthServerField.PHONE_SESSION_INFO] ||\n !response[fireauth.RpcHandler.AuthServerField.PHONE_SESSION_INFO]\n [fireauth.RpcHandler.AuthServerField.SESSION_INFO]) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Requests startMfaEnrollment endpoint for verifying the user's ownership of\n * a phone number before enrolling to MFA. It resolves with a sessionInfo\n * (verificationId) string.\n * @param {!Object} request The enroll MFA request for phone.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.startPhoneMfaEnrollment = function(request) {\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.START_PHONE_MFA_ENROLLMENT, request)\n .then(function(response) {\n // Extract the sessionInfo(verificationId) from response.\n return response[fireauth.RpcHandler.AuthServerField.PHONE_SESSION_INFO]\n [fireauth.RpcHandler.AuthServerField.SESSION_INFO];\n });\n};\n\n\n/**\n * Validates a request for finalizing phone MFA enrollment or sign-in.\n * @param {!Object} request The finalizePhoneMfaEnrollment or\n * finalizePhoneMfaSignIn request data.\n * @private\n */\nfireauth.RpcHandler.validateFinalizePhoneMfaRequest_ = function(request) {\n if (!request['phoneVerificationInfo']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n if (!request['phoneVerificationInfo']['sessionInfo']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_SESSION_INFO);\n }\n if (!request['phoneVerificationInfo']['code']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_CODE);\n }\n};\n\n\n/**\n * Requests finalizeMfaEnrollment endpoint to finish the enrollment flow for\n * phone MFA. It resolves with the MFA token response.\n * @param {!Object} request The enroll MFA request for phone.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.finalizePhoneMfaEnrollment = function(request) {\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.FINALIZE_PHONE_MFA_ENROLLMENT, request);\n};\n\n\n/**\n * Validates a request for starting phone MFA sign-in.\n * @param {!Object} request The startPhoneMfaSignIn request data.\n * @private\n */\nfireauth.RpcHandler.validateStartPhoneMfaSignInRequest_ = function(request) {\n if (!request['phoneSignInInfo'] ||\n !request['phoneSignInInfo']['recaptchaToken']) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.MISSING_APP_CREDENTIAL);\n }\n};\n\n\n/**\n * Validates a response to a start phone MFA sign-in request.\n * @param {!Object} response The server response data.\n * @private\n */\nfireauth.RpcHandler.validateStartPhoneMfaSignInResponse_ = function(response) {\n if (!response[fireauth.RpcHandler.AuthServerField.PHONE_RESPONSE_INFO] ||\n !response[fireauth.RpcHandler.AuthServerField.PHONE_RESPONSE_INFO]\n [fireauth.RpcHandler.AuthServerField.SESSION_INFO]) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Requests startMfaSignIn endpoint for verifying the user's ownership of\n * a phone number before signing in to MFA. It resolves with a sessionInfo\n * (verificationId) string.\n * @param {!Object} request The sign in MFA request for phone.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.startPhoneMfaSignIn = function(request) {\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.START_PHONE_MFA_SIGN_IN, request)\n .then(function(response) {\n // Extract the sessionInfo(verificationId) from response.\n return response[fireauth.RpcHandler.AuthServerField.PHONE_RESPONSE_INFO]\n [fireauth.RpcHandler.AuthServerField.SESSION_INFO];\n });\n};\n\n\n/**\n * Requests finalizeMfaSignIn endpoint to finish the sign-in flow for\n * phone MFA. It resolves with the MFA token response.\n * @param {!Object} request The sign in MFA request for phone.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.finalizePhoneMfaSignIn = function(request) {\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.FINALIZE_PHONE_MFA_SIGN_IN, request);\n};\n\n\n/**\n * Validates the response for unenrolling a second factor. If the user is still\n * considered signed in, the endpoint returns new tokens. However, if the\n * user session is revoked no tokens will be returned.\n * @param {!Object} response The server response data.\n * @private\n */\nfireauth.RpcHandler.validateWithdrawMfaResponse_ = function(response) {\n var hasIdToken = !!response[fireauth.RpcHandler.AuthServerField.ID_TOKEN];\n var hasRefreshToken =\n !!response[fireauth.RpcHandler.AuthServerField.REFRESH_TOKEN];\n\n if (hasIdToken ^ hasRefreshToken) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Requests the withdraw endpoint to unenroll a second factor. Returns new\n * tokens if the user is still considered signed in or no tokens if the user\n * session is revoked and the user is being signed out.\n * @param {string} idToken The ID token.\n * @param {string} mfaEnrollmentId The MFA enrollment ID.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.withdrawMfa = function(idToken, mfaEnrollmentId) {\n var request = {\n 'idToken': idToken,\n 'mfaEnrollmentId': mfaEnrollmentId\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.WITHDRAW_MFA, request);\n};\n\n\n/**\n * The custom error map for reauth with verifyPhoneNumber.\n * @private {!fireauth.RpcHandler.ServerErrorMap}\n */\nfireauth.RpcHandler.verifyPhoneNumberForExistingErrorMap_ = {};\n\n// For most RPCs, the backend error USER_NOT_FOUND means that the sent STS\n// token is invalid. However, for this specific case, USER_NOT_FOUND actually\n// means that the sent credential is invalid.\nfireauth.RpcHandler.verifyPhoneNumberForExistingErrorMap_[\n fireauth.RpcHandler.ServerError.USER_NOT_FOUND] =\n fireauth.authenum.Error.USER_DELETED;\n\n\n/**\n * Validates a request to deleteLinkedAccounts.\n * @param {?Object} request\n * @private\n */\nfireauth.RpcHandler.validateDeleteLinkedAccountsRequest_ = function(request) {\n if (!goog.isArray(request['deleteProvider'])) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Updates the providers for the account associated with the idToken.\n * @param {string} idToken The ID token.\n * @param {!Array<string>} providersToDelete The array of providers to delete.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.deleteLinkedAccounts =\n function(idToken, providersToDelete) {\n var request = {\n 'idToken': idToken,\n 'deleteProvider': providersToDelete\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.DELETE_LINKED_ACCOUNTS,\n request);\n};\n\n\n/**\n * Validates a verifyAssertion request.\n * @param {?Object} request The verifyAssertion request data.\n * @private\n */\nfireauth.RpcHandler.validateVerifyAssertionRequest_ = function(request) {\n // Either (requestUri and sessionId), (requestUri and postBody) or\n // (requestUri and pendingToken) are required.\n if (!request[fireauth.RpcHandler.AuthServerField.REQUEST_URI] ||\n (!request[fireauth.RpcHandler.AuthServerField.SESSION_ID] &&\n !request[fireauth.RpcHandler.AuthServerField.POST_BODY] &&\n !request[fireauth.RpcHandler.AuthServerField.PENDING_TOKEN])) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Processes the verifyAssertion response and injects the same raw nonce\n * if available in request.\n * @param {!Object} request The verifyAssertion request data.\n * @param {!Object} response The original verifyAssertion response data.\n * @return {!Object} The modified verifyAssertion response.\n * @private\n */\nfireauth.RpcHandler.processVerifyAssertionResponse_ =\n function(request, response) {\n // This makes it possible for OIDC providers to:\n // 1. Initialize an OIDC Auth credential on successful response.\n // 2. Initialize an OIDC Auth credential within the recovery error.\n\n // When request has sessionId and response has OIDC ID token and no pending\n // token, a credential with raw nonce and OIDC ID token needs to be returned.\n if (response[fireauth.RpcHandler.AuthServerField.OAUTH_ID_TOKEN] &&\n response[fireauth.RpcHandler.AuthServerField.PROVIDER_ID] &&\n response[fireauth.RpcHandler.AuthServerField.PROVIDER_ID]\n .indexOf(fireauth.constants.OIDC_PREFIX) == 0 &&\n // Use pendingToken instead of idToken and rawNonce when available.\n !response[fireauth.RpcHandler.AuthServerField.PENDING_TOKEN]) {\n if (request[fireauth.RpcHandler.AuthServerField.SESSION_ID]) {\n // For full OAuth flow, the nonce is in the session ID.\n response[fireauth.RpcHandler.InjectedResponseField.NONCE] =\n request[fireauth.RpcHandler.AuthServerField.SESSION_ID];\n } else if (request[fireauth.RpcHandler.AuthServerField.POST_BODY]) {\n // For credential flow, the nonce is in the postBody nonce field.\n var queryData = new goog.Uri.QueryData(\n request[fireauth.RpcHandler.AuthServerField.POST_BODY]);\n if (queryData.containsKey(\n fireauth.RpcHandler.InjectedResponseField.NONCE)) {\n response[fireauth.RpcHandler.InjectedResponseField.NONCE] =\n queryData.get(fireauth.RpcHandler.InjectedResponseField.NONCE);\n }\n }\n }\n return response;\n};\n\n\n/**\n * Validates a response from verifyAssertionForExisting.\n * @param {?Object} response The verifyAssertionForExisting response data.\n * @private\n */\nfireauth.RpcHandler.validateVerifyAssertionForExistingResponse_ =\n function(response) {\n // When returnIdpCredential is set to true and the account is new, no error\n // is thrown but an errorMessage is added to the response. No idToken is\n // passed.\n if (response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE] &&\n response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE] ==\n fireauth.RpcHandler.ServerError.USER_NOT_FOUND) {\n // This corresponds to user-not-found.\n throw new fireauth.AuthError(fireauth.authenum.Error.USER_DELETED);\n } else if (response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE]) {\n // Construct developer facing error message from server code in errorMessage\n // field.\n throw fireauth.RpcHandler.getDeveloperErrorFromCode_(\n response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE]);\n }\n // Need confirmation should not be returned when do not create new user flag\n // is set.\n // Validate if ID token or multi-factor pending credential is available.\n fireauth.RpcHandler.validateIdTokenResponse_(response);\n};\n\n\n/**\n * Validates a response from verifyAssertion.\n * @param {?Object} response The verifyAssertion response data.\n * @private\n */\nfireauth.RpcHandler.validateVerifyAssertionResponse_ = function(response) {\n var error = null;\n if (response[fireauth.RpcHandler.AuthServerField.NEED_CONFIRMATION]) {\n // Account linking required, previously logged in to another account\n // with same email. User must authenticate they are owners of the\n // first account.\n // If enough info for Auth linking error, throw an instance of Auth linking\n // error. This will be used by developer after reauthenticating with email\n // provided by error to link using the credentials in Auth linking error.\n // If missing information, return regular Auth error.\n response['code'] = fireauth.authenum.Error.NEED_CONFIRMATION;\n error = fireauth.AuthErrorWithCredential.fromPlainObject(response);\n } else if (response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE] ==\n fireauth.RpcHandler.ServerError.FEDERATED_USER_ID_ALREADY_LINKED) {\n // When FEDERATED_USER_ID_ALREADY_LINKED returned in error message, auth\n // credential and email will also be returned, throw relevant error in that\n // case.\n // In this case the developer needs to signInWithCredential to the returned\n // credentials.\n response['code'] = fireauth.authenum.Error.CREDENTIAL_ALREADY_IN_USE;\n error = fireauth.AuthErrorWithCredential.fromPlainObject(response);\n } else if (response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE] ==\n fireauth.RpcHandler.ServerError.EMAIL_EXISTS) {\n // When EMAIL_EXISTS returned in error message, Auth credential and email\n // will also be returned, throw relevant error in that case.\n // In this case, the developers needs to sign in the user to the original\n // owner of the account and then link to the returned credential here.\n response['code'] = fireauth.authenum.Error.EMAIL_EXISTS;\n error = fireauth.AuthErrorWithCredential.fromPlainObject(response);\n } else if (response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE]) {\n // Construct developer facing error message from server code in errorMessage\n // field.\n error = fireauth.RpcHandler.getDeveloperErrorFromCode_(\n response[fireauth.RpcHandler.AuthServerField.ERROR_MESSAGE]);\n }\n // If error found, throw it.\n if (error) {\n throw error;\n }\n // Validate if ID token or multi-factor pending credential is available.\n fireauth.RpcHandler.validateIdTokenResponse_(response);\n};\n\n\n/**\n * Validates a verifyAssertion with linking request.\n * @param {?Object} request The verifyAssertion request data.\n * @private\n */\nfireauth.RpcHandler.validateVerifyAssertionLinkRequest_ = function(request) {\n // idToken with either (requestUri and sessionId) or (requestUri and postBody)\n // are required.\n fireauth.RpcHandler.validateVerifyAssertionRequest_(request);\n if (!request['idToken']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * @typedef {{\n * autoCreate: (boolean|undefined),\n * requestUri: string,\n * postBody: (?string|undefined),\n * pendingIdToken: (?string|undefined),\n * sessionId: (?string|undefined),\n * idToken: (?string|undefined),\n * returnIdpCredential: (boolean|undefined),\n * tenantId: (?string|undefined)\n * }}\n */\nfireauth.RpcHandler.VerifyAssertionData;\n\n\n/**\n * Requests verifyAssertion endpoint. When resolved, promise returns the whole\n * response.\n * @param {!fireauth.RpcHandler.VerifyAssertionData} request\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyAssertion = function(request) {\n // Force Auth credential to be returned on the following errors:\n // FEDERATED_USER_ID_ALREADY_LINKED\n // EMAIL_EXISTS\n request['returnIdpCredential'] = true;\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.VERIFY_ASSERTION,\n request);\n};\n\n\n/**\n * Requests verifyAssertion endpoint for federated account linking. When\n * resolved, promise returns the whole response.\n * @param {!fireauth.RpcHandler.VerifyAssertionData} request\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyAssertionForLinking = function(request) {\n // Force Auth credential to be returned on the following errors:\n // FEDERATED_USER_ID_ALREADY_LINKED\n // EMAIL_EXISTS\n request['returnIdpCredential'] = true;\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.VERIFY_ASSERTION_FOR_LINKING,\n request);\n};\n\n\n/**\n * Requests verifyAssertion endpoint for an existing federated account. When\n * resolved, promise returns the whole response. If not existing, a\n * user-not-found error is thrown.\n * @param {!fireauth.RpcHandler.VerifyAssertionData} request\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.verifyAssertionForExisting = function(request) {\n // Since we are setting returnIdpCredential to true, a response will be\n // returned even though the account doesn't exist but an error message is\n // appended with value set to USER_NOT_FOUND. If this flag is not passed, only\n // the USER_NOT_FOUND error is thrown without any response.\n request['returnIdpCredential'] = true;\n // Do not create a new account if the user doesn't exist.\n request['autoCreate'] = false;\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.VERIFY_ASSERTION_FOR_EXISTING,\n request);\n};\n\n\n/**\n * Validates a request that should contain an action code.\n * @param {!Object} request\n * @private\n */\nfireauth.RpcHandler.validateApplyActionCodeRequest_ = function(request) {\n if (!request['oobCode']) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_OOB_CODE);\n }\n};\n\n\n/**\n * Validates that a checkActionCode response contains the email and requestType\n * fields.\n * @param {!Object} response The raw response returned by the server.\n * @private\n */\nfireauth.RpcHandler.validateCheckActionCodeResponse_ = function(response) {\n // If the code is invalid, usually a clear error would be returned.\n // In this case, something unexpected happened.\n // Email could be empty only if the request type is EMAIL_SIGNIN.\n var operation = response['requestType'];\n if (!operation ||\n (!response['email'] && operation != 'EMAIL_SIGNIN' &&\n operation != 'VERIFY_AND_CHANGE_EMAIL')) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n};\n\n\n/**\n * Requests resetPassword endpoint for password reset, returns promise that\n * resolves with user's email.\n * @param {string} code The email action code to confirm for password reset.\n * @param {string} newPassword The new password.\n * @return {!goog.Promise<string>}\n */\nfireauth.RpcHandler.prototype.confirmPasswordReset =\n function(code, newPassword) {\n var request = {\n 'oobCode': code,\n 'newPassword': newPassword\n };\n return this.invokeRpc(fireauth.RpcHandler.ApiMethod.RESET_PASSWORD, request);\n};\n\n\n/**\n * Checks the validity of an email action code and returns the response\n * received.\n * @param {string} code The email action code to check.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.RpcHandler.prototype.checkActionCode = function(code) {\n var request = {\n 'oobCode': code\n };\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.CHECK_ACTION_CODE, request);\n};\n\n\n/**\n * Applies an out-of-band email action code, such as an email verification code.\n * @param {string} code The email action code.\n * @return {!goog.Promise<string>} A promise that resolves with the user's\n * email.\n */\nfireauth.RpcHandler.prototype.applyActionCode = function(code) {\n var request = {\n 'oobCode': code\n };\n return this.invokeRpc(\n fireauth.RpcHandler.ApiMethod.APPLY_OOB_CODE, request);\n};\n\n\n/**\n * The specification of an RPC call. The fields are:\n * <ul>\n * <li>cachebuster: defines whether to send a unique string with request to\n * force the backend to return an uncached response to request.\n * <li>customErrorMap: A map of backend error codes to client-side errors.\n * Any entries set here override the default handling of the backend error\n * code.\n * <li>endpoint: defines the backend endpoint to call.\n * <li>httpMethod: defines the HTTP method to use, defaulting to POST if not\n * specified.\n * <li>requestRequiredFields: an array of the fields that are required in the\n * request. The RPC call will fail with an INTERNAL_ERROR error if a\n * required field is not present or if it is null, undefined, or the empty\n * string.\n * <li>requestValidator: a function that takes in the request object and throws\n * an error if the request is invalid.\n * <li>responsePreprocessor: a function to modify the response before running\n * validation. The function takes in the request and response object.\n * <li>responseValidator: a function that takes in the response object and\n * throws an error if the response is invalid.\n * <li>responseField: the field of the response object that will be returned\n * from the RPC call. If no field is specified, the entire response object\n * will be returned.\n * <li>returnSecureToken: Set to true to explicitly request STS tokens instead\n * of legacy Google Identity Toolkit tokens from the backend.\n * <li>requireTenantId: Set to true to send tenant ID to backend in the request.\n * <li>useIdentityPlatformEndpoint: Whether to use new identity platform\n * endpoints. The default is false.\n * </ul>\n * @typedef {{\n * cachebuster: (boolean|undefined),\n * customErrorMap: (!fireauth.RpcHandler.ServerErrorMap|undefined),\n * endpoint: string,\n * httpMethod: (!fireauth.RpcHandler.HttpMethod|undefined),\n * requestRequiredFields: (!Array<string>|undefined),\n * requestValidator: (function(!Object):void|undefined),\n * responsePreprocessor: ((function(!Object, !Object):!Object)|undefined),\n * responseValidator: (function(!Object):void|undefined),\n * responseField: (string|undefined),\n * returnSecureToken: (boolean|undefined),\n * requireTenantId: (boolean|undefined),\n * useIdentityPlatformEndpoint: (boolean|undefined)\n * }}\n */\nfireauth.RpcHandler.ApiMethodHandler;\n\n\n/**\n * The specifications for the backend API methods.\n * @enum {!fireauth.RpcHandler.ApiMethodHandler}\n */\nfireauth.RpcHandler.ApiMethod = {\n APPLY_OOB_CODE: {\n endpoint: 'setAccountInfo',\n requestValidator: fireauth.RpcHandler.validateApplyActionCodeRequest_,\n responseField: fireauth.RpcHandler.AuthServerField.EMAIL,\n requireTenantId: true\n },\n CHECK_ACTION_CODE: {\n endpoint: 'resetPassword',\n requestValidator: fireauth.RpcHandler.validateApplyActionCodeRequest_,\n responseValidator: fireauth.RpcHandler.validateCheckActionCodeResponse_,\n requireTenantId: true\n },\n CREATE_ACCOUNT: {\n endpoint: 'signupNewUser',\n requestValidator: fireauth.RpcHandler.validateCreateAccountRequest_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n returnSecureToken: true,\n requireTenantId: true\n },\n CREATE_AUTH_URI: {\n endpoint: 'createAuthUri',\n requireTenantId: true\n },\n DELETE_ACCOUNT: {\n endpoint: 'deleteAccount',\n requestRequiredFields: ['idToken']\n },\n DELETE_LINKED_ACCOUNTS: {\n endpoint: 'setAccountInfo',\n requestRequiredFields: ['idToken', 'deleteProvider'],\n requestValidator: fireauth.RpcHandler.validateDeleteLinkedAccountsRequest_\n },\n EMAIL_LINK_SIGNIN: {\n endpoint: 'emailLinkSignin',\n requestRequiredFields: ['email', 'oobCode'],\n requestValidator: fireauth.RpcHandler.validateRequestHasEmail_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n returnSecureToken: true,\n requireTenantId: true\n },\n EMAIL_LINK_SIGNIN_FOR_LINKING: {\n endpoint: 'emailLinkSignin',\n requestRequiredFields: ['idToken', 'email', 'oobCode'],\n requestValidator: fireauth.RpcHandler.validateRequestHasEmail_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n returnSecureToken: true\n },\n FINALIZE_PHONE_MFA_ENROLLMENT: {\n endpoint: 'accounts/mfaEnrollment:finalize',\n requestRequiredFields: ['idToken', 'phoneVerificationInfo'],\n requestValidator:\n fireauth.RpcHandler.validateFinalizePhoneMfaRequest_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n requireTenantId: true,\n useIdentityPlatformEndpoint: true\n },\n FINALIZE_PHONE_MFA_SIGN_IN: {\n endpoint: 'accounts/mfaSignIn:finalize',\n requestRequiredFields: ['mfaPendingCredential', 'phoneVerificationInfo'],\n requestValidator:\n fireauth.RpcHandler.validateFinalizePhoneMfaRequest_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n requireTenantId: true,\n useIdentityPlatformEndpoint: true\n },\n GET_ACCOUNT_INFO: {\n endpoint: 'getAccountInfo'\n },\n GET_AUTH_URI: {\n endpoint: 'createAuthUri',\n requestValidator: fireauth.RpcHandler.validateGetAuthUriRequest_,\n responseValidator: fireauth.RpcHandler.validateGetAuthResponse_,\n requireTenantId: true\n },\n GET_EMAIL_SIGNIN_CODE: {\n endpoint: 'getOobConfirmationCode',\n requestRequiredFields: ['requestType'],\n requestValidator: fireauth.RpcHandler.validateEmailSignInCodeRequest_,\n responseField: fireauth.RpcHandler.AuthServerField.EMAIL,\n requireTenantId: true\n },\n GET_EMAIL_VERIFICATION_CODE: {\n endpoint: 'getOobConfirmationCode',\n requestRequiredFields: ['idToken', 'requestType'],\n requestValidator: fireauth.RpcHandler.validateEmailVerificationCodeRequest_,\n responseField: fireauth.RpcHandler.AuthServerField.EMAIL,\n requireTenantId: true\n },\n GET_EMAIL_VERIFICATION_CODE_BEFORE_UPDATE: {\n endpoint: 'getOobConfirmationCode',\n requestRequiredFields: ['idToken', 'newEmail', 'requestType'],\n requestValidator:\n fireauth.RpcHandler.validateEmailVerificationCodeBeforeUpdateRequest_,\n responseField: fireauth.RpcHandler.AuthServerField.EMAIL,\n requireTenantId: true\n },\n GET_OOB_CODE: {\n endpoint: 'getOobConfirmationCode',\n requestRequiredFields: ['requestType'],\n requestValidator: fireauth.RpcHandler.validateOobCodeRequest_,\n responseField: fireauth.RpcHandler.AuthServerField.EMAIL,\n requireTenantId: true\n },\n GET_PROJECT_CONFIG: {\n // Microsoft edge caching bug. There are two getProjectConfig API calls,\n // first from top level window and then from iframe. The second call has a\n // response of 304 which means it's a cached response. We suspect the call\n // from iframe is reusing the response from the first call and checks the\n // allowed origin in the cached response, which only contains the domain for\n // the top level window.\n cachebuster: true,\n endpoint: 'getProjectConfig',\n httpMethod: fireauth.RpcHandler.HttpMethod.GET\n },\n GET_RECAPTCHA_PARAM: {\n cachebuster: true,\n endpoint: 'getRecaptchaParam',\n httpMethod: fireauth.RpcHandler.HttpMethod.GET,\n responseValidator: fireauth.RpcHandler.validateGetRecaptchaParamResponse_\n },\n RESET_PASSWORD: {\n endpoint: 'resetPassword',\n requestValidator: fireauth.RpcHandler.validateApplyActionCodeRequest_,\n responseField: fireauth.RpcHandler.AuthServerField.EMAIL,\n requireTenantId: true\n },\n RETURN_DYNAMIC_LINK: {\n cachebuster: true,\n endpoint: 'getProjectConfig',\n httpMethod: fireauth.RpcHandler.HttpMethod.GET,\n responseField: fireauth.RpcHandler.AuthServerField.DYNAMIC_LINKS_DOMAIN\n },\n SEND_VERIFICATION_CODE: {\n endpoint: 'sendVerificationCode',\n // Currently only reCAPTCHA tokens supported.\n requestRequiredFields: ['phoneNumber', 'recaptchaToken'],\n responseField: fireauth.RpcHandler.AuthServerField.SESSION_INFO,\n requireTenantId: true\n },\n SET_ACCOUNT_INFO: {\n endpoint: 'setAccountInfo',\n requestRequiredFields: ['idToken'],\n requestValidator: fireauth.RpcHandler.validateEmailIfPresent_,\n returnSecureToken: true // Maybe updating email will invalidate token in the\n // future, this will prevent breaking the client.\n },\n SET_ACCOUNT_INFO_SENSITIVE: {\n endpoint: 'setAccountInfo',\n requestRequiredFields: ['idToken'],\n requestValidator: fireauth.RpcHandler.validateSetAccountInfoSensitive_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n returnSecureToken: true // Updating password will send back new sts tokens.\n },\n SIGN_IN_ANONYMOUSLY: {\n endpoint: 'signupNewUser',\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n returnSecureToken: true,\n requireTenantId: true\n },\n START_PHONE_MFA_ENROLLMENT: {\n endpoint: 'accounts/mfaEnrollment:start',\n requestRequiredFields: ['idToken', 'phoneEnrollmentInfo'],\n requestValidator:\n fireauth.RpcHandler.validateStartPhoneMfaEnrollmentRequest_,\n responseValidator:\n fireauth.RpcHandler.validateStartPhoneMfaEnrollmentResponse_,\n requireTenantId: true,\n useIdentityPlatformEndpoint: true\n },\n START_PHONE_MFA_SIGN_IN: {\n endpoint: 'accounts/mfaSignIn:start',\n requestRequiredFields: ['mfaPendingCredential', 'mfaEnrollmentId',\n 'phoneSignInInfo'],\n requestValidator:\n fireauth.RpcHandler.validateStartPhoneMfaSignInRequest_,\n responseValidator:\n fireauth.RpcHandler.validateStartPhoneMfaSignInResponse_,\n requireTenantId: true,\n useIdentityPlatformEndpoint: true\n },\n VERIFY_ASSERTION: {\n endpoint: 'verifyAssertion',\n requestValidator: fireauth.RpcHandler.validateVerifyAssertionRequest_,\n responsePreprocessor: fireauth.RpcHandler.processVerifyAssertionResponse_,\n responseValidator: fireauth.RpcHandler.validateVerifyAssertionResponse_,\n returnSecureToken: true,\n // Tenant ID is required for this endpoint. But for\n // signInWithRedirect/Popup APIs, to make createAuthUri call and\n // verifyAssertion call atomic, the tenant ID on RPC handler will be\n // overridden by the tenant ID passed directly from the\n // request, which is retrieved from Auth event. For signInWithCredential\n // API, the tenant ID will still be retrieved from the RPC handler.\n requireTenantId: true\n },\n VERIFY_ASSERTION_FOR_EXISTING: {\n endpoint: 'verifyAssertion',\n requestValidator: fireauth.RpcHandler.validateVerifyAssertionRequest_,\n responsePreprocessor: fireauth.RpcHandler.processVerifyAssertionResponse_,\n responseValidator:\n fireauth.RpcHandler.validateVerifyAssertionForExistingResponse_,\n returnSecureToken: true,\n // Tenant ID is required for this endpoint. But for\n // reauthenticateWithRedirect/Popup APIs, to make createAuthUri call and\n // verifyAssertion call atomic, the tenant ID on RPC handler will be\n // overridden by the tenant ID passed directly from the\n // request, which is retrieved from Auth event. For\n // reauthenticateWithCredential API, the tenant ID will still be retrieved\n // from the RPC handler.\n requireTenantId: true\n },\n VERIFY_ASSERTION_FOR_LINKING: {\n endpoint: 'verifyAssertion',\n requestValidator: fireauth.RpcHandler.validateVerifyAssertionLinkRequest_,\n responsePreprocessor: fireauth.RpcHandler.processVerifyAssertionResponse_,\n responseValidator: fireauth.RpcHandler.validateVerifyAssertionResponse_,\n returnSecureToken: true\n },\n VERIFY_CUSTOM_TOKEN: {\n endpoint: 'verifyCustomToken',\n requestValidator: fireauth.RpcHandler.validateVerifyCustomTokenRequest_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n returnSecureToken: true,\n requireTenantId: true\n },\n VERIFY_PASSWORD: {\n endpoint: 'verifyPassword',\n requestValidator: fireauth.RpcHandler.validateVerifyPasswordRequest_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n returnSecureToken: true,\n requireTenantId: true\n },\n VERIFY_PHONE_NUMBER: {\n endpoint: 'verifyPhoneNumber',\n requestValidator: fireauth.RpcHandler.validateVerifyPhoneNumberRequest_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n requireTenantId: true\n },\n VERIFY_PHONE_NUMBER_FOR_LINKING: {\n endpoint: 'verifyPhoneNumber',\n requestValidator: fireauth.RpcHandler.validateVerifyPhoneNumberLinkRequest_,\n responseValidator:\n fireauth.RpcHandler.validateVerifyPhoneNumberForLinkingResponse_\n },\n VERIFY_PHONE_NUMBER_FOR_EXISTING: {\n customErrorMap: fireauth.RpcHandler.verifyPhoneNumberForExistingErrorMap_,\n endpoint: 'verifyPhoneNumber',\n requestValidator: fireauth.RpcHandler.validateVerifyPhoneNumberRequest_,\n responseValidator: fireauth.RpcHandler.validateIdTokenResponse_,\n requireTenantId: true\n },\n WITHDRAW_MFA: {\n endpoint: 'accounts/mfaEnrollment:withdraw',\n requestRequiredFields: ['idToken', 'mfaEnrollmentId'],\n responseValidator: fireauth.RpcHandler.validateWithdrawMfaResponse_,\n requireTenantId: true,\n useIdentityPlatformEndpoint: true\n }\n};\n\n\n/**\n * @const {string} The parameter to send to the backend to specify that the\n * client accepts STS tokens directly from Firebear backends.\n * @private\n */\nfireauth.RpcHandler.USE_STS_TOKEN_PARAM_ = 'returnSecureToken';\n\n\n/**\n * @const {string} The parameter to send to the backend to specify the tenant\n * ID.\n * @private\n */\nfireauth.RpcHandler.TENANT_ID_PARAM_ = 'tenantId';\n\n\n/**\n * Invokes an RPC method according to the specification defined by\n * {@code fireauth.RpcHandler.ApiMethod}.\n * @param {!fireauth.RpcHandler.ApiMethod} method The method to invoke.\n * @param {!Object} request The input data to the method.\n * @return {!goog.Promise} A promise that resolves with the results of the RPC.\n * The format of the results can be modified in\n * {@code fireauth.RpcHandler.ApiMethod}.\n */\nfireauth.RpcHandler.prototype.invokeRpc = function(method, request) {\n if (!fireauth.object.hasNonEmptyFields(\n request, method.requestRequiredFields)) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR));\n }\n\n var useIdentityPlatformEndpoint = !!method.useIdentityPlatformEndpoint;\n var httpMethod = method.httpMethod || fireauth.RpcHandler.HttpMethod.POST;\n var self = this;\n var response;\n return goog.Promise.resolve(request)\n .then(method.requestValidator)\n .then(function() {\n if (method.returnSecureToken) {\n // Signal that the client accepts STS tokens, for the legacy Google\n // Identity Toolkit token to STS token migration.\n request[fireauth.RpcHandler.USE_STS_TOKEN_PARAM_] = true;\n }\n // If tenant ID is explicitly passed in the request, it will override\n // the tenant ID on RPC handler.\n if (method.requireTenantId && self.tenantId_ &&\n (typeof request[fireauth.RpcHandler.TENANT_ID_PARAM_] ===\n 'undefined')) {\n request[fireauth.RpcHandler.TENANT_ID_PARAM_] = self.tenantId_;\n }\n return useIdentityPlatformEndpoint ?\n self.requestIdentityPlatformEndpoint(method.endpoint, httpMethod,\n request, method.customErrorMap, method.cachebuster || false) :\n self.requestFirebaseEndpoint(method.endpoint, httpMethod,\n request, method.customErrorMap, method.cachebuster || false);\n })\n .then(function(tempResponse) {\n response = tempResponse;\n // If response processor is available, pass request and response through\n // it. Modifications would be made using response reference.\n if (method.responsePreprocessor) {\n return method.responsePreprocessor(request, response);\n }\n return response;\n })\n .then(method.responseValidator)\n .then(function() {\n if (!method.responseField) {\n return response;\n }\n if (!(method.responseField in response)) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR);\n }\n return response[method.responseField];\n });\n};\n\n\n/**\n * Checks if the server response contains errors.\n * @param {!Object} resp The API response.\n * @return {boolean} {@code true} if the response contains errors.\n * @private\n */\nfireauth.RpcHandler.hasError_ = function(resp) {\n return !!resp['error'];\n};\n\n\n/**\n * Returns the developer facing error corresponding to the server code provided.\n * @param {string} serverErrorCode The server error message.\n * @return {!fireauth.AuthError} The corresponding error object.\n * @private\n */\nfireauth.RpcHandler.getDeveloperErrorFromCode_ = function(serverErrorCode) {\n // Encapsulate the server error code in a typical server error response with\n // the code populated within. This will convert the response to a developer\n // facing one.\n return fireauth.RpcHandler.getDeveloperError_({\n 'error': {\n 'errors': [\n {\n 'message': serverErrorCode\n }\n ],\n 'code': 400,\n 'message': serverErrorCode\n }\n });\n};\n\n\n/**\n * Converts a server response with errors to a developer-facing AuthError.\n * @param {!Object} response The server response.\n * @param {?fireauth.RpcHandler.ServerErrorMap=} opt_customErrorMap A map of\n * backend error codes to client-side errors. Any entries set here\n * override the default handling of the backend error code.\n * @return {!fireauth.AuthError} The corresponding error object.\n * @private\n */\nfireauth.RpcHandler.getDeveloperError_ =\n function(response, opt_customErrorMap) {\n var errorMessage;\n var apiaryError = fireauth.RpcHandler.getApiaryError_(response);\n if (apiaryError) {\n return apiaryError;\n }\n\n var serverErrorCode = fireauth.RpcHandler.getErrorCode_(response);\n\n var errorMap = {};\n\n // Custom token errors.\n errorMap[fireauth.RpcHandler.ServerError.INVALID_CUSTOM_TOKEN] =\n fireauth.authenum.Error.INVALID_CUSTOM_TOKEN;\n errorMap[fireauth.RpcHandler.ServerError.CREDENTIAL_MISMATCH] =\n fireauth.authenum.Error.CREDENTIAL_MISMATCH;\n // This can only happen if the SDK sends a bad request.\n errorMap[fireauth.RpcHandler.ServerError.MISSING_CUSTOM_TOKEN] =\n fireauth.authenum.Error.INTERNAL_ERROR;\n\n // Create Auth URI errors.\n errorMap[fireauth.RpcHandler.ServerError.INVALID_IDENTIFIER] =\n fireauth.authenum.Error.INVALID_EMAIL;\n // This can only happen if the SDK sends a bad request.\n errorMap[fireauth.RpcHandler.ServerError.MISSING_CONTINUE_URI] =\n fireauth.authenum.Error.INTERNAL_ERROR;\n\n // Sign in with email and password errors (some apply to sign up too).\n errorMap[fireauth.RpcHandler.ServerError.INVALID_EMAIL] =\n fireauth.authenum.Error.INVALID_EMAIL;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_PASSWORD] =\n fireauth.authenum.Error.INVALID_PASSWORD;\n errorMap[fireauth.RpcHandler.ServerError.USER_DISABLED] =\n fireauth.authenum.Error.USER_DISABLED;\n // This can only happen if the SDK sends a bad request.\n errorMap[fireauth.RpcHandler.ServerError.MISSING_PASSWORD] =\n fireauth.authenum.Error.INTERNAL_ERROR;\n\n // Sign up with email and password errors.\n errorMap[fireauth.RpcHandler.ServerError.EMAIL_EXISTS] =\n fireauth.authenum.Error.EMAIL_EXISTS;\n errorMap[fireauth.RpcHandler.ServerError.PASSWORD_LOGIN_DISABLED] =\n fireauth.authenum.Error.OPERATION_NOT_ALLOWED;\n\n // Verify assertion for sign in with credential errors:\n errorMap[fireauth.RpcHandler.ServerError.INVALID_IDP_RESPONSE] =\n fireauth.authenum.Error.INVALID_IDP_RESPONSE;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_PENDING_TOKEN] =\n fireauth.authenum.Error.INVALID_IDP_RESPONSE;\n errorMap[fireauth.RpcHandler.ServerError.FEDERATED_USER_ID_ALREADY_LINKED] =\n fireauth.authenum.Error.CREDENTIAL_ALREADY_IN_USE;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_OR_INVALID_NONCE] =\n fireauth.authenum.Error.MISSING_OR_INVALID_NONCE;\n\n // Email template errors while sending emails:\n errorMap[fireauth.RpcHandler.ServerError.INVALID_MESSAGE_PAYLOAD] =\n fireauth.authenum.Error.INVALID_MESSAGE_PAYLOAD;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_RECIPIENT_EMAIL] =\n fireauth.authenum.Error.INVALID_RECIPIENT_EMAIL;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_SENDER] =\n fireauth.authenum.Error.INVALID_SENDER;\n\n // Send Password reset email errors:\n errorMap[fireauth.RpcHandler.ServerError.EMAIL_NOT_FOUND] =\n fireauth.authenum.Error.USER_DELETED;\n errorMap[fireauth.RpcHandler.ServerError.RESET_PASSWORD_EXCEED_LIMIT] =\n fireauth.authenum.Error.TOO_MANY_ATTEMPTS_TRY_LATER;\n\n // Reset password errors:\n errorMap[fireauth.RpcHandler.ServerError.EXPIRED_OOB_CODE] =\n fireauth.authenum.Error.EXPIRED_OOB_CODE;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_OOB_CODE] =\n fireauth.authenum.Error.INVALID_OOB_CODE;\n // This can only happen if the SDK sends a bad request.\n errorMap[fireauth.RpcHandler.ServerError.MISSING_OOB_CODE] =\n fireauth.authenum.Error.INTERNAL_ERROR;\n\n // Get Auth URI errors:\n errorMap[fireauth.RpcHandler.ServerError.INVALID_PROVIDER_ID] =\n fireauth.authenum.Error.INVALID_PROVIDER_ID;\n\n // Operations that require ID token in request:\n errorMap[fireauth.RpcHandler.ServerError.CREDENTIAL_TOO_OLD_LOGIN_AGAIN] =\n fireauth.authenum.Error.CREDENTIAL_TOO_OLD_LOGIN_AGAIN;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_ID_TOKEN] =\n fireauth.authenum.Error.INVALID_AUTH;\n errorMap[fireauth.RpcHandler.ServerError.TOKEN_EXPIRED] =\n fireauth.authenum.Error.TOKEN_EXPIRED;\n errorMap[fireauth.RpcHandler.ServerError.USER_NOT_FOUND] =\n fireauth.authenum.Error.TOKEN_EXPIRED;\n\n // CORS issues.\n errorMap[fireauth.RpcHandler.ServerError.CORS_UNSUPPORTED] =\n fireauth.authenum.Error.CORS_UNSUPPORTED;\n\n // Dynamic link not activated.\n errorMap[fireauth.RpcHandler.ServerError.DYNAMIC_LINK_NOT_ACTIVATED] =\n fireauth.authenum.Error.DYNAMIC_LINK_NOT_ACTIVATED;\n\n // iosBundleId or androidPackageName not valid error.\n errorMap[fireauth.RpcHandler.ServerError.INVALID_APP_ID] =\n fireauth.authenum.Error.INVALID_APP_ID;\n\n // Other errors.\n errorMap[fireauth.RpcHandler.ServerError.TOO_MANY_ATTEMPTS_TRY_LATER] =\n fireauth.authenum.Error.TOO_MANY_ATTEMPTS_TRY_LATER;\n errorMap[fireauth.RpcHandler.ServerError.WEAK_PASSWORD] =\n fireauth.authenum.Error.WEAK_PASSWORD;\n errorMap[fireauth.RpcHandler.ServerError.OPERATION_NOT_ALLOWED] =\n fireauth.authenum.Error.OPERATION_NOT_ALLOWED;\n errorMap[fireauth.RpcHandler.ServerError.USER_CANCELLED] =\n fireauth.authenum.Error.USER_CANCELLED;\n\n // Phone Auth related errors.\n errorMap[fireauth.RpcHandler.ServerError.CAPTCHA_CHECK_FAILED] =\n fireauth.authenum.Error.CAPTCHA_CHECK_FAILED;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_APP_CREDENTIAL] =\n fireauth.authenum.Error.INVALID_APP_CREDENTIAL;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_CODE] =\n fireauth.authenum.Error.INVALID_CODE;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_PHONE_NUMBER] =\n fireauth.authenum.Error.INVALID_PHONE_NUMBER;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_SESSION_INFO] =\n fireauth.authenum.Error.INVALID_SESSION_INFO;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_TEMPORARY_PROOF] =\n fireauth.authenum.Error.INVALID_IDP_RESPONSE;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_APP_CREDENTIAL] =\n fireauth.authenum.Error.MISSING_APP_CREDENTIAL;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_CODE] =\n fireauth.authenum.Error.MISSING_CODE;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_PHONE_NUMBER] =\n fireauth.authenum.Error.MISSING_PHONE_NUMBER;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_SESSION_INFO] =\n fireauth.authenum.Error.MISSING_SESSION_INFO;\n errorMap[fireauth.RpcHandler.ServerError.QUOTA_EXCEEDED] =\n fireauth.authenum.Error.QUOTA_EXCEEDED;\n errorMap[fireauth.RpcHandler.ServerError.SESSION_EXPIRED] =\n fireauth.authenum.Error.CODE_EXPIRED;\n errorMap[fireauth.RpcHandler.ServerError.REJECTED_CREDENTIAL] =\n fireauth.authenum.Error.REJECTED_CREDENTIAL;\n\n // Other action code errors when additional settings passed.\n errorMap[fireauth.RpcHandler.ServerError.INVALID_CONTINUE_URI] =\n fireauth.authenum.Error.INVALID_CONTINUE_URI;\n // MISSING_CONTINUE_URI is getting mapped to INTERNAL_ERROR above.\n // This is OK as this error will be caught by client side validation.\n errorMap[fireauth.RpcHandler.ServerError.MISSING_ANDROID_PACKAGE_NAME] =\n fireauth.authenum.Error.MISSING_ANDROID_PACKAGE_NAME;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_IOS_BUNDLE_ID] =\n fireauth.authenum.Error.MISSING_IOS_BUNDLE_ID;\n errorMap[fireauth.RpcHandler.ServerError.UNAUTHORIZED_DOMAIN] =\n fireauth.authenum.Error.UNAUTHORIZED_DOMAIN;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_DYNAMIC_LINK_DOMAIN] =\n fireauth.authenum.Error.INVALID_DYNAMIC_LINK_DOMAIN;\n\n // getProjectConfig errors when clientId is passed.\n errorMap[fireauth.RpcHandler.ServerError.INVALID_OAUTH_CLIENT_ID] =\n fireauth.authenum.Error.INVALID_OAUTH_CLIENT_ID;\n // getProjectConfig errors when sha1Cert is passed.\n errorMap[fireauth.RpcHandler.ServerError.INVALID_CERT_HASH] =\n fireauth.authenum.Error.INVALID_CERT_HASH;\n\n // Multi-tenant related errors.\n errorMap[fireauth.RpcHandler.ServerError.UNSUPPORTED_TENANT_OPERATION] =\n fireauth.authenum.Error.UNSUPPORTED_TENANT_OPERATION;\n errorMap[fireauth.RpcHandler.ServerError.INVALID_TENANT_ID] =\n fireauth.authenum.Error.INVALID_TENANT_ID;\n errorMap[fireauth.RpcHandler.ServerError.TENANT_ID_MISMATCH] =\n fireauth.authenum.Error.TENANT_ID_MISMATCH;\n\n // User actions (sign-up or deletion) disabled errors.\n errorMap[fireauth.RpcHandler.ServerError.ADMIN_ONLY_OPERATION] =\n fireauth.authenum.Error.ADMIN_ONLY_OPERATION;\n\n // Multi-factor related errors.\n errorMap[fireauth.RpcHandler.ServerError.INVALID_MFA_PENDING_CREDENTIAL] =\n fireauth.authenum.Error.INVALID_MFA_PENDING_CREDENTIAL;\n errorMap[fireauth.RpcHandler.ServerError.MFA_ENROLLMENT_NOT_FOUND] =\n fireauth.authenum.Error.MFA_ENROLLMENT_NOT_FOUND;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_MFA_PENDING_CREDENTIAL] =\n fireauth.authenum.Error.MISSING_MFA_PENDING_CREDENTIAL;\n errorMap[fireauth.RpcHandler.ServerError.MISSING_MFA_ENROLLMENT_ID] =\n fireauth.authenum.Error.MISSING_MFA_ENROLLMENT_ID;\n errorMap[fireauth.RpcHandler.ServerError.EMAIL_CHANGE_NEEDS_VERIFICATION] =\n fireauth.authenum.Error.EMAIL_CHANGE_NEEDS_VERIFICATION;\n errorMap[fireauth.RpcHandler.ServerError.SECOND_FACTOR_EXISTS] =\n fireauth.authenum.Error.SECOND_FACTOR_EXISTS;\n errorMap[fireauth.RpcHandler.ServerError.SECOND_FACTOR_LIMIT_EXCEEDED] =\n fireauth.authenum.Error.SECOND_FACTOR_LIMIT_EXCEEDED;\n errorMap[fireauth.RpcHandler.ServerError.UNSUPPORTED_FIRST_FACTOR] =\n fireauth.authenum.Error.UNSUPPORTED_FIRST_FACTOR;\n errorMap[fireauth.RpcHandler.ServerError.UNVERIFIED_EMAIL] =\n fireauth.authenum.Error.UNVERIFIED_EMAIL;\n\n // Override errors set in the custom map.\n var customErrorMap = opt_customErrorMap || {};\n goog.object.extend(errorMap, customErrorMap);\n\n // Get detailed message if available.\n errorMessage = fireauth.RpcHandler.getErrorCodeDetails(serverErrorCode);\n\n // Handle backend errors where the error code can be a prefix of the message\n // (e.g. \"WEAK_PASSWORD : Password should be at least 6 characters\").\n // Use the details after the colon as the error message. If none available,\n // pass undefined, which will default to the client hard coded error messages.\n for (var prefixCode in errorMap) {\n if (serverErrorCode.indexOf(prefixCode) === 0) {\n return new fireauth.AuthError(errorMap[prefixCode], errorMessage);\n }\n }\n\n // No error message found, return the serialized response as the message.\n // This is likely to be an Apiary error for unexpected cases like keyExpired,\n // etc.\n if (!errorMessage && response) {\n errorMessage = fireauth.util.stringifyJSON(response);\n }\n // The backend returned some error we don't recognize; this is an error on\n // our side.\n return new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR, errorMessage);\n};\n\n\n/**\n * @param {string} serverMessage The server error code.\n * @return {string|undefined} The detailed error code message.\n */\nfireauth.RpcHandler.getErrorCodeDetails = function(serverMessage) {\n // Use the error details part as the autherror message.\n // For a message INVALID_CUSTOM_TOKEN : [error detail here],\n // The Auth error message should be [error detail here].\n // No space should be contained in the error code, otherwise no detailed error\n // message returned.\n var matches = serverMessage.match(/^[^\\s]+\\s*:\\s*([\\s\\S]*)$/);\n if (matches && matches.length > 1) {\n return matches[1];\n }\n return undefined;\n};\n\n\n/**\n * Gets the Apiary error from a backend response, if applicable.\n * @param {!Object} response The API response.\n * @return {?fireauth.AuthError} The error, if applicable.\n * @private\n */\nfireauth.RpcHandler.getApiaryError_ = function(response) {\n var error = response['error'] && response['error']['errors'] &&\n response['error']['errors'][0] || {};\n var reason = error['reason'] || '';\n\n var errorReasonMap = {\n 'keyInvalid': fireauth.authenum.Error.INVALID_API_KEY,\n 'ipRefererBlocked': fireauth.authenum.Error.APP_NOT_AUTHORIZED\n };\n\n if (errorReasonMap[reason]) {\n return new fireauth.AuthError(errorReasonMap[reason]);\n }\n\n return null;\n};\n\n\n/**\n * Gets the server error code from the response.\n * @param {!Object} resp The API response.\n * @return {string} The error code if present.\n * @private\n */\nfireauth.RpcHandler.getErrorCode_ = function(resp) {\n return (resp['error'] && resp['error']['message']) || '';\n};\n","// Copyright 2006 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 Low level handling of XMLHttpRequest.\n */\n\ngoog.provide('goog.net.DefaultXmlHttpFactory');\ngoog.provide('goog.net.XmlHttp');\ngoog.provide('goog.net.XmlHttp.OptionType');\ngoog.provide('goog.net.XmlHttp.ReadyState');\ngoog.provide('goog.net.XmlHttpDefines');\n\ngoog.require('goog.asserts');\ngoog.require('goog.net.WrapperXmlHttpFactory');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n/**\n * Static class for creating XMLHttpRequest objects.\n * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.\n */\ngoog.net.XmlHttp = function() {\n return goog.net.XmlHttp.factory_.createInstance();\n};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true bypasses the ActiveX probing code.\n * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip\n * out the ActiveX probing code from binaries. To achieve this, use\n * `goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR` instead.\n * TODO(ruilopes): Collapse both defines.\n */\ngoog.net.XmlHttp.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);\n\n\n/** @const */\ngoog.net.XmlHttpDefines = {};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true eliminates the ActiveX probing code.\n */\ngoog.net.XmlHttpDefines.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);\n\n\n/**\n * Gets the options to use with the XMLHttpRequest objects obtained using\n * the static methods.\n * @return {Object} The options.\n */\ngoog.net.XmlHttp.getOptions = function() {\n return goog.net.XmlHttp.factory_.getOptions();\n};\n\n\n/**\n * Type of options that an XmlHttp object can have.\n * @enum {number}\n */\ngoog.net.XmlHttp.OptionType = {\n /**\n * Whether a goog.nullFunction should be used to clear the onreadystatechange\n * handler instead of null.\n */\n USE_NULL_FUNCTION: 0,\n\n /**\n * NOTE(user): In IE if send() errors on a *local* request the readystate\n * is still changed to COMPLETE. We need to ignore it and allow the\n * try/catch around send() to pick up the error.\n */\n LOCAL_REQUEST_ERROR: 1,\n};\n\n\n/**\n * Status constants for XMLHTTP, matches:\n * https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx\n * @enum {number}\n */\ngoog.net.XmlHttp.ReadyState = {\n /**\n * Constant for when xmlhttprequest.readyState is uninitialized\n */\n UNINITIALIZED: 0,\n\n /**\n * Constant for when xmlhttprequest.readyState is loading.\n */\n LOADING: 1,\n\n /**\n * Constant for when xmlhttprequest.readyState is loaded.\n */\n LOADED: 2,\n\n /**\n * Constant for when xmlhttprequest.readyState is in an interactive state.\n */\n INTERACTIVE: 3,\n\n /**\n * Constant for when xmlhttprequest.readyState is completed\n */\n COMPLETE: 4,\n};\n\n\n/**\n * The global factory instance for creating XMLHttpRequest objects.\n * @type {goog.net.XmlHttpFactory}\n * @private\n */\ngoog.net.XmlHttp.factory_;\n\n\n/**\n * Sets the factories for creating XMLHttpRequest objects and their options.\n * @param {Function} factory The factory for XMLHttpRequest objects.\n * @param {Function} optionsFactory The factory for options.\n * @deprecated Use setGlobalFactory instead.\n */\ngoog.net.XmlHttp.setFactory = function(factory, optionsFactory) {\n goog.net.XmlHttp.setGlobalFactory(\n new goog.net.WrapperXmlHttpFactory(\n goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));\n};\n\n\n/**\n * Sets the global factory object.\n * @param {!goog.net.XmlHttpFactory} factory New global factory object.\n */\ngoog.net.XmlHttp.setGlobalFactory = function(factory) {\n goog.net.XmlHttp.factory_ = factory;\n};\n\n\n\n/**\n * Default factory to use when creating xhr objects. You probably shouldn't be\n * instantiating this directly, but rather using it via goog.net.XmlHttp.\n * @extends {goog.net.XmlHttpFactory}\n * @constructor\n */\ngoog.net.DefaultXmlHttpFactory = function() {\n goog.net.XmlHttpFactory.call(this);\n};\ngoog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {\n var progId = this.getProgId_();\n if (progId) {\n return new ActiveXObject(progId);\n } else {\n return new XMLHttpRequest();\n }\n};\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {\n var progId = this.getProgId_();\n var options = {};\n if (progId) {\n options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;\n options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;\n }\n return options;\n};\n\n\n/**\n * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.\n * @type {string|undefined}\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.ieProgId_;\n\n\n/**\n * Initialize the private state used by other functions.\n * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {\n if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||\n goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {\n return '';\n }\n\n // The following blog post describes what PROG IDs to use to create the\n // XMLHTTP object in Internet Explorer:\n // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx\n // However we do not (yet) fully trust that this will be OK for old versions\n // of IE on Win9x so we therefore keep the last 2.\n if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&\n typeof ActiveXObject != 'undefined') {\n // Candidate Active X types.\n var ACTIVE_X_IDENTS = [\n 'MSXML2.XMLHTTP.6.0',\n 'MSXML2.XMLHTTP.3.0',\n 'MSXML2.XMLHTTP',\n 'Microsoft.XMLHTTP',\n ];\n for (var i = 0; i < ACTIVE_X_IDENTS.length; i++) {\n var candidate = ACTIVE_X_IDENTS[i];\n\n try {\n new ActiveXObject(candidate);\n // NOTE(user): cannot assign progid and return candidate in one line\n // because JSCompiler complaings: BUG 658126\n this.ieProgId_ = candidate;\n return candidate;\n } catch (e) {\n // do nothing; try next choice\n }\n }\n\n // couldn't find any matches\n throw new Error(\n 'Could not create ActiveXObject. ActiveX might be disabled,' +\n ' or MSXML might not be installed');\n }\n\n return /** @type {string} */ (this.ieProgId_);\n};\n\n\n// Set the global factory to an instance of the default factory.\ngoog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 invalid origin error, a subclass of\n * fireauth.AuthError.\n */\n\n\ngoog.provide('fireauth.InvalidOriginError');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('goog.Uri');\ngoog.require('goog.string');\n\n\n\n/**\n * Invalid origin error that can be returned to the developer.\n * @param {string} origin The invalid domain name.\n * @constructor\n * @extends {fireauth.AuthError}\n */\nfireauth.InvalidOriginError = function(origin) {\n var code = fireauth.authenum.Error.INVALID_ORIGIN;\n var message = undefined;\n var uri = goog.Uri.parse(origin);\n // Get domain.\n var domain = uri.getDomain();\n // Get scheme.\n var scheme = uri.getScheme();\n // Only http, https and chrome-extension currently supported.\n if (scheme == 'chrome-extension') {\n // Chrome extension whitelisting.\n // Replace chrome-extension://CHROME_EXT_ID in error message template.\n message = goog.string.subs(\n fireauth.InvalidOriginError.CHROME_EXTENSION_MESSAGE_TEMPLATE_,\n domain);\n } else if (scheme == 'http' || scheme == 'https') {\n // Replace domain in error message template.\n message = goog.string.subs(\n fireauth.InvalidOriginError.HTTP_MESSAGE_TEMPLATE_,\n domain);\n } else {\n // Throw operation not supported when non http, https or Chrome extension\n // protocol.\n code = fireauth.authenum.Error.OPERATION_NOT_SUPPORTED;\n }\n fireauth.InvalidOriginError.base(this, 'constructor', code, message);\n};\ngoog.inherits(fireauth.InvalidOriginError, fireauth.AuthError);\n\n\n/** @private @const {string} The http invalid origin message template. */\nfireauth.InvalidOriginError.HTTP_MESSAGE_TEMPLATE_ = 'This domain (%s) is no' +\n 't authorized to run this operation. Add it to the OAuth redirect domain' +\n 's list in the Firebase console -> Auth section -> Sign in method tab.';\n\n\n/**\n * @private @const {string} The Chrome extension invalid origin message\n * template.\n */\nfireauth.InvalidOriginError.CHROME_EXTENSION_MESSAGE_TEMPLATE_ = 'This chrom' +\n 'e extension ID (chrome-extension://%s) is not authorized to run this op' +\n 'eration. Add it to the OAuth redirect domains list in the Firebase cons' +\n 'ole -> Auth section -> Sign in method tab.';\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Auth errors that include emails and an Auth\n * credential, a subclass of fireauth.AuthError.\n */\n\n\ngoog.provide('fireauth.AuthErrorWithCredential');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthProvider');\ngoog.require('fireauth.object');\ngoog.require('goog.object');\n\n\n/**\n * Error with email and credential that can be returned to the developer.\n * @param {fireauth.authenum.Error} code The error code.\n * @param {?fireauth.AuthErrorWithCredential.CredentialInfo=} opt_credentialInfo\n * Additional credential information to associate with the error.\n * @param {string=} opt_message The human-readable message.\n * @constructor\n * @extends {fireauth.AuthError}\n */\nfireauth.AuthErrorWithCredential =\n function(code, opt_credentialInfo, opt_message) {\n fireauth.AuthErrorWithCredential.base(\n this, 'constructor', code, opt_message);\n var credentialInfo = opt_credentialInfo || {};\n\n // These properties are public.\n if (credentialInfo.email) {\n fireauth.object.setReadonlyProperty(this, 'email', credentialInfo.email);\n }\n if (credentialInfo.phoneNumber) {\n fireauth.object.setReadonlyProperty(this, 'phoneNumber',\n credentialInfo.phoneNumber);\n }\n if (credentialInfo.credential) {\n fireauth.object.setReadonlyProperty(this, 'credential',\n credentialInfo.credential);\n }\n if (credentialInfo.tenantId) {\n fireauth.object.setReadonlyProperty(this, 'tenantId',\n credentialInfo.tenantId);\n }\n};\ngoog.inherits(fireauth.AuthErrorWithCredential, fireauth.AuthError);\n\n\n/**\n * Additional credential information to associate with an error, so that the\n * user does not have to execute the Auth flow again on linking errors.\n * @typedef {{\n * email: (?string|undefined),\n * phoneNumber: (?string|undefined),\n * credential: (?fireauth.AuthCredential|undefined),\n * tenantId: (?string|undefined),\n * }}\n */\nfireauth.AuthErrorWithCredential.CredentialInfo;\n\n\n/**\n * @return {!Object} The plain object form of the error.\n * @override\n */\nfireauth.AuthErrorWithCredential.prototype.toPlainObject = function() {\n var obj = {\n 'code': this['code'],\n 'message': this.message\n };\n if (this['email']) {\n obj['email'] = this['email'];\n }\n if (this['phoneNumber']) {\n obj['phoneNumber'] = this['phoneNumber'];\n }\n if (this['tenantId']) {\n obj['tenantId'] = this['tenantId'];\n }\n\n var credential = this['credential'] && this['credential'].toPlainObject();\n if (credential){\n goog.object.extend(obj, credential);\n }\n return obj;\n};\n\n\n/**\n * @return {!Object} The plain object form of the error. This is used by\n * JSON.toStringify() to return the stringified representation of the error;\n * @override\n */\nfireauth.AuthErrorWithCredential.prototype.toJSON = function() {\n // Return the plain object representation in case JSON.stringify is called on\n // an Auth error instance.\n return this.toPlainObject();\n};\n\n\n/**\n * @param {?Object|undefined} response The object response to convert to a\n * fireauth.AuthErrorWithCredential.\n * @return {?fireauth.AuthError} The error representation of the response.\n */\nfireauth.AuthErrorWithCredential.fromPlainObject = function(response) {\n // Code included.\n if (response['code']) {\n var code = response['code'] || '';\n // Remove prefix from name if available.\n if (code.indexOf(fireauth.AuthError.ERROR_CODE_PREFIX) == 0) {\n code = code.substring(fireauth.AuthError.ERROR_CODE_PREFIX.length);\n }\n\n // Credentials and tenant ID in response.\n var credentialInfo = {\n credential: fireauth.AuthProvider.getCredentialFromResponse(response),\n tenantId: response['tenantId']\n };\n if (response['email']) {\n credentialInfo.email = response['email'];\n } else if (response['phoneNumber']) {\n credentialInfo.phoneNumber = response['phoneNumber'];\n } else if (!credentialInfo.credential) {\n // Neither email, phone number or credentials are set; return a generic\n // error.\n return new fireauth.AuthError(code, response['message'] || undefined);\n }\n\n return new fireauth.AuthErrorWithCredential(code, credentialInfo,\n response['message']);\n }\n // No error or invalid response.\n return null;\n};\n","// Copyright 2010 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 Interface for a factory for creating XMLHttpRequest objects\n * and metadata about them.\n */\n\ngoog.provide('goog.net.XmlHttpFactory');\n\n/** @suppress {extraRequire} Typedef. */\ngoog.require('goog.net.XhrLike');\n\n\n\n/**\n * Abstract base class for an XmlHttpRequest factory.\n * @constructor\n */\ngoog.net.XmlHttpFactory = function() {};\n\n\n/**\n * Cache of options - we only actually call internalGetOptions once.\n * @type {?Object}\n * @private\n */\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\n\n\n/**\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\n */\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\n\n\n/**\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n */\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\n return this.cachedOptions_ ||\n (this.cachedOptions_ = this.internalGetOptions());\n};\n\n\n/**\n * Override this method in subclasses to preserve the caching offered by\n * getOptions().\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n * @protected\n */\ngoog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;\n","// Copyright 2013 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 This file contain classes that add support for cross-domain XHR\n * requests (see http://www.w3.org/TR/cors/). Most modern browsers are able to\n * use a regular XMLHttpRequest for that, but IE 8 use XDomainRequest object\n * instead. This file provides an adapter from this object to a goog.net.XhrLike\n * and a factory to allow using this with a goog.net.XhrIo instance.\n *\n * IE 7 and older versions are not supported (given that they do not support\n * CORS requests).\n */\ngoog.provide('goog.net.CorsXmlHttpFactory');\ngoog.provide('goog.net.IeCorsXhrAdapter');\n\ngoog.require('goog.net.HttpStatus');\ngoog.require('goog.net.XhrLike');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * A factory of XML http request objects that supports cross domain requests.\n * This class should be instantiated and passed as the parameter of a\n * goog.net.XhrIo constructor to allow cross-domain requests in every browser.\n *\n * @extends {goog.net.XmlHttpFactory}\n * @constructor\n * @final\n */\ngoog.net.CorsXmlHttpFactory = function() {\n goog.net.XmlHttpFactory.call(this);\n};\ngoog.inherits(goog.net.CorsXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.CorsXmlHttpFactory.prototype.createInstance = function() {\n var xhr = new XMLHttpRequest();\n if (('withCredentials' in xhr)) {\n return xhr;\n } else if (typeof XDomainRequest != 'undefined') {\n return new goog.net.IeCorsXhrAdapter();\n } else {\n throw new Error('Unsupported browser');\n }\n};\n\n\n/** @override */\ngoog.net.CorsXmlHttpFactory.prototype.internalGetOptions = function() {\n return {};\n};\n\n\n\n/**\n * An adapter around Internet Explorer's XDomainRequest object that makes it\n * look like a standard XMLHttpRequest. This can be used instead of\n * XMLHttpRequest to support CORS.\n *\n * @implements {goog.net.XhrLike}\n * @constructor\n * @struct\n * @final\n */\ngoog.net.IeCorsXhrAdapter = function() {\n /**\n * The underlying XDomainRequest used to make the HTTP request.\n * @type {!XDomainRequest}\n * @private\n */\n this.xdr_ = new XDomainRequest();\n\n /**\n * The simulated ready state.\n * @type {number}\n */\n this.readyState = goog.net.XmlHttp.ReadyState.UNINITIALIZED;\n\n /**\n * The simulated ready state change callback function.\n * @type {?function()|undefined}\n */\n this.onreadystatechange = null;\n\n /** @override */\n this.response = '';\n\n /**\n * The simulated response text parameter.\n * @type {string}\n */\n this.responseText = '';\n\n /**\n * This implementation only supports text response.\n * @type {string}\n * @override\n */\n this.responseType = '';\n\n /**\n * The simulated status code\n * @type {number}\n */\n this.status = -1;\n\n /** @override */\n this.responseXML = null;\n\n /** @override */\n this.statusText = '';\n\n this.xdr_.onload = goog.bind(this.handleLoad_, this);\n this.xdr_.onerror = goog.bind(this.handleError_, this);\n this.xdr_.onprogress = goog.bind(this.handleProgress_, this);\n this.xdr_.ontimeout = goog.bind(this.handleTimeout_, this);\n};\n\n\n/**\n * Opens a connection to the provided URL.\n * @param {string} method The HTTP method to use. Valid methods include GET and\n * POST.\n * @param {string} url The URL to contact. The authority of this URL must match\n * the authority of the current page's URL (e.g. http or https).\n * @param {?boolean=} opt_async Whether the request is asynchronous, defaulting\n * to true. XDomainRequest does not support syncronous requests, so setting\n * it to false will actually raise an exception.\n * @override\n */\ngoog.net.IeCorsXhrAdapter.prototype.open = function(method, url, opt_async) {\n if (opt_async != null && (!opt_async)) {\n throw new Error('Only async requests are supported.');\n }\n this.xdr_.open(method, url);\n};\n\n\n/**\n * Sends the request to the remote server. Before calling this function, always\n * call {@link open}.\n * @param {(ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string)=}\n * opt_content The content to send as POSTDATA, if any. Only string data is\n * supported by this implementation.\n * @override\n */\ngoog.net.IeCorsXhrAdapter.prototype.send = function(opt_content) {\n if (opt_content) {\n if (typeof opt_content == 'string') {\n this.xdr_.send(opt_content);\n } else {\n throw new Error('Only string data is supported');\n }\n } else {\n this.xdr_.send();\n }\n};\n\n\n/**\n * @override\n */\ngoog.net.IeCorsXhrAdapter.prototype.abort = function() {\n this.xdr_.abort();\n};\n\n\n/**\n * Sets a request header to send to the remote server. Because this\n * implementation does not support request headers, this function does nothing.\n * @param {string} key The name of the HTTP header to set. Ignored.\n * @param {string} value The value to set for the HTTP header. Ignored.\n * @override\n */\ngoog.net.IeCorsXhrAdapter.prototype.setRequestHeader = function(key, value) {\n // Unsupported; ignore the header.\n};\n\n\n/**\n * Returns the value of the response header identified by key. This\n * implementation only supports the 'content-type' header.\n * @param {string} key The request header to fetch. If this parameter is set to\n * 'content-type' (case-insensitive), this function returns the value of\n * the 'content-type' request header. If this parameter is set to any other\n * value, this function always returns an empty string.\n * @return {string} The value of the response header, or an empty string if key\n * is not 'content-type' (case-insensitive).\n * @override\n */\ngoog.net.IeCorsXhrAdapter.prototype.getResponseHeader = function(key) {\n if (key.toLowerCase() == 'content-type') {\n return this.xdr_.contentType;\n }\n return '';\n};\n\n\n/**\n * Handles a request that has fully loaded successfully.\n * @private\n */\ngoog.net.IeCorsXhrAdapter.prototype.handleLoad_ = function() {\n // IE only calls onload if the status is 200, so the status code must be OK.\n this.status = goog.net.HttpStatus.OK;\n this.response = this.responseText = this.xdr_.responseText;\n this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);\n};\n\n\n/**\n * Handles a request that has failed to load.\n * @private\n */\ngoog.net.IeCorsXhrAdapter.prototype.handleError_ = function() {\n // IE doesn't tell us what the status code actually is (other than the fact\n // that it is not 200), so simulate an INTERNAL_SERVER_ERROR.\n this.status = goog.net.HttpStatus.INTERNAL_SERVER_ERROR;\n this.response = this.responseText = '';\n this.setReadyState_(goog.net.XmlHttp.ReadyState.COMPLETE);\n};\n\n\n/**\n * Handles a request that timed out.\n * @private\n */\ngoog.net.IeCorsXhrAdapter.prototype.handleTimeout_ = function() {\n this.handleError_();\n};\n\n\n/**\n * Handles a request that is in the process of loading.\n * @private\n */\ngoog.net.IeCorsXhrAdapter.prototype.handleProgress_ = function() {\n // IE only calls onprogress if the status is 200, so the status code must be\n // OK.\n this.status = goog.net.HttpStatus.OK;\n this.setReadyState_(goog.net.XmlHttp.ReadyState.LOADING);\n};\n\n\n/**\n * Sets this XHR's ready state and fires the onreadystatechange listener (if one\n * is set).\n * @param {number} readyState The new ready state.\n * @private\n */\ngoog.net.IeCorsXhrAdapter.prototype.setReadyState_ = function(readyState) {\n this.readyState = readyState;\n if (this.onreadystatechange) {\n this.onreadystatechange();\n }\n};\n\n\n/**\n * Returns the response headers from the server. This implemntation only returns\n * the 'content-type' header.\n * @return {string} The headers returned from the server.\n * @override\n */\ngoog.net.IeCorsXhrAdapter.prototype.getAllResponseHeaders = function() {\n return 'content-type: ' + this.xdr_.contentType;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the LogRecord class. Please minimize\n * dependencies this file has on other closure classes as any dependency it\n * takes won't be able to use the logging infrastructure.\n */\n\ngoog.provide('goog.debug.LogRecord');\n\n\n\n/**\n * LogRecord objects are used to pass logging requests between\n * the logging framework and individual log Handlers.\n * @constructor\n * @param {goog.debug.Logger.Level} level One of the level identifiers.\n * @param {string} msg The string message.\n * @param {string} loggerName The name of the source logger.\n * @param {number=} opt_time Time this log record was created if other than now.\n * If 0, we use #goog.now.\n * @param {number=} opt_sequenceNumber Sequence number of this log record. This\n * should only be passed in when restoring a log record from persistence.\n */\ngoog.debug.LogRecord = function(\n level, msg, loggerName, opt_time, opt_sequenceNumber) {\n this.reset(level, msg, loggerName, opt_time, opt_sequenceNumber);\n};\n\n\n/**\n * Time the LogRecord was created.\n * @type {number}\n * @private\n */\ngoog.debug.LogRecord.prototype.time_;\n\n\n/**\n * Level of the LogRecord\n * @type {goog.debug.Logger.Level}\n * @private\n */\ngoog.debug.LogRecord.prototype.level_;\n\n\n/**\n * Message associated with the record\n * @type {string}\n * @private\n */\ngoog.debug.LogRecord.prototype.msg_;\n\n\n/**\n * Name of the logger that created the record.\n * @type {string}\n * @private\n */\ngoog.debug.LogRecord.prototype.loggerName_;\n\n\n/**\n * Sequence number for the LogRecord. Each record has a unique sequence number\n * that is greater than all log records created before it.\n * @type {number}\n * @private\n */\ngoog.debug.LogRecord.prototype.sequenceNumber_ = 0;\n\n\n/**\n * Exception associated with the record\n * @type {?Object}\n * @private\n */\ngoog.debug.LogRecord.prototype.exception_ = null;\n\n\n/**\n * @define {boolean} Whether to enable log sequence numbers.\n */\ngoog.debug.LogRecord.ENABLE_SEQUENCE_NUMBERS =\n goog.define('goog.debug.LogRecord.ENABLE_SEQUENCE_NUMBERS', true);\n\n\n/**\n * A sequence counter for assigning increasing sequence numbers to LogRecord\n * objects.\n * @type {number}\n * @private\n */\ngoog.debug.LogRecord.nextSequenceNumber_ = 0;\n\n\n/**\n * Sets all fields of the log record.\n * @param {goog.debug.Logger.Level} level One of the level identifiers.\n * @param {string} msg The string message.\n * @param {string} loggerName The name of the source logger.\n * @param {number=} opt_time Time this log record was created if other than now.\n * If 0, we use #goog.now.\n * @param {number=} opt_sequenceNumber Sequence number of this log record. This\n * should only be passed in when restoring a log record from persistence.\n */\ngoog.debug.LogRecord.prototype.reset = function(\n level, msg, loggerName, opt_time, opt_sequenceNumber) {\n if (goog.debug.LogRecord.ENABLE_SEQUENCE_NUMBERS) {\n this.sequenceNumber_ = typeof opt_sequenceNumber == 'number' ?\n opt_sequenceNumber :\n goog.debug.LogRecord.nextSequenceNumber_++;\n }\n\n this.time_ = opt_time || goog.now();\n this.level_ = level;\n this.msg_ = msg;\n this.loggerName_ = loggerName;\n delete this.exception_;\n};\n\n\n/**\n * Get the source Logger's name.\n *\n * @return {string} source logger name (may be null).\n */\ngoog.debug.LogRecord.prototype.getLoggerName = function() {\n return this.loggerName_;\n};\n\n\n/**\n * Get the exception that is part of the log record.\n *\n * @return {Object} the exception.\n */\ngoog.debug.LogRecord.prototype.getException = function() {\n return this.exception_;\n};\n\n\n/**\n * Set the exception that is part of the log record.\n *\n * @param {Object} exception the exception.\n */\ngoog.debug.LogRecord.prototype.setException = function(exception) {\n this.exception_ = exception;\n};\n\n\n/**\n * Get the source Logger's name.\n *\n * @param {string} loggerName source logger name (may be null).\n */\ngoog.debug.LogRecord.prototype.setLoggerName = function(loggerName) {\n this.loggerName_ = loggerName;\n};\n\n\n/**\n * Get the logging message level, for example Level.SEVERE.\n * @return {goog.debug.Logger.Level} the logging message level.\n */\ngoog.debug.LogRecord.prototype.getLevel = function() {\n return this.level_;\n};\n\n\n/**\n * Set the logging message level, for example Level.SEVERE.\n * @param {goog.debug.Logger.Level} level the logging message level.\n */\ngoog.debug.LogRecord.prototype.setLevel = function(level) {\n this.level_ = level;\n};\n\n\n/**\n * Get the \"raw\" log message, before localization or formatting.\n *\n * @return {string} the raw message string.\n */\ngoog.debug.LogRecord.prototype.getMessage = function() {\n return this.msg_;\n};\n\n\n/**\n * Set the \"raw\" log message, before localization or formatting.\n *\n * @param {string} msg the raw message string.\n */\ngoog.debug.LogRecord.prototype.setMessage = function(msg) {\n this.msg_ = msg;\n};\n\n\n/**\n * Get event time in milliseconds since 1970.\n *\n * @return {number} event time in millis since 1970.\n */\ngoog.debug.LogRecord.prototype.getMillis = function() {\n return this.time_;\n};\n\n\n/**\n * Set event time in milliseconds since 1970.\n *\n * @param {number} time event time in millis since 1970.\n */\ngoog.debug.LogRecord.prototype.setMillis = function(time) {\n this.time_ = time;\n};\n\n\n/**\n * Get the sequence number.\n * <p>\n * Sequence numbers are normally assigned in the LogRecord\n * constructor, which assigns unique sequence numbers to\n * each new LogRecord in increasing order.\n * @return {number} the sequence number.\n */\ngoog.debug.LogRecord.prototype.getSequenceNumber = function() {\n return this.sequenceNumber_;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the Logger class. Please minimize dependencies\n * this file has on other closure classes as any dependency it takes won't be\n * able to use the logging infrastructure.\n *\n * @see ../demos/debug.html\n */\n\ngoog.provide('goog.debug.LogManager');\ngoog.provide('goog.debug.Loggable');\ngoog.provide('goog.debug.Logger');\ngoog.provide('goog.debug.Logger.Level');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.debug');\ngoog.require('goog.debug.LogBuffer');\ngoog.require('goog.debug.LogRecord');\n\n\n/**\n * A message value that can be handled by a Logger.\n *\n * Functions are treated like callbacks, but are only called when the event's\n * log level is enabled. This is useful for logging messages that are expensive\n * to construct.\n *\n * @typedef {string|function(): string}\n */\ngoog.debug.Loggable;\n\n\n\n/**\n * The Logger is an object used for logging debug messages. Loggers are\n * normally named, using a hierarchical dot-separated namespace. Logger names\n * can be arbitrary strings, but they should normally be based on the package\n * name or class name of the logged component, such as goog.net.BrowserChannel.\n *\n * The Logger object is loosely based on the java class\n * java.util.logging.Logger. It supports different levels of filtering for\n * different loggers.\n *\n * The logger object should never be instantiated by application code. It\n * should always use the goog.debug.Logger.getLogger function.\n *\n * @constructor\n * @param {string} name The name of the Logger.\n * @final\n */\ngoog.debug.Logger = function(name) {\n /**\n * Name of the Logger. Generally a dot-separated namespace\n * @private {string}\n */\n this.name_ = name;\n\n /**\n * Parent Logger.\n * @private {?goog.debug.Logger}\n */\n this.parent_ = null;\n\n /**\n * Level that this logger only filters above. Null indicates it should\n * inherit from the parent.\n * @private {?goog.debug.Logger.Level}\n */\n this.level_ = null;\n\n /**\n * Map of children loggers. The keys are the leaf names of the children and\n * the values are the child loggers.\n * @private {?Object}\n */\n this.children_ = null;\n\n /**\n * Handlers that are listening to this logger.\n * @private {?Array<?Function>}\n */\n this.handlers_ = null;\n};\n\n\n/** @const */\ngoog.debug.Logger.ROOT_LOGGER_NAME = '';\n\n\n/**\n * @define {boolean} Toggles whether loggers other than the root logger can have\n * log handlers attached to them and whether they can have their log level\n * set. Logging is a bit faster when this is set to false.\n */\ngoog.debug.Logger.ENABLE_HIERARCHY =\n goog.define('goog.debug.Logger.ENABLE_HIERARCHY', true);\n\n\n/**\n * @define {boolean} Toggles whether active log statements are also recorded\n * to the profiler.\n */\ngoog.debug.Logger.ENABLE_PROFILER_LOGGING =\n goog.define('goog.debug.Logger.ENABLE_PROFILER_LOGGING', false);\n\n\nif (!goog.debug.Logger.ENABLE_HIERARCHY) {\n /**\n * @type {!Array<Function>}\n * @private\n */\n goog.debug.Logger.rootHandlers_ = [];\n\n\n /**\n * @type {goog.debug.Logger.Level}\n * @private\n */\n goog.debug.Logger.rootLevel_;\n}\n\n\n\n/**\n * The Level class defines a set of standard logging levels that\n * can be used to control logging output. The logging Level objects\n * are ordered and are specified by ordered integers. Enabling logging\n * at a given level also enables logging at all higher levels.\n * <p>\n * Clients should normally use the predefined Level constants such\n * as Level.SEVERE.\n * <p>\n * The levels in descending order are:\n * <ul>\n * <li>SEVERE (highest value)\n * <li>WARNING\n * <li>INFO\n * <li>CONFIG\n * <li>FINE\n * <li>FINER\n * <li>FINEST (lowest value)\n * </ul>\n * In addition there is a level OFF that can be used to turn\n * off logging, and a level ALL that can be used to enable\n * logging of all messages.\n *\n * @param {string} name The name of the level.\n * @param {number} value The numeric value of the level.\n * @constructor\n * @final\n */\ngoog.debug.Logger.Level = function(name, value) {\n /**\n * The name of the level\n * @type {string}\n */\n this.name = name;\n\n /**\n * The numeric value of the level\n * @type {number}\n */\n this.value = value;\n};\n\n\n/**\n * @return {string} String representation of the logger level.\n * @override\n */\ngoog.debug.Logger.Level.prototype.toString = function() {\n return this.name;\n};\n\n\n/**\n * OFF is a special level that can be used to turn off logging.\n * This level is initialized to <CODE>Infinity</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.OFF = new goog.debug.Logger.Level('OFF', Infinity);\n\n\n/**\n * SHOUT is a message level for extra debugging loudness.\n * This level is initialized to <CODE>1200</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.SHOUT = new goog.debug.Logger.Level('SHOUT', 1200);\n\n\n/**\n * SEVERE is a message level indicating a serious failure.\n * This level is initialized to <CODE>1000</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.SEVERE = new goog.debug.Logger.Level('SEVERE', 1000);\n\n\n/**\n * WARNING is a message level indicating a potential problem.\n * This level is initialized to <CODE>900</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.WARNING = new goog.debug.Logger.Level('WARNING', 900);\n\n\n/**\n * INFO is a message level for informational messages.\n * This level is initialized to <CODE>800</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.INFO = new goog.debug.Logger.Level('INFO', 800);\n\n\n/**\n * CONFIG is a message level for static configuration messages.\n * This level is initialized to <CODE>700</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.CONFIG = new goog.debug.Logger.Level('CONFIG', 700);\n\n\n/**\n * FINE is a message level providing tracing information.\n * This level is initialized to <CODE>500</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.FINE = new goog.debug.Logger.Level('FINE', 500);\n\n\n/**\n * FINER indicates a fairly detailed tracing message.\n * This level is initialized to <CODE>400</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.FINER = new goog.debug.Logger.Level('FINER', 400);\n\n/**\n * FINEST indicates a highly detailed tracing message.\n * This level is initialized to <CODE>300</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\n\ngoog.debug.Logger.Level.FINEST = new goog.debug.Logger.Level('FINEST', 300);\n\n\n/**\n * ALL indicates that all messages should be logged.\n * This level is initialized to <CODE>0</CODE>.\n * @type {!goog.debug.Logger.Level}\n */\ngoog.debug.Logger.Level.ALL = new goog.debug.Logger.Level('ALL', 0);\n\n\n/**\n * The predefined levels.\n * @type {!Array<!goog.debug.Logger.Level>}\n * @final\n */\ngoog.debug.Logger.Level.PREDEFINED_LEVELS = [\n goog.debug.Logger.Level.OFF, goog.debug.Logger.Level.SHOUT,\n goog.debug.Logger.Level.SEVERE, goog.debug.Logger.Level.WARNING,\n goog.debug.Logger.Level.INFO, goog.debug.Logger.Level.CONFIG,\n goog.debug.Logger.Level.FINE, goog.debug.Logger.Level.FINER,\n goog.debug.Logger.Level.FINEST, goog.debug.Logger.Level.ALL\n];\n\n\n/**\n * A lookup map used to find the level object based on the name or value of\n * the level object.\n * @type {?Object}\n * @private\n */\ngoog.debug.Logger.Level.predefinedLevelsCache_ = null;\n\n\n/**\n * Creates the predefined levels cache and populates it.\n * @private\n */\ngoog.debug.Logger.Level.createPredefinedLevelsCache_ = function() {\n goog.debug.Logger.Level.predefinedLevelsCache_ = {};\n for (var i = 0, level; level = goog.debug.Logger.Level.PREDEFINED_LEVELS[i];\n i++) {\n goog.debug.Logger.Level.predefinedLevelsCache_[level.value] = level;\n goog.debug.Logger.Level.predefinedLevelsCache_[level.name] = level;\n }\n};\n\n\n/**\n * Gets the predefined level with the given name.\n * @param {string} name The name of the level.\n * @return {goog.debug.Logger.Level} The level, or null if none found.\n */\ngoog.debug.Logger.Level.getPredefinedLevel = function(name) {\n if (!goog.debug.Logger.Level.predefinedLevelsCache_) {\n goog.debug.Logger.Level.createPredefinedLevelsCache_();\n }\n\n return goog.debug.Logger.Level.predefinedLevelsCache_[name] || null;\n};\n\n\n/**\n * Gets the highest predefined level <= #value.\n * @param {number} value Level value.\n * @return {goog.debug.Logger.Level} The level, or null if none found.\n */\ngoog.debug.Logger.Level.getPredefinedLevelByValue = function(value) {\n if (!goog.debug.Logger.Level.predefinedLevelsCache_) {\n goog.debug.Logger.Level.createPredefinedLevelsCache_();\n }\n\n if (value in /** @type {!Object} */ (\n goog.debug.Logger.Level.predefinedLevelsCache_)) {\n return goog.debug.Logger.Level.predefinedLevelsCache_[value];\n }\n\n for (var i = 0; i < goog.debug.Logger.Level.PREDEFINED_LEVELS.length; ++i) {\n var level = goog.debug.Logger.Level.PREDEFINED_LEVELS[i];\n if (level.value <= value) {\n return level;\n }\n }\n return null;\n};\n\n\n/**\n * Finds or creates a logger for a named subsystem. If a logger has already been\n * created with the given name it is returned. Otherwise a new logger is\n * created. If a new logger is created its log level will be configured based\n * on the LogManager configuration and it will configured to also send logging\n * output to its parent's handlers. It will be registered in the LogManager\n * global namespace.\n *\n * @param {string} name A name for the logger. This should be a dot-separated\n * name and should normally be based on the package name or class name of the\n * subsystem, such as goog.net.BrowserChannel.\n * @return {!goog.debug.Logger} The named logger.\n * @deprecated use {@link goog.log} instead.\n */\ngoog.debug.Logger.getLogger = function(name) {\n return goog.debug.LogManager.getLogger(name);\n};\n\n\n/**\n * Logs a message to profiling tools, if available.\n * {@see https://developers.google.com/web-toolkit/speedtracer/logging-api}\n * {@see http://msdn.microsoft.com/en-us/library/dd433074(VS.85).aspx}\n * @param {string} msg The message to log.\n */\ngoog.debug.Logger.logToProfilers = function(msg) {\n // Some browsers also log timeStamp calls to the console, only log\n // if actually asked.\n if (goog.debug.Logger.ENABLE_PROFILER_LOGGING) {\n var msWriteProfilerMark = goog.global['msWriteProfilerMark'];\n if (msWriteProfilerMark) {\n // Logs a message to the Microsoft profiler\n // On IE, console['timeStamp'] may output to console\n msWriteProfilerMark(msg);\n return;\n }\n\n // Using goog.global, as loggers might be used in window-less contexts.\n var console = goog.global['console'];\n if (console && console['timeStamp']) {\n // Logs a message to Firebug, Web Inspector, SpeedTracer, etc.\n console['timeStamp'](msg);\n }\n }\n};\n\n\n/**\n * Gets the name of this logger.\n * @return {string} The name of this logger.\n */\ngoog.debug.Logger.prototype.getName = function() {\n return this.name_;\n};\n\n\n/**\n * Adds a handler to the logger. This doesn't use the event system because\n * we want to be able to add logging to the event system.\n * @param {Function} handler Handler function to add.\n */\ngoog.debug.Logger.prototype.addHandler = function(handler) {\n if (goog.debug.LOGGING_ENABLED) {\n if (goog.debug.Logger.ENABLE_HIERARCHY) {\n if (!this.handlers_) {\n this.handlers_ = [];\n }\n this.handlers_.push(handler);\n } else {\n goog.asserts.assert(\n !this.name_, 'Cannot call addHandler on a non-root logger when ' +\n 'goog.debug.Logger.ENABLE_HIERARCHY is false.');\n goog.debug.Logger.rootHandlers_.push(handler);\n }\n }\n};\n\n\n/**\n * Removes a handler from the logger. This doesn't use the event system because\n * we want to be able to add logging to the event system.\n * @param {Function} handler Handler function to remove.\n * @return {boolean} Whether the handler was removed.\n */\ngoog.debug.Logger.prototype.removeHandler = function(handler) {\n if (goog.debug.LOGGING_ENABLED) {\n var handlers = goog.debug.Logger.ENABLE_HIERARCHY ?\n this.handlers_ :\n goog.debug.Logger.rootHandlers_;\n return !!handlers && goog.array.remove(handlers, handler);\n } else {\n return false;\n }\n};\n\n\n/**\n * Returns the parent of this logger.\n * @return {goog.debug.Logger} The parent logger or null if this is the root.\n */\ngoog.debug.Logger.prototype.getParent = function() {\n return this.parent_;\n};\n\n\n/**\n * Returns the children of this logger as a map of the child name to the logger.\n * @return {!Object} The map where the keys are the child leaf names and the\n * values are the Logger objects.\n */\ngoog.debug.Logger.prototype.getChildren = function() {\n if (!this.children_) {\n this.children_ = {};\n }\n return this.children_;\n};\n\n\n/**\n * Set the log level specifying which message levels will be logged by this\n * logger. Message levels lower than this value will be discarded.\n * The level value Level.OFF can be used to turn off logging. If the new level\n * is null, it means that this node should inherit its level from its nearest\n * ancestor with a specific (non-null) level value.\n *\n * @param {goog.debug.Logger.Level} level The new level.\n */\ngoog.debug.Logger.prototype.setLevel = function(level) {\n if (goog.debug.LOGGING_ENABLED) {\n if (goog.debug.Logger.ENABLE_HIERARCHY) {\n this.level_ = level;\n } else {\n goog.asserts.assert(\n !this.name_, 'Cannot call setLevel() on a non-root logger when ' +\n 'goog.debug.Logger.ENABLE_HIERARCHY is false.');\n goog.debug.Logger.rootLevel_ = level;\n }\n }\n};\n\n\n/**\n * Gets the log level specifying which message levels will be logged by this\n * logger. Message levels lower than this value will be discarded.\n * The level value Level.OFF can be used to turn off logging. If the level\n * is null, it means that this node should inherit its level from its nearest\n * ancestor with a specific (non-null) level value.\n *\n * @return {goog.debug.Logger.Level} The level.\n */\ngoog.debug.Logger.prototype.getLevel = function() {\n return goog.debug.LOGGING_ENABLED ? this.level_ : goog.debug.Logger.Level.OFF;\n};\n\n\n/**\n * Returns the effective level of the logger based on its ancestors' levels.\n * @return {goog.debug.Logger.Level} The level.\n */\ngoog.debug.Logger.prototype.getEffectiveLevel = function() {\n if (!goog.debug.LOGGING_ENABLED) {\n return goog.debug.Logger.Level.OFF;\n }\n\n if (!goog.debug.Logger.ENABLE_HIERARCHY) {\n return goog.debug.Logger.rootLevel_;\n }\n if (this.level_) {\n return this.level_;\n }\n if (this.parent_) {\n return this.parent_.getEffectiveLevel();\n }\n goog.asserts.fail('Root logger has no level set.');\n return null;\n};\n\n\n/**\n * Checks if a message of the given level would actually be logged by this\n * logger. This check is based on the Loggers effective level, which may be\n * inherited from its parent.\n * @param {goog.debug.Logger.Level} level The level to check.\n * @return {boolean} Whether the message would be logged.\n */\ngoog.debug.Logger.prototype.isLoggable = function(level) {\n return goog.debug.LOGGING_ENABLED &&\n level.value >= this.getEffectiveLevel().value;\n};\n\n\n/**\n * Logs a message. If the logger is currently enabled for the\n * given message level then the given message is forwarded to all the\n * registered output Handler objects.\n * @param {goog.debug.Logger.Level} level One of the level identifiers.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error|Object=} opt_exception An exception associated with the\n * message.\n */\ngoog.debug.Logger.prototype.log = function(level, msg, opt_exception) {\n // java caches the effective level, not sure it's necessary here\n if (goog.debug.LOGGING_ENABLED && this.isLoggable(level)) {\n // Message callbacks can be useful when a log message is expensive to build.\n if (goog.isFunction(msg)) {\n msg = msg();\n }\n\n this.doLogRecord_(this.getLogRecord(level, msg, opt_exception));\n }\n};\n\n\n/**\n * Creates a new log record and adds the exception (if present) to it.\n * @param {goog.debug.Logger.Level} level One of the level identifiers.\n * @param {string} msg The string message.\n * @param {Error|Object=} opt_exception An exception associated with the\n * message.\n * @return {!goog.debug.LogRecord} A log record.\n * @suppress {es5Strict}\n */\ngoog.debug.Logger.prototype.getLogRecord = function(level, msg, opt_exception) {\n if (goog.debug.LogBuffer.isBufferingEnabled()) {\n var logRecord =\n goog.debug.LogBuffer.getInstance().addRecord(level, msg, this.name_);\n } else {\n logRecord = new goog.debug.LogRecord(level, String(msg), this.name_);\n }\n if (opt_exception) {\n logRecord.setException(opt_exception);\n }\n return logRecord;\n};\n\n\n/**\n * Logs a message at the Logger.Level.SHOUT level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.shout = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.SHOUT, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Logger.Level.SEVERE level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.severe = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.SEVERE, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Logger.Level.WARNING level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.warning = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.WARNING, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Logger.Level.INFO level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.info = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.INFO, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Logger.Level.CONFIG level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.config = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.CONFIG, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Logger.Level.FINE level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.fine = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.FINE, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Logger.Level.FINER level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.finer = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.FINER, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Logger.Level.FINEST level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.debug.Logger.prototype.finest = function(msg, opt_exception) {\n if (goog.debug.LOGGING_ENABLED) {\n this.log(goog.debug.Logger.Level.FINEST, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a LogRecord. If the logger is currently enabled for the\n * given message level then the given message is forwarded to all the\n * registered output Handler objects.\n * @param {goog.debug.LogRecord} logRecord A log record to log.\n */\ngoog.debug.Logger.prototype.logRecord = function(logRecord) {\n if (goog.debug.LOGGING_ENABLED && this.isLoggable(logRecord.getLevel())) {\n this.doLogRecord_(logRecord);\n }\n};\n\n\n/**\n * Logs a LogRecord.\n * @param {goog.debug.LogRecord} logRecord A log record to log.\n * @private\n */\ngoog.debug.Logger.prototype.doLogRecord_ = function(logRecord) {\n if (goog.debug.Logger.ENABLE_PROFILER_LOGGING) {\n goog.debug.Logger.logToProfilers('log:' + logRecord.getMessage());\n }\n if (goog.debug.Logger.ENABLE_HIERARCHY) {\n var target = this;\n while (target) {\n target.callPublish_(logRecord);\n target = target.getParent();\n }\n } else {\n for (var i = 0, handler; handler = goog.debug.Logger.rootHandlers_[i++];) {\n handler(logRecord);\n }\n }\n};\n\n\n/**\n * Calls the handlers for publish.\n * @param {goog.debug.LogRecord} logRecord The log record to publish.\n * @private\n */\ngoog.debug.Logger.prototype.callPublish_ = function(logRecord) {\n if (this.handlers_) {\n for (var i = 0, handler; handler = this.handlers_[i]; i++) {\n handler(logRecord);\n }\n }\n};\n\n\n/**\n * Sets the parent of this logger. This is used for setting up the logger tree.\n * @param {goog.debug.Logger} parent The parent logger.\n * @private\n */\ngoog.debug.Logger.prototype.setParent_ = function(parent) {\n this.parent_ = parent;\n};\n\n\n/**\n * Adds a child to this logger. This is used for setting up the logger tree.\n * @param {string} name The leaf name of the child.\n * @param {goog.debug.Logger} logger The child logger.\n * @private\n */\ngoog.debug.Logger.prototype.addChild_ = function(name, logger) {\n this.getChildren()[name] = logger;\n};\n\n\n/**\n * There is a single global LogManager object that is used to maintain a set of\n * shared state about Loggers and log services. This is loosely based on the\n * java class java.util.logging.LogManager.\n * @const\n */\ngoog.debug.LogManager = {};\n\n\n/**\n * Map of logger names to logger objects.\n *\n * @type {!Object<string, !goog.debug.Logger>}\n * @private\n */\ngoog.debug.LogManager.loggers_ = {};\n\n\n/**\n * The root logger which is the root of the logger tree.\n * @type {?goog.debug.Logger}\n * @private\n */\ngoog.debug.LogManager.rootLogger_ = null;\n\n\n/**\n * Initializes the LogManager if not already initialized.\n */\ngoog.debug.LogManager.initialize = function() {\n if (!goog.debug.LogManager.rootLogger_) {\n goog.debug.LogManager.rootLogger_ =\n new goog.debug.Logger(goog.debug.Logger.ROOT_LOGGER_NAME);\n goog.debug.LogManager.loggers_[goog.debug.Logger.ROOT_LOGGER_NAME] =\n goog.debug.LogManager.rootLogger_;\n goog.debug.LogManager.rootLogger_.setLevel(goog.debug.Logger.Level.CONFIG);\n }\n};\n\n\n/**\n * Returns all the loggers.\n * @return {!Object<string, !goog.debug.Logger>} Map of logger names to logger\n * objects.\n */\ngoog.debug.LogManager.getLoggers = function() {\n return goog.debug.LogManager.loggers_;\n};\n\n\n/**\n * Returns the root of the logger tree namespace, the logger with the empty\n * string as its name.\n *\n * @return {!goog.debug.Logger} The root logger.\n */\ngoog.debug.LogManager.getRoot = function() {\n goog.debug.LogManager.initialize();\n return /** @type {!goog.debug.Logger} */ (goog.debug.LogManager.rootLogger_);\n};\n\n\n/**\n * Finds a named logger.\n *\n * @param {string} name A name for the logger. This should be a dot-separated\n * name and should normally be based on the package name or class name of the\n * subsystem, such as goog.net.BrowserChannel.\n * @return {!goog.debug.Logger} The named logger.\n */\ngoog.debug.LogManager.getLogger = function(name) {\n goog.debug.LogManager.initialize();\n var ret = goog.debug.LogManager.loggers_[name];\n return ret || goog.debug.LogManager.createLogger_(name);\n};\n\n\n/**\n * Creates a function that can be passed to goog.debug.catchErrors. The function\n * will log all reported errors using the given logger.\n * @param {goog.debug.Logger=} opt_logger The logger to log the errors to.\n * Defaults to the root logger.\n * @return {function(Object)} The created function.\n */\ngoog.debug.LogManager.createFunctionForCatchErrors = function(opt_logger) {\n return function(info) {\n var logger = opt_logger || goog.debug.LogManager.getRoot();\n logger.severe(\n 'Error: ' + info.message + ' (' + info.fileName + ' @ Line: ' +\n info.line + ')');\n };\n};\n\n\n/**\n * Creates the named logger. Will also create the parents of the named logger\n * if they don't yet exist.\n * @param {string} name The name of the logger.\n * @return {!goog.debug.Logger} The named logger.\n * @private\n */\ngoog.debug.LogManager.createLogger_ = function(name) {\n // find parent logger\n var logger = new goog.debug.Logger(name);\n if (goog.debug.Logger.ENABLE_HIERARCHY) {\n var lastDotIndex = name.lastIndexOf('.');\n var parentName = name.substr(0, lastDotIndex);\n var leafName = name.substr(lastDotIndex + 1);\n var parentLogger = goog.debug.LogManager.getLogger(parentName);\n\n // tell the parent about the child and the child about the parent\n parentLogger.addChild_(leafName, logger);\n logger.setParent_(parentLogger);\n }\n\n goog.debug.LogManager.loggers_[name] = logger;\n return logger;\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 Constants for HTTP status codes.\n */\n\ngoog.provide('goog.net.HttpStatus');\n\n\n/**\n * HTTP Status Codes defined in RFC 2616, RFC 6585, RFC 4918 and RFC 7538.\n * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n * @see http://tools.ietf.org/html/rfc6585\n * @see https://tools.ietf.org/html/rfc4918\n * @see https://tools.ietf.org/html/rfc7538\n * @enum {number}\n */\ngoog.net.HttpStatus = {\n // Informational 1xx\n CONTINUE: 100,\n SWITCHING_PROTOCOLS: 101,\n\n // Successful 2xx\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NON_AUTHORITATIVE_INFORMATION: 203,\n NO_CONTENT: 204,\n RESET_CONTENT: 205,\n PARTIAL_CONTENT: 206,\n MULTI_STATUS: 207,\n\n // Redirection 3xx\n MULTIPLE_CHOICES: 300,\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n SEE_OTHER: 303,\n NOT_MODIFIED: 304,\n USE_PROXY: 305,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // Client Error 4xx\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n REQUEST_TIMEOUT: 408,\n CONFLICT: 409,\n GONE: 410,\n LENGTH_REQUIRED: 411,\n PRECONDITION_FAILED: 412,\n REQUEST_ENTITY_TOO_LARGE: 413,\n REQUEST_URI_TOO_LONG: 414,\n UNSUPPORTED_MEDIA_TYPE: 415,\n REQUEST_RANGE_NOT_SATISFIABLE: 416,\n EXPECTATION_FAILED: 417,\n UNPROCESSABLE_ENTITY: 422,\n LOCKED: 423,\n FAILED_DEPENDENCY: 424,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n\n // Server Error 5xx\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n INSUFFICIENT_STORAGE: 507,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n\n /*\n * IE returns this code for 204 due to its use of URLMon, which returns this\n * code for 'Operation Aborted'. The status text is 'Unknown', the response\n * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.\n */\n QUIRK_IE_NO_CONTENT: 1223,\n};\n\n\n/**\n * Returns whether the given status should be considered successful.\n *\n * Successful codes are OK (200), CREATED (201), ACCEPTED (202),\n * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),\n * and IE's no content code (1223).\n *\n * @param {number} status The status code to test.\n * @return {boolean} Whether the status code should be considered successful.\n */\ngoog.net.HttpStatus.isSuccess = function(status) {\n switch (status) {\n case goog.net.HttpStatus.OK:\n case goog.net.HttpStatus.CREATED:\n case goog.net.HttpStatus.ACCEPTED:\n case goog.net.HttpStatus.NO_CONTENT:\n case goog.net.HttpStatus.PARTIAL_CONTENT:\n case goog.net.HttpStatus.NOT_MODIFIED:\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\n return true;\n\n default:\n return false;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for creating functions. Loosely inspired by these\n * java classes from the Guava library:\n * com.google.common.base.Functions\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\n *\n * com.google.common.base.Predicates\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\n *\n * More about these can be found at\n * https://github.com/google/guava/wiki/FunctionalExplained\n */\n\n\ngoog.provide('goog.functions');\n\n\n/**\n * Creates a function that always returns the same value.\n * @param {T} retValue The value to return.\n * @return {function():T} The new function.\n * @template T\n */\ngoog.functions.constant = function(retValue) {\n return function() { return retValue; };\n};\n\n\n/**\n * Always returns false.\n * @type {function(...): boolean}\n */\ngoog.functions.FALSE = function() {\n return false;\n};\n\n\n/**\n * Always returns true.\n * @type {function(...): boolean}\n */\ngoog.functions.TRUE = function() {\n return true;\n};\n\n\n/**\n * Always returns NULL.\n * @type {function(...): null}\n */\ngoog.functions.NULL = function() {\n return null;\n};\n\n\n/**\n * A simple function that returns the first argument of whatever is passed\n * into it.\n * @param {T=} opt_returnValue The single value that will be returned.\n * @param {...*} var_args Optional trailing arguments. These are ignored.\n * @return {T} The first argument passed in, or undefined if nothing was passed.\n * @template T\n */\ngoog.functions.identity = function(opt_returnValue, var_args) {\n return opt_returnValue;\n};\n\n\n/**\n * Creates a function that always throws an error with the given message.\n * @param {string} message The error message.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.error = function(message) {\n return function() {\n throw new Error(message);\n };\n};\n\n\n/**\n * Creates a function that throws the given object.\n * @param {*} err An object to be thrown.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.fail = function(err) {\n return function() { throw err; };\n};\n\n\n/**\n * Given a function, create a function that keeps opt_numArgs arguments and\n * silently discards all additional arguments.\n * @param {Function} f The original function.\n * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.\n * @return {!Function} A version of f that only keeps the first opt_numArgs\n * arguments.\n */\ngoog.functions.lock = function(f, opt_numArgs) {\n opt_numArgs = opt_numArgs || 0;\n return function() {\n const self = /** @type {*} */ (this);\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\n };\n};\n\n\n/**\n * Creates a function that returns its nth argument.\n * @param {number} n The position of the return argument.\n * @return {!Function} A new function.\n */\ngoog.functions.nth = function(n) {\n return function() { return arguments[n]; };\n};\n\n\n/**\n * Like goog.partial(), except that arguments are added after arguments to the\n * returned function.\n *\n * Usage:\n * function f(arg1, arg2, arg3, arg4) { ... }\n * var g = goog.functions.partialRight(f, arg3, arg4);\n * g(arg1, arg2);\n *\n * @param {!Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn\n * at the end.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.functions.partialRight = function(fn, var_args) {\n const rightArgs = Array.prototype.slice.call(arguments, 1);\n return function() {\n const self = /** @type {*} */ (this);\n const newArgs = Array.prototype.slice.call(arguments);\n newArgs.push.apply(newArgs, rightArgs);\n return fn.apply(self, newArgs);\n };\n};\n\n\n/**\n * Given a function, create a new function that swallows its return value\n * and replaces it with a new one.\n * @param {Function} f A function.\n * @param {T} retValue A new return value.\n * @return {function(...?):T} A new function.\n * @template T\n */\ngoog.functions.withReturnValue = function(f, retValue) {\n return goog.functions.sequence(f, goog.functions.constant(retValue));\n};\n\n\n/**\n * Creates a function that returns whether its argument equals the given value.\n *\n * Example:\n * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));\n *\n * @param {*} value The value to compare to.\n * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)\n * comparison rather than a strict (===) one. Defaults to false.\n * @return {function(*):boolean} The new function.\n */\ngoog.functions.equalTo = function(value, opt_useLooseComparison) {\n return function(other) {\n return opt_useLooseComparison ? (value == other) : (value === other);\n };\n};\n\n\n/**\n * Creates the composition of the functions passed in.\n * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).\n * @param {function(...?):T} fn The final function.\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):T} The composition of all inputs.\n * @template T\n */\ngoog.functions.compose = function(fn, var_args) {\n const functions = arguments;\n const length = functions.length;\n return function() {\n const self = /** @type {*} */ (this);\n let result;\n if (length) {\n result = functions[length - 1].apply(self, arguments);\n }\n\n for (let i = length - 2; i >= 0; i--) {\n result = functions[i].call(self, result);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that calls the functions passed in in sequence, and\n * returns the value of the last function. For example,\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\n * @param {...Function} var_args A list of functions.\n * @return {!Function} A function that calls all inputs in sequence.\n */\ngoog.functions.sequence = function(var_args) {\n const functions = arguments;\n const length = functions.length;\n return function() {\n const self = /** @type {*} */ (this);\n let result;\n for (let i = 0; i < length; i++) {\n result = functions[i].apply(self, arguments);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that returns true if each of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns false.\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ANDs its component\n * functions.\n */\ngoog.functions.and = function(var_args) {\n const functions = arguments;\n const length = functions.length;\n return function() {\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (!functions[i].apply(self, arguments)) {\n return false;\n }\n }\n return true;\n };\n};\n\n\n/**\n * Creates a function that returns true if any of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns true.\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ORs its component\n * functions.\n */\ngoog.functions.or = function(var_args) {\n const functions = arguments;\n const length = functions.length;\n return function() {\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (functions[i].apply(self, arguments)) {\n return true;\n }\n }\n return false;\n };\n};\n\n\n/**\n * Creates a function that returns the Boolean opposite of a provided function.\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\n * @param {!Function} f The original function.\n * @return {function(...?):boolean} A function that delegates to f and returns\n * opposite.\n */\ngoog.functions.not = function(f) {\n return function() {\n const self = /** @type {*} */ (this);\n return !f.apply(self, arguments);\n };\n};\n\n\n/**\n * Generic factory function to construct an object given the constructor\n * and the arguments. Intended to be bound to create object factories.\n *\n * Example:\n *\n * var factory = goog.partial(goog.functions.create, Class);\n *\n * @param {function(new:T, ...)} constructor The constructor for the Object.\n * @param {...*} var_args The arguments to be passed to the constructor.\n * @return {T} A new instance of the class given in `constructor`.\n * @template T\n * @deprecated This function does not work with ES6 class constructors. Use\n * arrow functions + spread args instead.\n */\ngoog.functions.create = function(constructor, var_args) {\n /**\n * @constructor\n * @final\n */\n const temp = function() {};\n temp.prototype = constructor.prototype;\n\n // obj will have constructor's prototype in its chain and\n // 'obj instanceof constructor' will be true.\n const obj = new temp();\n\n // obj is initialized by constructor.\n // arguments is only array-like so lacks shift(), but can be used with\n // the Array prototype function.\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\n return obj;\n};\n\n\n/**\n * @define {boolean} Whether the return value cache should be used.\n * This should only be used to disable caches when testing.\n */\ngoog.functions.CACHE_RETURN_VALUE =\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\n\n\n/**\n * Gives a wrapper function that caches the return value of a parameterless\n * function when first called.\n *\n * When called for the first time, the given function is called and its\n * return value is cached (thus this is only appropriate for idempotent\n * functions). Subsequent calls will return the cached return value. This\n * allows the evaluation of expensive functions to be delayed until first used.\n *\n * To cache the return values of functions with parameters, see goog.memoize.\n *\n * @param {function():T} fn A function to lazily evaluate.\n * @return {function():T} A wrapped version the function.\n * @template T\n */\ngoog.functions.cacheReturnValue = function(fn) {\n let called = false;\n let value;\n\n return function() {\n if (!goog.functions.CACHE_RETURN_VALUE) {\n return fn();\n }\n\n if (!called) {\n value = fn();\n called = true;\n }\n\n return value;\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once. All\n * additional calls are no-ops.\n *\n * This is particularly useful for initialization functions\n * that should be called, at most, once.\n *\n * @param {function():*} f Function to call.\n * @return {function():undefined} Wrapped function.\n */\ngoog.functions.once = function(f) {\n // Keep a reference to the function that we null out when we're done with\n // it -- that way, the function can be GC'd when we're done with it.\n let inner = f;\n return function() {\n if (inner) {\n const tmp = inner;\n inner = null;\n tmp();\n }\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the Nth call will go through.\n *\n * This is particularly useful for batching up repeated actions where the\n * last action should win. This can be used, for example, for refreshing an\n * autocomplete pop-up every so often rather than updating with every keystroke,\n * since the final text typed by the user is the one that should produce the\n * final autocomplete results. For more stateful debouncing with support for\n * pausing, resuming, and canceling debounced actions, use\n * `goog.async.Debouncer`.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to debounce. The function will\n * only be called after the full interval has elapsed since the last call.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.debounce = function(f, interval, opt_scope) {\n let timeout = 0;\n return /** @type {function(...?)} */ (function(var_args) {\n goog.global.clearTimeout(timeout);\n const args = arguments;\n timeout = goog.global.setTimeout(function() {\n f.apply(opt_scope, args);\n }, interval);\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times in\n * that interval, both the 1st and the Nth calls will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * the last action should win, but you also don't want to wait until the end of\n * the interval before sending a request out, as it leads to a perception of\n * slowness for the user.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to throttle. The function can\n * only be called once per interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.throttle = function(f, interval, opt_scope) {\n let timeout = 0;\n let shouldFire = false;\n let args = [];\n\n const handleTimeout = function() {\n timeout = 0;\n if (shouldFire) {\n shouldFire = false;\n fire();\n }\n };\n\n const fire = function() {\n timeout = goog.global.setTimeout(handleTimeout, interval);\n f.apply(opt_scope, args);\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n args = arguments;\n if (!timeout) {\n fire();\n } else {\n shouldFire = true;\n }\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the 1st call will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * first request is guaranteed to have all the data required to perform the\n * final action, so there's no need to wait until the end of the interval before\n * sending the request out.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to rate-limit. The function will\n * only be called once per interval, and ignored for the remainer of the\n * interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.rateLimit = function(f, interval, opt_scope) {\n let timeout = 0;\n\n const handleTimeout = function() {\n timeout = 0;\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n if (!timeout) {\n timeout = goog.global.setTimeout(handleTimeout, interval);\n f.apply(opt_scope, arguments);\n }\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Basic strippable logging definitions.\n * @see http://go/closurelogging\n */\n\ngoog.provide('goog.log');\ngoog.provide('goog.log.Level');\ngoog.provide('goog.log.LogRecord');\ngoog.provide('goog.log.Logger');\n\ngoog.require('goog.debug');\ngoog.require('goog.debug.LogManager');\ngoog.require('goog.debug.LogRecord');\ngoog.require('goog.debug.Logger');\n\n\n/** @define {boolean} Whether logging is enabled. */\ngoog.log.ENABLED = goog.define('goog.log.ENABLED', goog.debug.LOGGING_ENABLED);\n\n\n/** @const {string} */\ngoog.log.ROOT_LOGGER_NAME = goog.debug.Logger.ROOT_LOGGER_NAME;\n\n\n\n/**\n * @constructor\n * @final\n */\ngoog.log.Logger = goog.debug.Logger;\n\n\n\n/**\n * @constructor\n * @final\n */\ngoog.log.Level = goog.debug.Logger.Level;\n\n\n\n/**\n * @constructor\n * @final\n */\ngoog.log.LogRecord = goog.debug.LogRecord;\n\n\n/**\n * Finds or creates a logger for a named subsystem. If a logger has already been\n * created with the given name it is returned. Otherwise a new logger is\n * created. If a new logger is created its log level will be configured based\n * on the goog.debug.LogManager configuration and it will configured to also\n * send logging output to its parent's handlers.\n * @see goog.debug.LogManager\n *\n * @param {string} name A name for the logger. This should be a dot-separated\n * name and should normally be based on the package name or class name of\n * the subsystem, such as goog.net.BrowserChannel.\n * @param {goog.log.Level=} opt_level If provided, override the\n * default logging level with the provided level.\n * @return {goog.log.Logger} The named logger or null if logging is disabled.\n */\ngoog.log.getLogger = function(name, opt_level) {\n if (goog.log.ENABLED) {\n var logger = goog.debug.LogManager.getLogger(name);\n if (opt_level && logger) {\n logger.setLevel(opt_level);\n }\n return logger;\n } else {\n return null;\n }\n};\n\n\n// TODO(johnlenz): try to tighten the types to these functions.\n/**\n * Adds a handler to the logger. This doesn't use the event system because\n * we want to be able to add logging to the event system.\n * @param {goog.log.Logger} logger\n * @param {Function} handler Handler function to add.\n */\ngoog.log.addHandler = function(logger, handler) {\n if (goog.log.ENABLED && logger) {\n logger.addHandler(handler);\n }\n};\n\n\n/**\n * Removes a handler from the logger. This doesn't use the event system because\n * we want to be able to add logging to the event system.\n * @param {goog.log.Logger} logger\n * @param {Function} handler Handler function to remove.\n * @return {boolean} Whether the handler was removed.\n */\ngoog.log.removeHandler = function(logger, handler) {\n if (goog.log.ENABLED && logger) {\n return logger.removeHandler(handler);\n } else {\n return false;\n }\n};\n\n\n/**\n * Logs a message. If the logger is currently enabled for the\n * given message level then the given message is forwarded to all the\n * registered output Handler objects.\n * @param {goog.log.Logger} logger\n * @param {goog.log.Level} level One of the level identifiers.\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error|Object=} opt_exception An exception associated with the\n * message.\n */\ngoog.log.log = function(logger, level, msg, opt_exception) {\n if (goog.log.ENABLED && logger) {\n logger.log(level, msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Level.SEVERE level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.log.Logger} logger\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.log.error = function(logger, msg, opt_exception) {\n if (goog.log.ENABLED && logger) {\n logger.severe(msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Level.WARNING level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.log.Logger} logger\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.log.warning = function(logger, msg, opt_exception) {\n if (goog.log.ENABLED && logger) {\n logger.warning(msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Level.INFO level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.log.Logger} logger\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.log.info = function(logger, msg, opt_exception) {\n if (goog.log.ENABLED && logger) {\n logger.info(msg, opt_exception);\n }\n};\n\n\n/**\n * Logs a message at the Level.Fine level.\n * If the logger is currently enabled for the given message level then the\n * given message is forwarded to all the registered output Handler objects.\n * @param {goog.log.Logger} logger\n * @param {goog.debug.Loggable} msg The message to log.\n * @param {Error=} opt_exception An exception associated with the message.\n */\ngoog.log.fine = function(logger, msg, opt_exception) {\n if (goog.log.ENABLED && logger) {\n logger.fine(msg, opt_exception);\n }\n};\n","// Copyright 2015 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\ngoog.provide('goog.net.FetchXmlHttp');\ngoog.provide('goog.net.FetchXmlHttpFactory');\n\ngoog.require('goog.asserts');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.functions');\ngoog.require('goog.log');\ngoog.require('goog.net.XhrLike');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * Factory for creating Xhr objects that uses the native fetch() method.\n * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n * Note that this factory is intended for use in Service Worker only.\n * @param {!WorkerGlobalScope} worker The Service Worker global scope.\n * @extends {goog.net.XmlHttpFactory}\n * @struct\n * @constructor\n */\ngoog.net.FetchXmlHttpFactory = function(worker) {\n goog.net.FetchXmlHttpFactory.base(this, 'constructor');\n\n /** @private @final {!WorkerGlobalScope} */\n this.worker_ = worker;\n\n /** @private {!RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {!RequestCache|undefined} */\n this.cacheMode_ = undefined;\n};\ngoog.inherits(goog.net.FetchXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.createInstance = function() {\n var instance = new goog.net.FetchXmlHttp(this.worker_);\n if (this.credentialsMode_) {\n instance.setCredentialsMode(this.credentialsMode_);\n }\n if (this.cacheMode_) {\n instance.setCacheMode(this.cacheMode_);\n }\n return instance;\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.internalGetOptions =\n goog.functions.constant({});\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCredentialsMode = function(\n credentialsMode) {\n this.credentialsMode_ = credentialsMode;\n};\n\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCacheMode = function(cacheMode) {\n this.cacheMode_ = cacheMode;\n};\n\n\n\n/**\n * FetchXmlHttp object constructor.\n * @param {!WorkerGlobalScope} worker\n * @extends {goog.events.EventTarget}\n * @implements {goog.net.XhrLike}\n * @constructor\n * @struct\n */\ngoog.net.FetchXmlHttp = function(worker) {\n goog.net.FetchXmlHttp.base(this, 'constructor');\n\n /** @private @final {!WorkerGlobalScope} */\n this.worker_ = worker;\n\n /** @private {RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {RequestCache|undefined} */\n this.cacheMode_ = undefined;\n\n /**\n * Request state.\n * @type {goog.net.FetchXmlHttp.RequestState}\n */\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n\n /**\n * HTTP status.\n * @type {number}\n */\n this.status = 0;\n\n /**\n * HTTP status string.\n * @type {string}\n */\n this.statusText = '';\n\n /**\n * Content of the response.\n * @type {string|!ArrayBuffer}\n */\n this.response = '';\n\n /**\n * Content of the response.\n * @type {string}\n */\n this.responseText = '';\n\n /**\n * The type of the response. If this is set to 'arraybuffer' the request will\n * be discrete, streaming is only supported for text encoded requests.\n * @type {string}\n */\n this.responseType = '';\n\n /**\n * Document response entity body.\n * NOTE: This is always null and not supported by this class.\n * @final {null}\n */\n this.responseXML = null;\n\n /**\n * Method to call when the state changes.\n * @type {?function()}\n */\n this.onreadystatechange = null;\n\n /** @private {!Headers} */\n this.requestHeaders_ = new Headers();\n\n /** @private {?Headers} */\n this.responseHeaders_ = null;\n\n /**\n * Request method (GET or POST).\n * @private {string}\n */\n this.method_ = 'GET';\n\n /**\n * Request URL.\n * @private {string}\n */\n this.url_ = '';\n\n /**\n * Whether the request is in progress.\n * @private {boolean}\n */\n this.inProgress_ = false;\n\n /** @private @final {?goog.log.Logger} */\n this.logger_ = goog.log.getLogger('goog.net.FetchXmlHttp');\n\n /** @private {?Response} */\n this.fetchResponse_ = null;\n\n /** @private {!ReadableStreamDefaultReader|null} */\n this.currentReader_ = null;\n\n /** @private {?TextDecoder} */\n this.textDecoder_ = null;\n};\ngoog.inherits(goog.net.FetchXmlHttp, goog.events.EventTarget);\n\n\n/**\n * State of the requests.\n * @enum {number}\n */\ngoog.net.FetchXmlHttp.RequestState = {\n UNSENT: 0,\n OPENED: 1,\n HEADER_RECEIVED: 2,\n LOADING: 3,\n DONE: 4,\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.open = function(method, url, opt_async) {\n goog.asserts.assert(!!opt_async, 'Only async requests are supported.');\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.UNSENT) {\n this.abort();\n throw new Error('Error reopening a connection');\n }\n\n this.method_ = method;\n this.url_ = url;\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.OPENED;\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.send = function(opt_data) {\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.OPENED) {\n this.abort();\n throw new Error('need to call open() first. ');\n }\n\n this.inProgress_ = true;\n var requestInit = {\n headers: this.requestHeaders_,\n method: this.method_,\n credentials: this.credentialsMode_,\n cache: this.cacheMode_,\n };\n if (opt_data) {\n requestInit['body'] = opt_data;\n }\n this.worker_\n .fetch(new Request(this.url_, /** @type {!RequestInit} */ (requestInit)))\n .then(\n this.handleResponse_.bind(this), this.handleSendFailure_.bind(this));\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.abort = function() {\n this.response = this.responseText = '';\n this.requestHeaders_ = new Headers();\n this.status = 0;\n\n if (!!this.currentReader_) {\n this.currentReader_.cancel('Request was aborted.');\n }\n\n if (((this.readyState >= goog.net.FetchXmlHttp.RequestState.OPENED) &&\n this.inProgress_) &&\n (this.readyState != goog.net.FetchXmlHttp.RequestState.DONE)) {\n this.inProgress_ = false;\n this.requestDone_(false);\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n};\n\n\n/**\n * Handles the fetch response.\n * @param {!Response} response\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponse_ = function(response) {\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.fetchResponse_ = response;\n\n if (!this.responseHeaders_) {\n this.responseHeaders_ = response.headers;\n this.readyState = goog.net.FetchXmlHttp.RequestState.HEADER_RECEIVED;\n this.dispatchCallback_();\n }\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.LOADING;\n this.dispatchCallback_();\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.responseType === 'arraybuffer') {\n response.arrayBuffer().then(\n this.handleResponseArrayBuffer_.bind(this),\n this.handleSendFailure_.bind(this));\n } else if (\n typeof (goog.global.ReadableStream) !== 'undefined' &&\n 'body' in response) {\n this.response = this.responseText = '';\n this.currentReader_ =\n /** @type {!ReadableStreamDefaultReader} */ (response.body.getReader());\n this.textDecoder_ = new TextDecoder();\n this.readInputFromFetch_();\n } else {\n response.text().then(\n this.handleResponseText_.bind(this),\n this.handleSendFailure_.bind(this));\n }\n};\n\n\n/**\n * Reads the next chunk of data from the fetch response.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.readInputFromFetch_ = function() {\n this.currentReader_.read()\n .then(this.handleDataFromStream_.bind(this))\n .catch(this.handleSendFailure_.bind(this));\n};\n\n\n/**\n * Handles a chunk of data from the fetch response stream reader.\n * @param {!IteratorResult} result\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleDataFromStream_ = function(result) {\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n var dataPacket = result.value ? /** @type {!Uint8Array} */ (result.value) :\n new Uint8Array(0);\n var newText = this.textDecoder_.decode(dataPacket, {stream: !result.done});\n if (newText) {\n this.responseText += newText;\n this.response = this.responseText;\n }\n\n if (result.done) {\n this.requestDone_(true);\n } else {\n this.dispatchCallback_();\n }\n\n if (this.readyState == goog.net.FetchXmlHttp.RequestState.LOADING) {\n this.readInputFromFetch_();\n }\n};\n\n\n/**\n * Handles the response text.\n * @param {string} responseText\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseText_ = function(responseText) {\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = this.responseText = responseText;\n this.requestDone_(true);\n};\n\n\n/**\n * Handles the response text.\n * @param {!ArrayBuffer} responseArrayBuffer\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_ = function(\n responseArrayBuffer) {\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = responseArrayBuffer;\n this.requestDone_(true);\n};\n\n\n/**\n * Handles the send failure.\n * @param {*} error\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleSendFailure_ = function(error) {\n var e = error instanceof Error ? error : Error(error);\n goog.log.warning(this.logger_, 'Failed to fetch url ' + this.url_, e);\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.requestDone_(true);\n};\n\n\n/**\n * Sets the request state to DONE and performs cleanup.\n * @param {boolean} setStatus whether to set the status and statusText fields,\n * this is not necessary when the request is aborted.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.requestDone_ = function(setStatus) {\n if (setStatus && this.fetchResponse_) {\n this.status = this.fetchResponse_.status;\n this.statusText = this.fetchResponse_.statusText;\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.DONE;\n\n this.fetchResponse_ = null;\n this.currentReader_ = null;\n this.textDecoder_ = null;\n\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.setRequestHeader = function(header, value) {\n this.requestHeaders_.append(header, value);\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getResponseHeader = function(header) {\n // TODO(user): This method should return null when the headers are not\n // present or the specified header is missing. The externs need to be fixed.\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get response header but no headers have been received ' +\n 'for url: ' + this.url_);\n return '';\n }\n return this.responseHeaders_.get(header.toLowerCase()) || '';\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getAllResponseHeaders = function() {\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get all response headers but no headers have been ' +\n 'received for url: ' + this.url_);\n return '';\n }\n var lines = [];\n var iter = this.responseHeaders_.entries();\n var entry = iter.next();\n while (!entry.done) {\n var pair = entry.value;\n lines.push(pair[0] + ': ' + pair[1]);\n entry = iter.next();\n }\n return lines.join('\\r\\n');\n};\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCredentialsMode = function(credentialsMode) {\n this.credentialsMode_ = credentialsMode;\n};\n\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCacheMode = function(cacheMode) {\n this.cacheMode_ = cacheMode;\n};\n\n\n/**\n * Dispatches the callback, if the callback attribute is defined.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.dispatchCallback_ = function() {\n if (this.onreadystatechange) {\n this.onreadystatechange.call(this);\n }\n};\n","// Copyright 2006 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 Wrapper class for handling XmlHttpRequests.\n *\n * One off requests can be sent through goog.net.XhrIo.send() or an\n * instance can be created to send multiple requests. Each request uses its\n * own XmlHttpRequest object and handles clearing of the event callback to\n * ensure no leaks.\n *\n * XhrIo is event based, it dispatches events on success, failure, finishing,\n * ready-state change, or progress (download and upload).\n *\n * The ready-state or timeout event fires first, followed by\n * a generic completed event. Then the abort, error, or success event\n * is fired as appropriate. Progress events are fired as they are\n * received. Lastly, the ready event will fire to indicate that the\n * object may be used to make another request.\n *\n * The error event may also be called before completed and\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\n *\n * This class does not support multiple requests, queuing, or prioritization.\n *\n * When progress events are supported by the browser, and progress is\n * enabled via .setProgressEventsEnabled(true), the\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\n * will be fired for download and upload progress respectively.\n */\n\n\ngoog.provide('goog.net.XhrIo');\ngoog.provide('goog.net.XhrIo.ResponseType');\n\ngoog.require('goog.Timer');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json.hybrid');\ngoog.require('goog.log');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.HttpStatus');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.structs');\ngoog.require('goog.structs.Map');\ngoog.require('goog.uri.utils');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\n\ngoog.scope(function() {\n\n/**\n * Basic class for handling XMLHttpRequests.\n * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when\n * creating XMLHttpRequest objects.\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.net.XhrIo = function(opt_xmlHttpFactory) {\n XhrIo.base(this, 'constructor');\n\n /**\n * Map of default headers to add to every request, use:\n * XhrIo.headers.set(name, value)\n * @type {!goog.structs.Map}\n */\n this.headers = new goog.structs.Map();\n\n /**\n * Optional XmlHttpFactory\n * @private {goog.net.XmlHttpFactory}\n */\n this.xmlHttpFactory_ = opt_xmlHttpFactory || null;\n\n /**\n * Whether XMLHttpRequest is active. A request is active from the time send()\n * is called until onReadyStateChange() is complete, or error() or abort()\n * is called.\n * @private {boolean}\n */\n this.active_ = false;\n\n /**\n * The XMLHttpRequest object that is being used for the transfer.\n * @private {?goog.net.XhrLike.OrNative}\n */\n this.xhr_ = null;\n\n /**\n * The options to use with the current XMLHttpRequest object.\n * @private {?Object}\n */\n this.xhrOptions_ = null;\n\n /**\n * Last URL that was requested.\n * @private {string|goog.Uri}\n */\n this.lastUri_ = '';\n\n /**\n * Method for the last request.\n * @private {string}\n */\n this.lastMethod_ = '';\n\n /**\n * Last error code.\n * @private {!goog.net.ErrorCode}\n */\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n\n /**\n * Last error message.\n * @private {Error|string}\n */\n this.lastError_ = '';\n\n /**\n * Used to ensure that we don't dispatch an multiple ERROR events. This can\n * happen in IE when it does a synchronous load and one error is handled in\n * the ready statte change and one is handled due to send() throwing an\n * exception.\n * @private {boolean}\n */\n this.errorDispatched_ = false;\n\n /**\n * Used to make sure we don't fire the complete event from inside a send call.\n * @private {boolean}\n */\n this.inSend_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.open.\n * @private {boolean}\n */\n this.inOpen_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.abort.\n * @private {boolean}\n */\n this.inAbort_ = false;\n\n /**\n * Number of milliseconds after which an incomplete request will be aborted\n * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout\n * is set.\n * @private {number}\n */\n this.timeoutInterval_ = 0;\n\n /**\n * Timer to track request timeout.\n * @private {?number}\n */\n this.timeoutId_ = null;\n\n /**\n * The requested type for the response. The empty string means use the default\n * XHR behavior.\n * @private {goog.net.XhrIo.ResponseType}\n */\n this.responseType_ = ResponseType.DEFAULT;\n\n /**\n * Whether a \"credentialed\" request is to be sent (one that is aware of\n * cookies and authentication). This is applicable only for cross-domain\n * requests and more recent browsers that support this part of the HTTP Access\n * Control standard.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute\n *\n * @private {boolean}\n */\n this.withCredentials_ = false;\n\n /**\n * Whether progress events are enabled for this request. This is\n * disabled by default because setting a progress event handler\n * causes pre-flight OPTIONS requests to be sent for CORS requests,\n * even in cases where a pre-flight request would not otherwise be\n * sent.\n *\n * @see http://xhr.spec.whatwg.org/#security-considerations\n *\n * Note that this can cause problems for Firefox 22 and below, as an\n * older \"LSProgressEvent\" will be dispatched by the browser. That\n * progress event is no longer supported, and can lead to failures,\n * including throwing exceptions.\n *\n * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631\n * @see b/23469793\n *\n * @private {boolean}\n */\n this.progressEventsEnabled_ = false;\n\n /**\n * True if we can use XMLHttpRequest's timeout directly.\n * @private {boolean}\n */\n this.useXhr2Timeout_ = false;\n};\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\n\nvar XhrIo = goog.net.XhrIo;\n\n/**\n * Response types that may be requested for XMLHttpRequests.\n * @enum {string}\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute\n */\ngoog.net.XhrIo.ResponseType = {\n DEFAULT: '',\n TEXT: 'text',\n DOCUMENT: 'document',\n // Not supported as of Chrome 10.0.612.1 dev\n BLOB: 'blob',\n ARRAY_BUFFER: 'arraybuffer',\n};\n\nvar ResponseType = goog.net.XhrIo.ResponseType;\n\n\n/**\n * A reference to the XhrIo logger\n * @private {?goog.log.Logger}\n * @const\n */\ngoog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');\n\n\n/**\n * The Content-Type HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';\n\n\n/**\n * The Content-Transfer-Encoding HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';\n\n\n/**\n * The pattern matching the 'http' and 'https' URI schemes\n * @type {!RegExp}\n */\ngoog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;\n\n\n/**\n * The methods that typically come along with form data. We set different\n * headers depending on whether the HTTP action is one of these.\n * @type {!Array<string>}\n */\ngoog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];\n\n\n/**\n * The Content-Type HTTP header value for a url-encoded form\n * @type {string}\n */\ngoog.net.XhrIo.FORM_CONTENT_TYPE =\n 'application/x-www-form-urlencoded;charset=utf-8';\n\n\n/**\n * The XMLHttpRequest Level two timeout delay ms property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';\n\n\n/**\n * The XMLHttpRequest Level two ontimeout handler property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';\n\n\n/**\n * All non-disposed instances of goog.net.XhrIo created\n * by {@link goog.net.XhrIo.send} are in this Array.\n * @see goog.net.XhrIo.cleanup\n * @private {!Array<!goog.net.XhrIo>}\n */\ngoog.net.XhrIo.sendInstances_ = [];\n\n\n/**\n * Static send that creates a short lived instance of XhrIo to send the\n * request.\n * @see goog.net.XhrIo.cleanup\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function\n * for when request is complete.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the\n * request.\n * @param {number=} opt_timeoutInterval Number of milliseconds after which an\n * incomplete request will be aborted; 0 means no timeout is set.\n * @param {boolean=} opt_withCredentials Whether to send credentials with the\n * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.\n * @return {!goog.net.XhrIo} The sent XhrIo.\n */\ngoog.net.XhrIo.send = function(\n url, opt_callback, opt_method, opt_content, opt_headers,\n opt_timeoutInterval, opt_withCredentials) {\n var x = new goog.net.XhrIo();\n goog.net.XhrIo.sendInstances_.push(x);\n if (opt_callback) {\n x.listen(goog.net.EventType.COMPLETE, opt_callback);\n }\n x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);\n if (opt_timeoutInterval) {\n x.setTimeoutInterval(opt_timeoutInterval);\n }\n if (opt_withCredentials) {\n x.setWithCredentials(opt_withCredentials);\n }\n x.send(url, opt_method, opt_content, opt_headers);\n return x;\n};\n\n\n/**\n * Disposes all non-disposed instances of goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send}.\n * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance\n * it creates when the request completes or fails. However, if\n * the request never completes, then the goog.net.XhrIo is not disposed.\n * This can occur if the window is unloaded before the request completes.\n * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo\n * it creates and make the client of {@link goog.net.XhrIo.send} be\n * responsible for disposing it in this case. However, this makes things\n * significantly more complicated for the client, and the whole point\n * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.\n * Clients of {@link goog.net.XhrIo.send} should call\n * {@link goog.net.XhrIo.cleanup} when doing final\n * cleanup on window unload.\n */\ngoog.net.XhrIo.cleanup = function() {\n var instances = goog.net.XhrIo.sendInstances_;\n while (instances.length) {\n instances.pop().dispose();\n }\n};\n\n\n/**\n * Installs exception protection for all entry point introduced by\n * goog.net.XhrIo instances which are not protected by\n * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},\n * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or\n * {@link goog.events.protectBrowserEventEntryPoint}.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point(s).\n */\ngoog.net.XhrIo.protectEntryPoints = function(errorHandler) {\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n errorHandler.protectEntryPoint(\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n};\n\n\n/**\n * Disposes of the specified goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send} and removes it from\n * {@link goog.net.XhrIo.pendingStaticSendInstances_}.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanupSend_ = function() {\n this.dispose();\n goog.array.remove(goog.net.XhrIo.sendInstances_, this);\n};\n\n\n/**\n * Returns the number of milliseconds after which an incomplete request will be\n * aborted, or 0 if no timeout is set.\n * @return {number} Timeout interval in milliseconds.\n */\ngoog.net.XhrIo.prototype.getTimeoutInterval = function() {\n return this.timeoutInterval_;\n};\n\n\n/**\n * Sets the number of milliseconds after which an incomplete request will be\n * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no\n * timeout is set.\n * @param {number} ms Timeout interval in milliseconds; 0 means none.\n */\ngoog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {\n this.timeoutInterval_ = Math.max(0, ms);\n};\n\n\n/**\n * Sets the desired type for the response. At time of writing, this is only\n * supported in very recent versions of WebKit (10.0.612.1 dev and later).\n *\n * If this is used, the response may only be accessed via {@link #getResponse}.\n *\n * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.\n */\ngoog.net.XhrIo.prototype.setResponseType = function(type) {\n this.responseType_ = type;\n};\n\n\n/**\n * Gets the desired type for the response.\n * @return {goog.net.XhrIo.ResponseType} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getResponseType = function() {\n return this.responseType_;\n};\n\n\n/**\n * Sets whether a \"credentialed\" request that is aware of cookie and\n * authentication information should be made. This option is only supported by\n * browsers that support HTTP Access Control. As of this writing, this option\n * is not supported in IE.\n *\n * @param {boolean} withCredentials Whether this should be a \"credentialed\"\n * request.\n */\ngoog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {\n this.withCredentials_ = withCredentials;\n};\n\n\n/**\n * Gets whether a \"credentialed\" request is to be sent.\n * @return {boolean} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getWithCredentials = function() {\n return this.withCredentials_;\n};\n\n\n/**\n * Sets whether progress events are enabled for this request. Note\n * that progress events require pre-flight OPTIONS request handling\n * for CORS requests, and may cause trouble with older browsers. See\n * progressEventsEnabled_ for details.\n * @param {boolean} enabled Whether progress events should be enabled.\n */\ngoog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {\n this.progressEventsEnabled_ = enabled;\n};\n\n\n/**\n * Gets whether progress events are enabled.\n * @return {boolean} Whether progress events are enabled for this request.\n */\ngoog.net.XhrIo.prototype.getProgressEventsEnabled = function() {\n return this.progressEventsEnabled_;\n};\n\n\n/**\n * Instance send that actually uses XMLHttpRequest to make a server call.\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the\n * request.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters for opt_headers.\n */\ngoog.net.XhrIo.prototype.send = function(\n url, opt_method, opt_content, opt_headers) {\n if (this.xhr_) {\n throw new Error(\n '[goog.net.XhrIo] Object is active with another request=' +\n this.lastUri_ + '; newUri=' + url);\n }\n\n var method = opt_method ? opt_method.toUpperCase() : 'GET';\n\n this.lastUri_ = url;\n this.lastError_ = '';\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n this.lastMethod_ = method;\n this.errorDispatched_ = false;\n this.active_ = true;\n\n // Use the factory to create the XHR object and options\n this.xhr_ = this.createXhr();\n this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :\n goog.net.XmlHttp.getOptions();\n\n // Set up the onreadystatechange callback\n this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);\n\n // Set up upload/download progress events, if progress events are supported.\n if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {\n this.xhr_.onprogress =\n goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);\n if (this.xhr_.upload) {\n this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);\n }\n }\n\n /**\n * Try to open the XMLHttpRequest (always async), if an error occurs here it\n * is generally permission denied\n */\n try {\n goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));\n this.inOpen_ = true;\n this.xhr_.open(method, String(url), true); // Always async!\n this.inOpen_ = false;\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n return;\n }\n\n // We can't use null since this won't allow requests with form data to have a\n // content length specified which will cause some proxies to return a 411\n // error.\n var content = opt_content || '';\n\n var headers = this.headers.clone();\n\n // Add headers specific to this request\n if (opt_headers) {\n goog.structs.forEach(\n opt_headers, function(value, key) { headers.set(key, value); });\n }\n\n // Find whether a content type header is set, ignoring case.\n // HTTP header names are case-insensitive. See:\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\n var contentTypeKey =\n goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);\n\n var contentIsFormData =\n (goog.global['FormData'] && (content instanceof goog.global['FormData']));\n if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&\n !contentTypeKey && !contentIsFormData) {\n // For requests typically with form data, default to the url-encoded form\n // content type unless this is a FormData request. For FormData,\n // the browser will automatically add a multipart/form-data content type\n // with an appropriate multipart boundary.\n headers.set(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);\n }\n\n // Add the headers to the Xhr object\n headers.forEach(function(value, key) {\n this.xhr_.setRequestHeader(key, value);\n }, this);\n\n if (this.responseType_) {\n this.xhr_.responseType = this.responseType_;\n }\n // Set xhr_.withCredentials only when the value is different, or else in\n // synchronous XMLHtppRequest.open Firefox will throw an exception.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=736340\n if ('withCredentials' in this.xhr_ &&\n this.xhr_.withCredentials !== this.withCredentials_) {\n this.xhr_.withCredentials = this.withCredentials_;\n }\n\n /**\n * Try to send the request, or other wise report an error (404 not found).\n */\n try {\n this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.\n if (this.timeoutInterval_ > 0) {\n this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);\n goog.log.fine(\n this.logger_, this.formatMsg_(\n 'Will abort after ' + this.timeoutInterval_ +\n 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));\n if (this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =\n goog.bind(this.timeout_, this);\n } else {\n this.timeoutId_ =\n goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);\n }\n }\n goog.log.fine(this.logger_, this.formatMsg_('Sending request'));\n this.inSend_ = true;\n this.xhr_.send(content);\n this.inSend_ = false;\n\n } catch (err) {\n goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n }\n};\n\n\n/**\n * Determines if the argument is an XMLHttpRequest that supports the level 2\n * timeout value and event.\n *\n * Currently, FF 21.0 OS X has the fields but won't actually call the timeout\n * handler. Perhaps the confusion in the bug referenced below hasn't\n * entirely been resolved.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816\n *\n * @param {!goog.net.XhrLike.OrNative} xhr The request.\n * @return {boolean} True if the request supports level 2 timeout.\n * @private\n */\ngoog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {\n return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&\n typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' &&\n xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined;\n};\n\n\n/**\n * @param {string} header An HTTP header key.\n * @return {boolean} Whether the key is a content type header (ignoring\n * case.\n * @private\n */\ngoog.net.XhrIo.isContentTypeHeader_ = function(header) {\n return goog.string.caseInsensitiveEquals(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header);\n};\n\n\n/**\n * Creates a new XHR object.\n * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.\n * @protected\n */\ngoog.net.XhrIo.prototype.createXhr = function() {\n return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :\n goog.net.XmlHttp();\n};\n\n\n/**\n * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}\n * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts\n * the request.\n * @private\n */\ngoog.net.XhrIo.prototype.timeout_ = function() {\n if (typeof goog == 'undefined') {\n // If goog is undefined then the callback has occurred as the application\n // is unloading and will error. Thus we let it silently fail.\n } else if (this.xhr_) {\n this.lastError_ =\n 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';\n this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;\n goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));\n this.dispatchEvent(goog.net.EventType.TIMEOUT);\n this.abort(goog.net.ErrorCode.TIMEOUT);\n }\n};\n\n\n/**\n * Something errorred, so inactivate, fire error callback and clean up\n * @param {goog.net.ErrorCode} errorCode The error code.\n * @param {Error} err The error object.\n * @private\n */\ngoog.net.XhrIo.prototype.error_ = function(errorCode, err) {\n this.active_ = false;\n if (this.xhr_) {\n this.inAbort_ = true;\n this.xhr_.abort(); // Ensures XHR isn't hung (FF)\n this.inAbort_ = false;\n }\n this.lastError_ = err;\n this.lastErrorCode_ = errorCode;\n this.dispatchErrors_();\n this.cleanUpXhr_();\n};\n\n\n/**\n * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do\n * not dispatch multiple error events.\n * @private\n */\ngoog.net.XhrIo.prototype.dispatchErrors_ = function() {\n if (!this.errorDispatched_) {\n this.errorDispatched_ = true;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ERROR);\n }\n};\n\n\n/**\n * Abort the current XMLHttpRequest\n * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -\n * defaults to ABORT.\n */\ngoog.net.XhrIo.prototype.abort = function(opt_failureCode) {\n if (this.xhr_ && this.active_) {\n goog.log.fine(this.logger_, this.formatMsg_('Aborting'));\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ABORT);\n this.cleanUpXhr_();\n }\n};\n\n\n/**\n * Nullifies all callbacks to reduce risks of leaks.\n * @override\n * @protected\n */\ngoog.net.XhrIo.prototype.disposeInternal = function() {\n if (this.xhr_) {\n // We explicitly do not call xhr_.abort() unless active_ is still true.\n // This is to avoid unnecessarily aborting a successful request when\n // dispose() is called in a callback triggered by a complete response, but\n // in which browser cleanup has not yet finished.\n // (See http://b/issue?id=1684217.)\n if (this.active_) {\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n }\n this.cleanUpXhr_(true);\n }\n\n XhrIo.base(this, 'disposeInternal');\n};\n\n\n/**\n * Internal handler for the XHR object's readystatechange event. This method\n * checks the status and the readystate and fires the correct callbacks.\n * If the request has ended, the handlers are cleaned up and the XHR object is\n * nullified.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChange_ = function() {\n if (this.isDisposed()) {\n // This method is the target of an untracked goog.Timer.callOnce().\n return;\n }\n if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {\n // Were not being called from within a call to this.xhr_.send\n // this.xhr_.abort, or this.xhr_.open, so this is an entry point\n this.onReadyStateChangeEntryPoint_();\n } else {\n this.onReadyStateChangeHelper_();\n }\n};\n\n\n/**\n * Used to protect the onreadystatechange handler entry point. Necessary\n * as {#onReadyStateChange_} maybe called from within send or abort, this\n * method is only called when {#onReadyStateChange_} is called as an\n * entry point.\n * {@see #protectEntryPoints}\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {\n this.onReadyStateChangeHelper_();\n};\n\n\n/**\n * Helper for {@link #onReadyStateChange_}. This is used so that\n * entry point calls to {@link #onReadyStateChange_} can be routed through\n * {@link #onReadyStateChangeEntryPoint_}.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {\n if (!this.active_) {\n // can get called inside abort call\n return;\n }\n\n if (typeof goog == 'undefined') {\n // NOTE(user): If goog is undefined then the callback has occurred as the\n // application is unloading and will error. Thus we let it silently fail.\n\n } else if (\n this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&\n this.getStatus() == 2) {\n // NOTE(user): In IE if send() errors on a *local* request the readystate\n // is still changed to COMPLETE. We need to ignore it and allow the\n // try/catch around send() to pick up the error.\n goog.log.fine(\n this.logger_,\n this.formatMsg_('Local request error detected and ignored'));\n\n } else {\n // In IE when the response has been cached we sometimes get the callback\n // from inside the send call and this usually breaks code that assumes that\n // XhrIo is asynchronous. If that is the case we delay the callback\n // using a timer.\n if (this.inSend_ &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {\n goog.Timer.callOnce(this.onReadyStateChange_, 0, this);\n return;\n }\n\n this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);\n\n // readyState indicates the transfer has finished\n if (this.isComplete()) {\n goog.log.fine(this.logger_, this.formatMsg_('Request complete'));\n\n this.active_ = false;\n\n try {\n // Call the specific callbacks for success or failure. Only call the\n // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)\n if (this.isSuccess()) {\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.SUCCESS);\n } else {\n this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;\n this.lastError_ =\n this.getStatusText() + ' [' + this.getStatus() + ']';\n this.dispatchErrors_();\n }\n } finally {\n this.cleanUpXhr_();\n }\n }\n }\n};\n\n\n/**\n * Internal handler for the XHR object's onprogress event. Fires both a generic\n * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to\n * allow specific binding for each XHR progress event.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {boolean=} opt_isDownload Whether the current progress event is from a\n * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS\n * event should be dispatched.\n * @private\n */\ngoog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {\n goog.asserts.assert(\n e.type === goog.net.EventType.PROGRESS,\n 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');\n this.dispatchEvent(\n goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));\n this.dispatchEvent(\n goog.net.XhrIo.buildProgressEvent_(\n e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :\n goog.net.EventType.UPLOAD_PROGRESS));\n};\n\n\n/**\n * Creates a representation of the native ProgressEvent. IE doesn't support\n * constructing ProgressEvent via \"new\", and the alternatives (e.g.,\n * ProgressEvent.initProgressEvent) are non-standard or deprecated.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {!goog.net.EventType} eventType The type of the event.\n * @return {!ProgressEvent} The progress event.\n * @private\n */\ngoog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {\n return /** @type {!ProgressEvent} */ ({\n type: eventType,\n lengthComputable: e.lengthComputable,\n loaded: e.loaded,\n total: e.total,\n });\n};\n\n\n/**\n * Remove the listener to protect against leaks, and nullify the XMLHttpRequest\n * object.\n * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to\n * fire any events).\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {\n if (this.xhr_) {\n // Cancel any pending timeout event handler.\n this.cleanUpTimeoutTimer_();\n\n // Save reference so we can mark it as closed after the READY event. The\n // READY event may trigger another request, thus we must nullify this.xhr_\n var xhr = this.xhr_;\n var clearedOnReadyStateChange =\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\n goog.nullFunction :\n null;\n this.xhr_ = null;\n this.xhrOptions_ = null;\n\n if (!opt_fromDispose) {\n this.dispatchEvent(goog.net.EventType.READY);\n }\n\n try {\n // NOTE(user): Not nullifying in FireFox can still leak if the callbacks\n // are defined in the same scope as the instance of XhrIo. But, IE doesn't\n // allow you to set the onreadystatechange to NULL so nullFunction is\n // used.\n xhr.onreadystatechange = clearedOnReadyStateChange;\n } catch (e) {\n // This seems to occur with a Gears HTTP request. Delayed the setting of\n // this onreadystatechange until after READY is sent out and catching the\n // error to see if we can track down the problem.\n goog.log.error(\n this.logger_,\n 'Problem encountered resetting onreadystatechange: ' + e.message);\n }\n }\n};\n\n\n/**\n * Make sure the timeout timer isn't running.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {\n if (this.xhr_ && this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;\n }\n if (this.timeoutId_) {\n goog.Timer.clear(this.timeoutId_);\n this.timeoutId_ = null;\n }\n};\n\n\n/**\n * @return {boolean} Whether there is an active request.\n */\ngoog.net.XhrIo.prototype.isActive = function() {\n return !!this.xhr_;\n};\n\n\n/**\n * @return {boolean} Whether the request has completed.\n */\ngoog.net.XhrIo.prototype.isComplete = function() {\n return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n};\n\n\n/**\n * @return {boolean} Whether the request completed with a success.\n */\ngoog.net.XhrIo.prototype.isSuccess = function() {\n var status = this.getStatus();\n // A zero status code is considered successful for local files.\n return goog.net.HttpStatus.isSuccess(status) ||\n status === 0 && !this.isLastUriEffectiveSchemeHttp_();\n};\n\n\n/**\n * @return {boolean} whether the effective scheme of the last URI that was\n * fetched was 'http' or 'https'.\n * @private\n */\ngoog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {\n var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\n return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);\n};\n\n\n/**\n * Get the readystate from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.\n */\ngoog.net.XhrIo.prototype.getReadyState = function() {\n return this.xhr_ ?\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\n goog.net.XmlHttp.ReadyState\n .UNINITIALIZED;\n};\n\n\n/**\n * Get the status from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {number} Http status.\n */\ngoog.net.XhrIo.prototype.getStatus = function() {\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.status :\n -1;\n } catch (e) {\n return -1;\n }\n};\n\n\n/**\n * Get the status text from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {string} Status text.\n */\ngoog.net.XhrIo.prototype.getStatusText = function() {\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.statusText :\n '';\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get status: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the last Uri that was requested\n * @return {string} Last Uri.\n */\ngoog.net.XhrIo.prototype.getLastUri = function() {\n return String(this.lastUri_);\n};\n\n\n/**\n * Get the response text from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {string} Result from the server, or '' if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseText = function() {\n try {\n return this.xhr_ ? this.xhr_.responseText : '';\n } catch (e) {\n // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute\n // states that responseText should return '' (and responseXML null)\n // when the state is not LOADING or DONE. Instead, IE can\n // throw unexpected exceptions, for example when a request is aborted\n // or no data is available yet.\n goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the response body from the Xhr object. This property is only available\n * in IE since version 7 according to MSDN:\n * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx\n * Will only return correct result when called from the context of a callback.\n *\n * One option is to construct a VBArray from the returned object and convert\n * it to a JavaScript array using the toArray method:\n * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`\n * This will result in an array of numbers in the range of [0..255]\n *\n * Another option is to use the VBScript CStr method to convert it into a\n * string as outlined in http://stackoverflow.com/questions/1919972\n *\n * @return {Object} Binary result from the server or null if not available.\n */\ngoog.net.XhrIo.prototype.getResponseBody = function() {\n try {\n if (this.xhr_ && 'responseBody' in this.xhr_) {\n return this.xhr_['responseBody'];\n }\n } catch (e) {\n // IE can throw unexpected exceptions, for example when a request is aborted\n // or no data is yet available.\n goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);\n }\n return null;\n};\n\n\n/**\n * Get the response XML from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {Document} The DOM Document representing the XML file, or null\n * if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseXml = function() {\n try {\n return this.xhr_ ? this.xhr_.responseXML : null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the response and evaluates it as JSON from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for\n * stripping of the response before parsing. This needs to be set only if\n * your backend server prepends the same prefix string to the JSON response.\n * @throws Error if the response text is invalid JSON.\n * @return {Object|undefined} JavaScript object.\n */\ngoog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {\n if (!this.xhr_) {\n return undefined;\n }\n\n var responseText = this.xhr_.responseText;\n if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {\n responseText = responseText.substring(opt_xssiPrefix.length);\n }\n\n return goog.json.hybrid.parse(responseText);\n};\n\n\n/**\n * Get the response as the type specificed by {@link #setResponseType}. At time\n * of writing, this is only directly supported in very recent versions of WebKit\n * (10.0.612.1 dev and later). If the field is not supported directly, we will\n * try to emulate it.\n *\n * Emulating the response means following the rules laid out at\n * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute\n *\n * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only\n * response types of DEFAULT or TEXT may be used, and the response returned will\n * be the text response.\n *\n * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),\n * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the\n * response returned will be either the text response or the Mozilla\n * implementation of the array buffer response.\n *\n * On browsers will full support, any valid response type supported by the\n * browser may be used, and the response provided by the browser will be\n * returned.\n *\n * @return {*} The response.\n */\ngoog.net.XhrIo.prototype.getResponse = function() {\n try {\n if (!this.xhr_) {\n return null;\n }\n if ('response' in this.xhr_) {\n return this.xhr_.response;\n }\n switch (this.responseType_) {\n case ResponseType.DEFAULT:\n case ResponseType.TEXT:\n return this.xhr_.responseText;\n // DOCUMENT and BLOB don't need to be handled here because they are\n // introduced in the same spec that adds the .response field, and would\n // have been caught above.\n // ARRAY_BUFFER needs an implementation for Firefox 4, where it was\n // implemented using a draft spec rather than the final spec.\n case ResponseType.ARRAY_BUFFER:\n if ('mozResponseArrayBuffer' in this.xhr_) {\n return this.xhr_.mozResponseArrayBuffer;\n }\n }\n // Fell through to a response type that is not supported on this browser.\n goog.log.error(\n this.logger_, 'Response type ' + this.responseType_ + ' is not ' +\n 'supported on this browser');\n return null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get response: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object\n * Will only return correct result when called from the context of a callback\n * and the request has completed\n * @param {string} key The name of the response-header to retrieve.\n * @return {string|undefined} The value of the response-header named key.\n */\ngoog.net.XhrIo.prototype.getResponseHeader = function(key) {\n if (!this.xhr_ || !this.isComplete()) {\n return undefined;\n }\n\n var value = this.xhr_.getResponseHeader(key);\n return value === null ? undefined : value;\n};\n\n\n/**\n * Gets the text of all the headers in the response.\n * Will only return correct result when called from the context of a callback\n * and the request has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\n // getAllResponseHeaders can return null if no response has been received,\n // ensure we always return an empty string.\n return this.xhr_ && this.isComplete() ?\n (this.xhr_.getAllResponseHeaders() || '') :\n '';\n};\n\n\n/**\n * Returns all response headers as a key-value map.\n * Multiple values for the same header key can be combined into one,\n * separated by a comma and a space.\n * Note that the native getResponseHeader method for retrieving a single header\n * does a case insensitive match on the header name. This method does not\n * include any case normalization logic, it will just return a key-value\n * representation of the headers.\n * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method\n * @return {!Object<string, string>} An object with the header keys as keys\n * and header values as values.\n */\ngoog.net.XhrIo.prototype.getResponseHeaders = function() {\n // TODO(user): Make this function parse headers as per the spec\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\n\n var headersObject = {};\n var headersArray = this.getAllResponseHeaders().split('\\r\\n');\n for (var i = 0; i < headersArray.length; i++) {\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\n continue;\n }\n var keyValue =\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\n var key = keyValue[0];\n var value = keyValue[1];\n\n if (typeof value !== 'string') {\n // There must be a value but it can be the empty string.\n continue;\n }\n\n // Whitespace at the start and end of the value is meaningless.\n value = value.trim();\n // The key should not contain whitespace but we currently ignore that.\n\n var values = headersObject[key] || [];\n headersObject[key] = values;\n values.push(value);\n }\n\n return goog.object.map(headersObject, function(values) {\n return values.join(', ');\n });\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object.\n * As opposed to {@link #getResponseHeader}, this method does not require that\n * the request has completed.\n * @param {string} key The name of the response-header to retrieve.\n * @return {?string} The value of the response-header, or null if it is\n * unavailable.\n */\ngoog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {\n return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;\n};\n\n\n/**\n * Gets the text of all the headers in the response. As opposed to\n * {@link #getAllResponseHeaders}, this method does not require that the request\n * has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {\n return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';\n};\n\n\n/**\n * Get the last error message\n * @return {!goog.net.ErrorCode} Last error code.\n */\ngoog.net.XhrIo.prototype.getLastErrorCode = function() {\n return this.lastErrorCode_;\n};\n\n\n/**\n * Get the last error message\n * @return {string} Last error message.\n */\ngoog.net.XhrIo.prototype.getLastError = function() {\n return typeof this.lastError_ === 'string' ? this.lastError_ :\n String(this.lastError_);\n};\n\n\n/**\n * Adds the last method, status and URI to the message. This is used to add\n * this information to the logging calls.\n * @param {string} msg The message text that we want to add the extra text to.\n * @return {string} The message with the extra text appended.\n * @private\n */\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\n return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +\n this.getStatus() + ']';\n};\n\n\n// Register the xhr handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n });\n}); // goog.scope\n","// Copyright 2006 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 Common events for the network classes.\n */\n\n\ngoog.provide('goog.net.EventType');\n\n\n/**\n * Event names for network events\n * @enum {string}\n */\ngoog.net.EventType = {\n COMPLETE: 'complete',\n SUCCESS: 'success',\n ERROR: 'error',\n ABORT: 'abort',\n READY: 'ready',\n READY_STATE_CHANGE: 'readystatechange',\n TIMEOUT: 'timeout',\n INCREMENTAL_DATA: 'incrementaldata',\n PROGRESS: 'progress',\n // DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by\n // goog.net.XhrIo to allow binding listeners specific to each type of\n // progress.\n DOWNLOAD_PROGRESS: 'downloadprogress',\n UPLOAD_PROGRESS: 'uploadprogress',\n};\n","// Copyright 2007 Bob Ippolito. All Rights Reserved.\n// Modifications Copyright 2009 The Closure Library Authors. All Rights\n// Reserved.\n\n/**\n * @license Portions of this code are from MochiKit, received by\n * The Closure Authors under the MIT license. All other code is Copyright\n * 2005-2009 The Closure Authors. All Rights Reserved.\n */\n\n/**\n * @fileoverview Classes for tracking asynchronous operations and handling the\n * results. The Deferred object here is patterned after the Deferred object in\n * the Twisted python networking framework.\n *\n * See: http://twistedmatrix.com/projects/core/documentation/howto/defer.html\n *\n * Based on the Dojo code which in turn is based on the MochiKit code.\n *\n */\n\ngoog.provide('goog.async.Deferred');\ngoog.provide('goog.async.Deferred.AlreadyCalledError');\ngoog.provide('goog.async.Deferred.CanceledError');\n\ngoog.require('goog.Promise');\ngoog.require('goog.Thenable');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.debug.Error');\n\n\n\n/**\n * A Deferred represents the result of an asynchronous operation. A Deferred\n * instance has no result when it is created, and is \"fired\" (given an initial\n * result) by calling `callback` or `errback`.\n *\n * Once fired, the result is passed through a sequence of callback functions\n * registered with `addCallback` or `addErrback`. The functions may\n * mutate the result before it is passed to the next function in the sequence.\n *\n * Callbacks and errbacks may be added at any time, including after the Deferred\n * has been \"fired\". If there are no pending actions in the execution sequence\n * of a fired Deferred, any new callback functions will be called with the last\n * computed result. Adding a callback function is the only way to access the\n * result of the Deferred.\n *\n * If a Deferred operation is canceled, an optional user-provided cancellation\n * function is invoked which may perform any special cleanup, followed by firing\n * the Deferred's errback sequence with a `CanceledError`. If the\n * Deferred has already fired, cancellation is ignored.\n *\n * Deferreds may be templated to a specific type they produce using generics\n * with syntax such as:\n *\n * /** @type {goog.async.Deferred<string>} *\\\n * var d = new goog.async.Deferred();\n * // Compiler can infer that foo is a string.\n * d.addCallback(function(foo) {...});\n * d.callback('string'); // Checked to be passed a string\n *\n * Since deferreds are often used to produce different values across a chain,\n * the type information is not propagated across chains, but rather only\n * associated with specifically cast objects.\n *\n * @param {Function=} opt_onCancelFunction A function that will be called if the\n * Deferred is canceled. If provided, this function runs before the\n * Deferred is fired with a `CanceledError`.\n * @param {Object=} opt_defaultScope The default object context to call\n * callbacks and errbacks in.\n * @constructor\n * @implements {goog.Thenable<VALUE>}\n * @template VALUE\n */\ngoog.async.Deferred = function(opt_onCancelFunction, opt_defaultScope) {\n /**\n * Entries in the sequence are arrays containing a callback, an errback, and\n * an optional scope. The callback or errback in an entry may be null.\n * @type {!Array<!Array>}\n * @private\n */\n this.sequence_ = [];\n\n /**\n * Optional function that will be called if the Deferred is canceled.\n * @type {Function|undefined}\n * @private\n */\n this.onCancelFunction_ = opt_onCancelFunction;\n\n /**\n * The default scope to execute callbacks and errbacks in.\n * @type {Object}\n * @private\n */\n this.defaultScope_ = opt_defaultScope || null;\n\n /**\n * Whether the Deferred has been fired.\n * @type {boolean}\n * @private\n */\n this.fired_ = false;\n\n /**\n * Whether the last result in the execution sequence was an error.\n * @type {boolean}\n * @private\n */\n this.hadError_ = false;\n\n /**\n * The current Deferred result, updated as callbacks and errbacks are\n * executed.\n * @type {*}\n * @private\n */\n this.result_ = undefined;\n\n /**\n * Whether the Deferred is blocked waiting on another Deferred to fire. If a\n * callback or errback returns a Deferred as a result, the execution sequence\n * is blocked until that Deferred result becomes available.\n * @type {boolean}\n * @private\n */\n this.blocked_ = false;\n\n /**\n * Whether this Deferred is blocking execution of another Deferred. If this\n * instance was returned as a result in another Deferred's execution\n * sequence,that other Deferred becomes blocked until this instance's\n * execution sequence completes. No additional callbacks may be added to a\n * Deferred once it is blocking another instance.\n * @type {boolean}\n * @private\n */\n this.blocking_ = false;\n\n /**\n * Whether the Deferred has been canceled without having a custom cancel\n * function.\n * @type {boolean}\n * @private\n */\n this.silentlyCanceled_ = false;\n\n /**\n * If an error is thrown during Deferred execution with no errback to catch\n * it, the error is rethrown after a timeout. Reporting the error after a\n * timeout allows execution to continue in the calling context (empty when\n * no error is scheduled).\n * @type {number}\n * @private\n */\n this.unhandledErrorId_ = 0;\n\n /**\n * If this Deferred was created by branch(), this will be the \"parent\"\n * Deferred.\n * @type {?goog.async.Deferred}\n * @private\n */\n this.parent_ = null;\n\n /**\n * The number of Deferred objects that have been branched off this one. This\n * will be decremented whenever a branch is fired or canceled.\n * @type {number}\n * @private\n */\n this.branches_ = 0;\n\n if (goog.async.Deferred.LONG_STACK_TRACES) {\n /**\n * Holds the stack trace at time of deferred creation if the JS engine\n * provides the Error.captureStackTrace API.\n * @private {?string}\n */\n this.constructorStack_ = null;\n if (Error.captureStackTrace) {\n var target = { stack: '' };\n Error.captureStackTrace(target, goog.async.Deferred);\n // Check if Error.captureStackTrace worked. It fails in gjstest.\n if (typeof target.stack == 'string') {\n // Remove first line and force stringify to prevent memory leak due to\n // holding on to actual stack frames.\n this.constructorStack_ = target.stack.replace(/^[^\\n]*\\n/, '');\n }\n }\n }\n};\n\n\n/**\n * @define {boolean} Whether unhandled errors should always get rethrown to the\n * global scope. Defaults to false.\n */\ngoog.async.Deferred.STRICT_ERRORS =\n goog.define('goog.async.Deferred.STRICT_ERRORS', false);\n\n\n/**\n * @define {boolean} Whether to attempt to make stack traces long. Defaults to\n * false.\n */\ngoog.async.Deferred.LONG_STACK_TRACES =\n goog.define('goog.async.Deferred.LONG_STACK_TRACES', false);\n\n\n/**\n * Cancels a Deferred that has not yet been fired, or is blocked on another\n * deferred operation. If this Deferred is waiting for a blocking Deferred to\n * fire, the blocking Deferred will also be canceled.\n *\n * If this Deferred was created by calling branch() on a parent Deferred with\n * opt_propagateCancel set to true, the parent may also be canceled. If\n * opt_deepCancel is set, cancel() will be called on the parent (as well as any\n * other ancestors if the parent is also a branch). If one or more branches were\n * created with opt_propagateCancel set to true, the parent will be canceled if\n * cancel() is called on all of those branches.\n *\n * @param {boolean=} opt_deepCancel If true, cancels this Deferred's parent even\n * if cancel() hasn't been called on some of the parent's branches. Has no\n * effect on a branch without opt_propagateCancel set to true.\n */\ngoog.async.Deferred.prototype.cancel = function(opt_deepCancel) {\n if (!this.hasFired()) {\n if (this.parent_) {\n // Get rid of the parent reference before potentially running the parent's\n // canceler function to ensure that this cancellation isn't\n // double-counted.\n var parent = this.parent_;\n delete this.parent_;\n if (opt_deepCancel) {\n parent.cancel(opt_deepCancel);\n } else {\n parent.branchCancel_();\n }\n }\n\n if (this.onCancelFunction_) {\n // Call in user-specified scope.\n this.onCancelFunction_.call(this.defaultScope_, this);\n } else {\n this.silentlyCanceled_ = true;\n }\n if (!this.hasFired()) {\n this.errback(new goog.async.Deferred.CanceledError(this));\n }\n } else if (this.result_ instanceof goog.async.Deferred) {\n this.result_.cancel();\n }\n};\n\n\n/**\n * Handle a single branch being canceled. Once all branches are canceled, this\n * Deferred will be canceled as well.\n *\n * @private\n */\ngoog.async.Deferred.prototype.branchCancel_ = function() {\n this.branches_--;\n if (this.branches_ <= 0) {\n this.cancel();\n }\n};\n\n\n/**\n * Called after a blocking Deferred fires. Unblocks this Deferred and resumes\n * its execution sequence.\n *\n * @param {boolean} isSuccess Whether the result is a success or an error.\n * @param {*} res The result of the blocking Deferred.\n * @private\n */\ngoog.async.Deferred.prototype.continue_ = function(isSuccess, res) {\n this.blocked_ = false;\n this.updateResult_(isSuccess, res);\n};\n\n\n/**\n * Updates the current result based on the success or failure of the last action\n * in the execution sequence.\n *\n * @param {boolean} isSuccess Whether the new result is a success or an error.\n * @param {*} res The result.\n * @private\n */\ngoog.async.Deferred.prototype.updateResult_ = function(isSuccess, res) {\n this.fired_ = true;\n this.result_ = res;\n this.hadError_ = !isSuccess;\n this.fire_();\n};\n\n\n/**\n * Verifies that the Deferred has not yet been fired.\n *\n * @private\n * @throws {Error} If this has already been fired.\n */\ngoog.async.Deferred.prototype.check_ = function() {\n if (this.hasFired()) {\n if (!this.silentlyCanceled_) {\n throw new goog.async.Deferred.AlreadyCalledError(this);\n }\n this.silentlyCanceled_ = false;\n }\n};\n\n\n/**\n * Fire the execution sequence for this Deferred by passing the starting result\n * to the first registered callback.\n * @param {VALUE=} opt_result The starting result.\n */\ngoog.async.Deferred.prototype.callback = function(opt_result) {\n this.check_();\n this.assertNotDeferred_(opt_result);\n this.updateResult_(true /* isSuccess */, opt_result);\n};\n\n\n/**\n * Fire the execution sequence for this Deferred by passing the starting error\n * result to the first registered errback.\n * @param {*=} opt_result The starting error.\n */\ngoog.async.Deferred.prototype.errback = function(opt_result) {\n this.check_();\n this.assertNotDeferred_(opt_result);\n this.makeStackTraceLong_(opt_result);\n this.updateResult_(false /* isSuccess */, opt_result);\n};\n\n\n/**\n * Attempt to make the error's stack trace be long in that it contains the\n * stack trace from the point where the deferred was created on top of the\n * current stack trace to give additional context.\n * @param {*} error\n * @private\n * @suppress {missingProperties} error.stack\n */\ngoog.async.Deferred.prototype.makeStackTraceLong_ = function(error) {\n if (!goog.async.Deferred.LONG_STACK_TRACES) {\n return;\n }\n if (this.constructorStack_ && goog.isObject(error) && error.stack &&\n // Stack looks like it was system generated. See\n // https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi\n (/^[^\\n]+(\\n [^\\n]+)+/).test(error.stack)) {\n error.stack = error.stack + '\\nDEFERRED OPERATION:\\n' +\n this.constructorStack_;\n }\n};\n\n\n/**\n * Asserts that an object is not a Deferred.\n * @param {*} obj The object to test.\n * @throws {Error} Throws an exception if the object is a Deferred.\n * @private\n */\ngoog.async.Deferred.prototype.assertNotDeferred_ = function(obj) {\n goog.asserts.assert(\n !(obj instanceof goog.async.Deferred),\n 'An execution sequence may not be initiated with a blocking Deferred.');\n};\n\n\n/**\n * Register a callback function to be called with a successful result. If no\n * value is returned by the callback function, the result value is unchanged. If\n * a new value is returned, it becomes the Deferred result and will be passed to\n * the next callback in the execution sequence.\n *\n * If the function throws an error, the error becomes the new result and will be\n * passed to the next errback in the execution chain.\n *\n * If the function returns a Deferred, the execution sequence will be blocked\n * until that Deferred fires. Its result will be passed to the next callback (or\n * errback if it is an error result) in this Deferred's execution sequence.\n *\n * @param {function(this:T,VALUE):?} cb The function to be called with a\n * successful result.\n * @param {T=} opt_scope An optional scope to call the callback in.\n * @return {!goog.async.Deferred} This Deferred.\n * @template T\n */\ngoog.async.Deferred.prototype.addCallback = function(cb, opt_scope) {\n return this.addCallbacks(cb, null, opt_scope);\n};\n\n\n/**\n * Register a callback function to be called with an error result. If no value\n * is returned by the function, the error result is unchanged. If a new error\n * value is returned or thrown, that error becomes the Deferred result and will\n * be passed to the next errback in the execution sequence.\n *\n * If the errback function handles the error by returning a non-error value,\n * that result will be passed to the next normal callback in the sequence.\n *\n * If the function returns a Deferred, the execution sequence will be blocked\n * until that Deferred fires. Its result will be passed to the next callback (or\n * errback if it is an error result) in this Deferred's execution sequence.\n *\n * @param {function(this:T,?):?} eb The function to be called on an\n * unsuccessful result.\n * @param {T=} opt_scope An optional scope to call the errback in.\n * @return {!goog.async.Deferred<VALUE>} This Deferred.\n * @template T\n */\ngoog.async.Deferred.prototype.addErrback = function(eb, opt_scope) {\n return this.addCallbacks(null, eb, opt_scope);\n};\n\n\n/**\n * Registers one function as both a callback and errback.\n *\n * @param {function(this:T,?):?} f The function to be called on any result.\n * @param {T=} opt_scope An optional scope to call the function in.\n * @return {!goog.async.Deferred} This Deferred.\n * @template T\n */\ngoog.async.Deferred.prototype.addBoth = function(f, opt_scope) {\n return this.addCallbacks(f, f, opt_scope);\n};\n\n\n/**\n * Like addBoth, but propagates uncaught exceptions in the errback.\n *\n * @param {function(this:T,?):?} f The function to be called on any result.\n * @param {T=} opt_scope An optional scope to call the function in.\n * @return {!goog.async.Deferred<VALUE>} This Deferred.\n * @template T\n */\ngoog.async.Deferred.prototype.addFinally = function(f, opt_scope) {\n return this.addCallbacks(f, function(err) {\n var result = f.call(/** @type {?} */ (this), err);\n if (result === undefined) {\n throw err;\n }\n return result;\n }, opt_scope);\n};\n\n\n/**\n * Registers a callback function and an errback function at the same position\n * in the execution sequence. Only one of these functions will execute,\n * depending on the error state during the execution sequence.\n *\n * NOTE: This is not equivalent to {@code def.addCallback().addErrback()}! If\n * the callback is invoked, the errback will be skipped, and vice versa.\n *\n * @param {?(function(this:T,VALUE):?)} cb The function to be called on a\n * successful result.\n * @param {?(function(this:T,?):?)} eb The function to be called on an\n * unsuccessful result.\n * @param {T=} opt_scope An optional scope to call the functions in.\n * @return {!goog.async.Deferred} This Deferred.\n * @template T\n */\ngoog.async.Deferred.prototype.addCallbacks = function(cb, eb, opt_scope) {\n goog.asserts.assert(!this.blocking_, 'Blocking Deferreds can not be re-used');\n this.sequence_.push([cb, eb, opt_scope]);\n if (this.hasFired()) {\n this.fire_();\n }\n return this;\n};\n\n\n/**\n * Implements {@see goog.Thenable} for seamless integration with\n * {@see goog.Promise}.\n * Deferred results are mutable and may represent multiple values over\n * their lifetime. Calling `then` on a Deferred returns a Promise\n * with the result of the Deferred at that point in its callback chain.\n * Note that if the Deferred result is never mutated, and only\n * `then` calls are made, the Deferred will behave like a Promise.\n *\n * @override\n */\ngoog.async.Deferred.prototype.then = function(opt_onFulfilled, opt_onRejected,\n opt_context) {\n var resolve, reject;\n var promise = new goog.Promise(function(res, rej) {\n // Copying resolvers to outer scope, so that they are available when the\n // deferred callback fires (which may be synchronous).\n resolve = res;\n reject = rej;\n });\n this.addCallbacks(resolve, function(reason) {\n if (reason instanceof goog.async.Deferred.CanceledError) {\n promise.cancel();\n } else {\n reject(reason);\n }\n });\n return promise.then(opt_onFulfilled, opt_onRejected, opt_context);\n};\ngoog.Thenable.addImplementation(goog.async.Deferred);\n\n\n/**\n * Links another Deferred to the end of this Deferred's execution sequence. The\n * result of this execution sequence will be passed as the starting result for\n * the chained Deferred, invoking either its first callback or errback.\n *\n * @param {!goog.async.Deferred} otherDeferred The Deferred to chain.\n * @return {!goog.async.Deferred} This Deferred.\n */\ngoog.async.Deferred.prototype.chainDeferred = function(otherDeferred) {\n this.addCallbacks(\n otherDeferred.callback, otherDeferred.errback, otherDeferred);\n return this;\n};\n\n\n/**\n * Makes this Deferred wait for another Deferred's execution sequence to\n * complete before continuing.\n *\n * This is equivalent to adding a callback that returns `otherDeferred`,\n * but doesn't prevent additional callbacks from being added to\n * `otherDeferred`.\n *\n * @param {!goog.async.Deferred|!goog.Thenable} otherDeferred The Deferred\n * to wait for.\n * @return {!goog.async.Deferred} This Deferred.\n */\ngoog.async.Deferred.prototype.awaitDeferred = function(otherDeferred) {\n if (!(otherDeferred instanceof goog.async.Deferred)) {\n // The Thenable case.\n return this.addCallback(function() {\n return otherDeferred;\n });\n }\n return this.addCallback(goog.bind(otherDeferred.branch, otherDeferred));\n};\n\n\n/**\n * Creates a branch off this Deferred's execution sequence, and returns it as a\n * new Deferred. The branched Deferred's starting result will be shared with the\n * parent at the point of the branch, even if further callbacks are added to the\n * parent.\n *\n * All branches at the same stage in the execution sequence will receive the\n * same starting value.\n *\n * @param {boolean=} opt_propagateCancel If cancel() is called on every child\n * branch created with opt_propagateCancel, the parent will be canceled as\n * well.\n * @return {!goog.async.Deferred<VALUE>} A Deferred that will be started with\n * the computed result from this stage in the execution sequence.\n */\ngoog.async.Deferred.prototype.branch = function(opt_propagateCancel) {\n var d = new goog.async.Deferred();\n this.chainDeferred(d);\n if (opt_propagateCancel) {\n d.parent_ = this;\n this.branches_++;\n }\n return d;\n};\n\n\n/**\n * @return {boolean} Whether the execution sequence has been started on this\n * Deferred by invoking `callback` or `errback`.\n */\ngoog.async.Deferred.prototype.hasFired = function() {\n return this.fired_;\n};\n\n\n/**\n * @param {*} res The latest result in the execution sequence.\n * @return {boolean} Whether the current result is an error that should cause\n * the next errback to fire. May be overridden by subclasses to handle\n * special error types.\n * @protected\n */\ngoog.async.Deferred.prototype.isError = function(res) {\n return res instanceof Error;\n};\n\n\n/**\n * @return {boolean} Whether an errback exists in the remaining sequence.\n * @private\n */\ngoog.async.Deferred.prototype.hasErrback_ = function() {\n return goog.array.some(this.sequence_, function(sequenceRow) {\n // The errback is the second element in the array.\n return goog.isFunction(sequenceRow[1]);\n });\n};\n\n\n/**\n * Exhausts the execution sequence while a result is available. The result may\n * be modified by callbacks or errbacks, and execution will block if the\n * returned result is an incomplete Deferred.\n *\n * @private\n */\ngoog.async.Deferred.prototype.fire_ = function() {\n if (this.unhandledErrorId_ && this.hasFired() && this.hasErrback_()) {\n // It is possible to add errbacks after the Deferred has fired. If a new\n // errback is added immediately after the Deferred encountered an unhandled\n // error, but before that error is rethrown, the error is unscheduled.\n goog.async.Deferred.unscheduleError_(this.unhandledErrorId_);\n this.unhandledErrorId_ = 0;\n }\n\n if (this.parent_) {\n this.parent_.branches_--;\n delete this.parent_;\n }\n\n var res = this.result_;\n var unhandledException = false;\n var isNewlyBlocked = false;\n\n while (this.sequence_.length && !this.blocked_) {\n var sequenceEntry = this.sequence_.shift();\n\n var callback = sequenceEntry[0];\n var errback = sequenceEntry[1];\n var scope = sequenceEntry[2];\n\n var f = this.hadError_ ? errback : callback;\n if (f) {\n\n try {\n var ret = f.call(scope || this.defaultScope_, res);\n\n // If no result, then use previous result.\n if (ret !== undefined) {\n // Bubble up the error as long as the return value hasn't changed.\n this.hadError_ = this.hadError_ && (ret == res || this.isError(ret));\n this.result_ = res = ret;\n }\n\n if (goog.Thenable.isImplementedBy(res) ||\n (typeof goog.global['Promise'] === 'function' &&\n res instanceof goog.global['Promise'])) {\n isNewlyBlocked = true;\n this.blocked_ = true;\n }\n\n } catch (ex) {\n res = ex;\n this.hadError_ = true;\n this.makeStackTraceLong_(res);\n\n if (!this.hasErrback_()) {\n // If an error is thrown with no additional errbacks in the queue,\n // prepare to rethrow the error.\n unhandledException = true;\n }\n }\n }\n }\n\n this.result_ = res;\n\n if (isNewlyBlocked) {\n var onCallback = goog.bind(this.continue_, this, true /* isSuccess */);\n var onErrback = goog.bind(this.continue_, this, false /* isSuccess */);\n\n if (res instanceof goog.async.Deferred) {\n res.addCallbacks(onCallback, onErrback);\n res.blocking_ = true;\n } else {\n /** @type {!IThenable} */ (res).then(onCallback, onErrback);\n }\n } else if (goog.async.Deferred.STRICT_ERRORS && this.isError(res) &&\n !(res instanceof goog.async.Deferred.CanceledError)) {\n this.hadError_ = true;\n unhandledException = true;\n }\n\n if (unhandledException) {\n // Rethrow the unhandled error after a timeout. Execution will continue, but\n // the error will be seen by global handlers and the user. The throw will\n // be canceled if another errback is appended before the timeout executes.\n // The error's original stack trace is preserved where available.\n this.unhandledErrorId_ = goog.async.Deferred.scheduleError_(res);\n }\n};\n\n\n/**\n * Creates a Deferred that has an initial result.\n *\n * @param {*=} opt_result The result.\n * @return {!goog.async.Deferred} The new Deferred.\n */\ngoog.async.Deferred.succeed = function(opt_result) {\n var d = new goog.async.Deferred();\n d.callback(opt_result);\n return d;\n};\n\n\n/**\n * Creates a Deferred that fires when the given promise resolves.\n * Use only during migration to Promises.\n *\n * Note: If the promise resolves to a thenable value (which is not allowed by\n * conforming promise implementations), then the deferred may behave\n * unexpectedly as it tries to wait on it. This should not be a risk when using\n * goog.Promise, goog.async.Deferred, or native Promise objects.\n *\n * @param {!IThenable<T>} promise\n * @return {!goog.async.Deferred<T>} The new Deferred.\n * @template T\n */\ngoog.async.Deferred.fromPromise = function(promise) {\n var d = new goog.async.Deferred();\n promise.then(\n function(value) {\n d.callback(value);\n },\n function(error) {\n d.errback(error);\n });\n return d;\n};\n\n\n/**\n * Creates a Deferred that has an initial error result.\n *\n * @param {*} res The error result.\n * @return {!goog.async.Deferred} The new Deferred.\n */\ngoog.async.Deferred.fail = function(res) {\n var d = new goog.async.Deferred();\n d.errback(res);\n return d;\n};\n\n\n/**\n * Creates a Deferred that has already been canceled.\n *\n * @return {!goog.async.Deferred} The new Deferred.\n */\ngoog.async.Deferred.canceled = function() {\n var d = new goog.async.Deferred();\n d.cancel();\n return d;\n};\n\n\n/**\n * Normalizes values that may or may not be Deferreds.\n *\n * If the input value is a Deferred, the Deferred is branched (so the original\n * execution sequence is not modified) and the input callback added to the new\n * branch. The branch is returned to the caller.\n *\n * If the input value is not a Deferred, the callback will be executed\n * immediately and an already firing Deferred will be returned to the caller.\n *\n * In the following (contrived) example, if <code>isImmediate</code> is true\n * then 3 is alerted immediately, otherwise 6 is alerted after a 2-second delay.\n *\n * <pre>\n * var value;\n * if (isImmediate) {\n * value = 3;\n * } else {\n * value = new goog.async.Deferred();\n * setTimeout(function() { value.callback(6); }, 2000);\n * }\n *\n * var d = goog.async.Deferred.when(value, alert);\n * </pre>\n *\n * @param {*} value Deferred or normal value to pass to the callback.\n * @param {function(this:T, ?):?} callback The callback to execute.\n * @param {T=} opt_scope An optional scope to call the callback in.\n * @return {!goog.async.Deferred} A new Deferred that will call the input\n * callback with the input value.\n * @template T\n */\ngoog.async.Deferred.when = function(value, callback, opt_scope) {\n if (value instanceof goog.async.Deferred) {\n return value.branch(true).addCallback(callback, opt_scope);\n } else {\n return goog.async.Deferred.succeed(value).addCallback(callback, opt_scope);\n }\n};\n\n\n\n/**\n * An error sub class that is used when a Deferred has already been called.\n * @param {!goog.async.Deferred} deferred The Deferred.\n *\n * @constructor\n * @extends {goog.debug.Error}\n */\ngoog.async.Deferred.AlreadyCalledError = function(deferred) {\n goog.debug.Error.call(this);\n\n /**\n * The Deferred that raised this error.\n * @type {goog.async.Deferred}\n */\n this.deferred = deferred;\n};\ngoog.inherits(goog.async.Deferred.AlreadyCalledError, goog.debug.Error);\n\n\n/** @override */\ngoog.async.Deferred.AlreadyCalledError.prototype.message =\n 'Deferred has already fired';\n\n\n/** @override */\ngoog.async.Deferred.AlreadyCalledError.prototype.name = 'AlreadyCalledError';\n\n\n\n/**\n * An error sub class that is used when a Deferred is canceled.\n *\n * @param {!goog.async.Deferred} deferred The Deferred object.\n * @constructor\n * @extends {goog.debug.Error}\n */\ngoog.async.Deferred.CanceledError = function(deferred) {\n goog.debug.Error.call(this);\n\n /**\n * The Deferred that raised this error.\n * @type {goog.async.Deferred}\n */\n this.deferred = deferred;\n};\ngoog.inherits(goog.async.Deferred.CanceledError, goog.debug.Error);\n\n\n/** @override */\ngoog.async.Deferred.CanceledError.prototype.message = 'Deferred was canceled';\n\n\n/** @override */\ngoog.async.Deferred.CanceledError.prototype.name = 'CanceledError';\n\n\n\n/**\n * Wrapper around errors that are scheduled to be thrown by failing deferreds\n * after a timeout.\n *\n * @param {*} error Error from a failing deferred.\n * @constructor\n * @final\n * @private\n * @struct\n */\ngoog.async.Deferred.Error_ = function(error) {\n /** @const @private {number} */\n this.id_ = goog.global.setTimeout(goog.bind(this.throwError, this), 0);\n\n /** @const @private {*} */\n this.error_ = error;\n};\n\n\n/**\n * Actually throws the error and removes it from the list of pending\n * deferred errors.\n */\ngoog.async.Deferred.Error_.prototype.throwError = function() {\n goog.asserts.assert(goog.async.Deferred.errorMap_[this.id_],\n 'Cannot throw an error that is not scheduled.');\n delete goog.async.Deferred.errorMap_[this.id_];\n throw this.error_;\n};\n\n\n/**\n * Resets the error throw timer.\n */\ngoog.async.Deferred.Error_.prototype.resetTimer = function() {\n goog.global.clearTimeout(this.id_);\n};\n\n\n/**\n * Map of unhandled errors scheduled to be rethrown in a future timestep.\n * @private {!Object<(number|string), goog.async.Deferred.Error_>}\n */\ngoog.async.Deferred.errorMap_ = {};\n\n\n/**\n * Schedules an error to be thrown after a delay.\n * @param {*} error Error from a failing deferred.\n * @return {number} Id of the error.\n * @private\n */\ngoog.async.Deferred.scheduleError_ = function(error) {\n var deferredError = new goog.async.Deferred.Error_(error);\n goog.async.Deferred.errorMap_[deferredError.id_] = deferredError;\n return deferredError.id_;\n};\n\n\n/**\n * Unschedules an error from being thrown.\n * @param {number} id Id of the deferred error to unschedule.\n * @private\n */\ngoog.async.Deferred.unscheduleError_ = function(id) {\n var error = goog.async.Deferred.errorMap_[id];\n if (error) {\n error.resetTimer();\n delete goog.async.Deferred.errorMap_[id];\n }\n};\n\n\n/**\n * Asserts that there are no pending deferred errors. If there are any\n * scheduled errors, one will be thrown immediately to make this function fail.\n */\ngoog.async.Deferred.assertNoErrors = function() {\n var map = goog.async.Deferred.errorMap_;\n for (var key in map) {\n var error = map[key];\n error.resetTimer();\n error.throwError();\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 A utility to load JavaScript files via DOM script tags.\n * Refactored from goog.net.Jsonp. Works cross-domain.\n */\n\ngoog.provide('goog.net.jsloader');\ngoog.provide('goog.net.jsloader.Error');\ngoog.provide('goog.net.jsloader.ErrorCode');\ngoog.provide('goog.net.jsloader.Options');\n\ngoog.require('goog.array');\ngoog.require('goog.async.Deferred');\ngoog.require('goog.debug.Error');\ngoog.require('goog.dom');\ngoog.require('goog.dom.TagName');\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.object');\n\n\n/**\n * The name of the property of goog.global under which the JavaScript\n * verification object is stored by the loaded script.\n * @private {string}\n */\ngoog.net.jsloader.GLOBAL_VERIFY_OBJS_ = 'closure_verification';\n\n\n/**\n * The default length of time, in milliseconds, we are prepared to wait for a\n * load request to complete.\n * @type {number}\n */\ngoog.net.jsloader.DEFAULT_TIMEOUT = 5000;\n\n\n/**\n * Optional parameters for goog.net.jsloader.send.\n * timeout: The length of time, in milliseconds, we are prepared to wait\n * for a load request to complete, or 0 or negative for no timeout. Default\n * is 5 seconds.\n * document: The HTML document under which to load the JavaScript. Default is\n * the current document.\n * cleanupWhenDone: If true clean up the script tag after script completes to\n * load. This is important if you just want to read data from the JavaScript\n * and then throw it away. Default is false.\n * attributes: Additional attributes to set on the script tag.\n *\n * @typedef {{\n * timeout: (number|undefined),\n * document: (HTMLDocument|undefined),\n * cleanupWhenDone: (boolean|undefined),\n * attributes: (!Object<string, string>|undefined)\n * }}\n */\ngoog.net.jsloader.Options;\n\n\n/**\n * Scripts (URIs) waiting to be loaded.\n * @private {!Array<!goog.html.TrustedResourceUrl>}\n */\ngoog.net.jsloader.scriptsToLoad_ = [];\n\n\n/**\n * The deferred result of loading the URIs in scriptsToLoad_.\n * We need to return this to a caller that wants to load URIs while\n * a deferred is already working on them.\n * @private {!goog.async.Deferred<null>}\n */\ngoog.net.jsloader.scriptLoadingDeferred_;\n\n\n\n/**\n * Loads and evaluates the JavaScript files at the specified URIs, guaranteeing\n * the order of script loads.\n *\n * Because we have to load the scripts in serial (load script 1, exec script 1,\n * load script 2, exec script 2, and so on), this will be slower than doing\n * the network fetches in parallel.\n *\n * If you need to load a large number of scripts but dependency order doesn't\n * matter, you should just call goog.net.jsloader.safeLoad N times.\n *\n * If you need to load a large number of scripts on the same domain,\n * you may want to use goog.module.ModuleLoader.\n *\n * @param {Array<!goog.html.TrustedResourceUrl>} trustedUris The URIs to load.\n * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See\n * goog.net.jsloader.options documentation for details.\n * @return {!goog.async.Deferred} The deferred result, that may be used to add\n * callbacks\n */\ngoog.net.jsloader.safeLoadMany = function(trustedUris, opt_options) {\n // Loading the scripts in serial introduces asynchronosity into the flow.\n // Therefore, there are race conditions where client A can kick off the load\n // sequence for client B, even though client A's scripts haven't all been\n // loaded yet.\n //\n // To work around this issue, all module loads share a queue.\n if (!trustedUris.length) {\n return goog.async.Deferred.succeed(null);\n }\n\n var isAnotherModuleLoading = goog.net.jsloader.scriptsToLoad_.length;\n goog.array.extend(goog.net.jsloader.scriptsToLoad_, trustedUris);\n if (isAnotherModuleLoading) {\n // jsloader is still loading some other scripts.\n // In order to prevent the race condition noted above, we just add\n // these URIs to the end of the scripts' queue and return the deferred\n // result of the ongoing script load, so the caller knows when they\n // finish loading.\n return goog.net.jsloader.scriptLoadingDeferred_;\n }\n\n trustedUris = goog.net.jsloader.scriptsToLoad_;\n var popAndLoadNextScript = function() {\n var trustedUri = trustedUris.shift();\n var deferred = goog.net.jsloader.safeLoad(trustedUri, opt_options);\n if (trustedUris.length) {\n deferred.addBoth(popAndLoadNextScript);\n }\n return deferred;\n };\n goog.net.jsloader.scriptLoadingDeferred_ = popAndLoadNextScript();\n return goog.net.jsloader.scriptLoadingDeferred_;\n};\n\n\n/**\n * Loads and evaluates a JavaScript file.\n * When the script loads, a user callback is called.\n * It is the client's responsibility to verify that the script ran successfully.\n *\n * @param {!goog.html.TrustedResourceUrl} trustedUri The URI of the JavaScript.\n * @param {goog.net.jsloader.Options=} opt_options Optional parameters. See\n * goog.net.jsloader.Options documentation for details.\n * @return {!goog.async.Deferred} The deferred result, that may be used to add\n * callbacks and/or cancel the transmission.\n * The error callback will be called with a single goog.net.jsloader.Error\n * parameter.\n */\ngoog.net.jsloader.safeLoad = function(trustedUri, opt_options) {\n var options = opt_options || {};\n var doc = options.document || document;\n var uri = goog.html.TrustedResourceUrl.unwrap(trustedUri);\n\n var script = goog.dom.createElement(goog.dom.TagName.SCRIPT);\n var request = {script_: script, timeout_: undefined};\n var deferred = new goog.async.Deferred(goog.net.jsloader.cancel_, request);\n\n // Set a timeout.\n var timeout = null;\n var timeoutDuration = (options.timeout != null) ?\n options.timeout :\n goog.net.jsloader.DEFAULT_TIMEOUT;\n if (timeoutDuration > 0) {\n timeout = window.setTimeout(function() {\n goog.net.jsloader.cleanup_(script, true);\n deferred.errback(\n new goog.net.jsloader.Error(\n goog.net.jsloader.ErrorCode.TIMEOUT,\n 'Timeout reached for loading script ' + uri));\n }, timeoutDuration);\n request.timeout_ = timeout;\n }\n\n // Hang the user callback to be called when the script completes to load.\n // NOTE(user): This callback will be called in IE even upon error. In any\n // case it is the client's responsibility to verify that the script ran\n // successfully.\n script.onload = script.onreadystatechange = function() {\n if (!script.readyState || script.readyState == 'loaded' ||\n script.readyState == 'complete') {\n var removeScriptNode = options.cleanupWhenDone || false;\n goog.net.jsloader.cleanup_(script, removeScriptNode, timeout);\n deferred.callback(null);\n }\n };\n\n // Add an error callback.\n // NOTE(user): Not supported in IE.\n script.onerror = function() {\n goog.net.jsloader.cleanup_(script, true, timeout);\n deferred.errback(\n new goog.net.jsloader.Error(\n goog.net.jsloader.ErrorCode.LOAD_ERROR,\n 'Error while loading script ' + uri));\n };\n\n var properties = options.attributes || {};\n goog.object.extend(\n properties, {'type': 'text/javascript', 'charset': 'UTF-8'});\n goog.dom.setProperties(script, properties);\n // NOTE(user): Safari never loads the script if we don't set the src\n // attribute before appending.\n goog.dom.safe.setScriptSrc(script, trustedUri);\n var scriptParent = goog.net.jsloader.getScriptParentElement_(doc);\n scriptParent.appendChild(script);\n\n return deferred;\n};\n\n\n/**\n * Loads a JavaScript file and verifies it was evaluated successfully, using a\n * verification object.\n * The verification object is set by the loaded JavaScript at the end of the\n * script.\n * We verify this object was set and return its value in the success callback.\n * If the object is not defined we trigger an error callback.\n *\n * @param {!goog.html.TrustedResourceUrl} trustedUri The URI of the JavaScript.\n * @param {string} verificationObjName The name of the verification object that\n * the loaded script should set.\n * @param {goog.net.jsloader.Options} options Optional parameters. See\n * goog.net.jsloader.Options documentation for details.\n * @return {!goog.async.Deferred} The deferred result, that may be used to add\n * callbacks and/or cancel the transmission.\n * The success callback will be called with a single parameter containing\n * the value of the verification object.\n * The error callback will be called with a single goog.net.jsloader.Error\n * parameter.\n */\ngoog.net.jsloader.safeLoadAndVerify = function(\n trustedUri, verificationObjName, options) {\n // Define the global objects variable.\n if (!goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_]) {\n goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_] = {};\n }\n var verifyObjs = goog.global[goog.net.jsloader.GLOBAL_VERIFY_OBJS_];\n var uri = goog.html.TrustedResourceUrl.unwrap(trustedUri);\n\n // Verify that the expected object does not exist yet.\n if (verifyObjs[verificationObjName] !== undefined) {\n // TODO(user): Error or reset variable?\n return goog.async.Deferred.fail(\n new goog.net.jsloader.Error(\n goog.net.jsloader.ErrorCode.VERIFY_OBJECT_ALREADY_EXISTS,\n 'Verification object ' + verificationObjName +\n ' already defined.'));\n }\n\n // Send request to load the JavaScript.\n var sendDeferred = goog.net.jsloader.safeLoad(trustedUri, options);\n\n // Create a deferred object wrapping the send result.\n var deferred =\n new goog.async.Deferred(goog.bind(sendDeferred.cancel, sendDeferred));\n\n // Call user back with object that was set by the script.\n sendDeferred.addCallback(function() {\n var result = verifyObjs[verificationObjName];\n if (result !== undefined) {\n deferred.callback(result);\n delete verifyObjs[verificationObjName];\n } else {\n // Error: script was not loaded properly.\n deferred.errback(\n new goog.net.jsloader.Error(\n goog.net.jsloader.ErrorCode.VERIFY_ERROR, 'Script ' + uri +\n ' loaded, but verification object ' + verificationObjName +\n ' was not defined.'));\n }\n });\n\n // Pass error to new deferred object.\n sendDeferred.addErrback(function(error) {\n if (verifyObjs[verificationObjName] !== undefined) {\n delete verifyObjs[verificationObjName];\n }\n deferred.errback(error);\n });\n\n return deferred;\n};\n\n\n/**\n * Gets the DOM element under which we should add new script elements.\n * How? Take the first head element, and if not found take doc.documentElement,\n * which always exists.\n *\n * @param {!HTMLDocument} doc The relevant document.\n * @return {!Element} The script parent element.\n * @private\n */\ngoog.net.jsloader.getScriptParentElement_ = function(doc) {\n var headElements = goog.dom.getElementsByTagName(goog.dom.TagName.HEAD, doc);\n if (!headElements || goog.array.isEmpty(headElements)) {\n return doc.documentElement;\n } else {\n return headElements[0];\n }\n};\n\n\n/**\n * Cancels a given request.\n * @this {{script_: Element, timeout_: number}} The request context.\n * @private\n */\ngoog.net.jsloader.cancel_ = function() {\n var request = this;\n if (request && request.script_) {\n var scriptNode = request.script_;\n if (scriptNode && scriptNode.tagName == goog.dom.TagName.SCRIPT) {\n goog.net.jsloader.cleanup_(scriptNode, true, request.timeout_);\n }\n }\n};\n\n\n/**\n * Removes the script node and the timeout.\n * @param {Node} scriptNode The node to be cleaned up.\n * @param {boolean} removeScriptNode If true completely remove the script node.\n * @param {?number=} opt_timeout The timeout handler to cleanup.\n * @private\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\ngoog.net.jsloader.cleanup_ = function(\n scriptNode, removeScriptNode, opt_timeout) {\n if (opt_timeout != null) {\n goog.global.clearTimeout(opt_timeout);\n }\n\n scriptNode.onload = goog.nullFunction;\n scriptNode.onerror = goog.nullFunction;\n scriptNode.onreadystatechange = goog.nullFunction;\n\n // Do this after a delay (removing the script node of a running script can\n // confuse older IEs).\n if (removeScriptNode) {\n window.setTimeout(function() { goog.dom.removeNode(scriptNode); }, 0);\n }\n};\n\n\n/**\n * Possible error codes for jsloader.\n * @enum {number}\n */\ngoog.net.jsloader.ErrorCode = {\n LOAD_ERROR: 0,\n TIMEOUT: 1,\n VERIFY_ERROR: 2,\n VERIFY_OBJECT_ALREADY_EXISTS: 3,\n};\n\n\n\n/**\n * A jsloader error.\n *\n * @param {goog.net.jsloader.ErrorCode} code The error code.\n * @param {string=} opt_message Additional message.\n * @constructor\n * @extends {goog.debug.Error}\n * @final\n */\ngoog.net.jsloader.Error = function(code, opt_message) {\n var msg = 'Jsloader error (code #' + code + ')';\n if (opt_message) {\n msg += ': ' + opt_message;\n }\n goog.net.jsloader.Error.base(this, 'constructor', msg);\n\n /**\n * The code for this error.\n *\n * @type {goog.net.jsloader.ErrorCode}\n */\n this.code = code;\n};\ngoog.inherits(goog.net.jsloader.Error, goog.debug.Error);\n","// Copyright 2007 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 Error codes shared between goog.net.IframeIo and\n * goog.net.XhrIo.\n */\n\ngoog.provide('goog.net.ErrorCode');\n\n\n/**\n * Error codes\n * @enum {number}\n */\ngoog.net.ErrorCode = {\n\n /**\n * There is no error condition.\n */\n NO_ERROR: 0,\n\n /**\n * The most common error from iframeio, unfortunately, is that the browser\n * responded with an error page that is classed as a different domain. The\n * situations, are when a browser error page is shown -- 404, access denied,\n * DNS failure, connection reset etc.)\n *\n */\n ACCESS_DENIED: 1,\n\n /**\n * Currently the only case where file not found will be caused is when the\n * code is running on the local file system and a non-IE browser makes a\n * request to a file that doesn't exist.\n */\n FILE_NOT_FOUND: 2,\n\n /**\n * If Firefox shows a browser error page, such as a connection reset by\n * server or access denied, then it will fail silently without the error or\n * load handlers firing.\n */\n FF_SILENT_ERROR: 3,\n\n /**\n * Custom error provided by the client through the error check hook.\n */\n CUSTOM_ERROR: 4,\n\n /**\n * Exception was thrown while processing the request.\n */\n EXCEPTION: 5,\n\n /**\n * The Http response returned a non-successful http status code.\n */\n HTTP_ERROR: 6,\n\n /**\n * The request was aborted.\n */\n ABORT: 7,\n\n /**\n * The request timed out.\n */\n TIMEOUT: 8,\n\n /**\n * The resource is not available offline.\n */\n OFFLINE: 9,\n};\n\n\n/**\n * Returns a friendly error message for an error code. These messages are for\n * debugging and are not localized.\n * @param {goog.net.ErrorCode} errorCode An error code.\n * @return {string} A message for debugging.\n */\ngoog.net.ErrorCode.getDebugMessage = function(errorCode) {\n switch (errorCode) {\n case goog.net.ErrorCode.NO_ERROR:\n return 'No Error';\n\n case goog.net.ErrorCode.ACCESS_DENIED:\n return 'Access denied to content document';\n\n case goog.net.ErrorCode.FILE_NOT_FOUND:\n return 'File not found';\n\n case goog.net.ErrorCode.FF_SILENT_ERROR:\n return 'Firefox silently errored';\n\n case goog.net.ErrorCode.CUSTOM_ERROR:\n return 'Application custom error';\n\n case goog.net.ErrorCode.EXCEPTION:\n return 'An exception occurred';\n\n case goog.net.ErrorCode.HTTP_ERROR:\n return 'Http response at 400 or 500 level';\n\n case goog.net.ErrorCode.ABORT:\n return 'Request was aborted';\n\n case goog.net.ErrorCode.TIMEOUT:\n return 'Request timed out';\n\n case goog.net.ErrorCode.OFFLINE:\n return 'The resource is not available offline';\n\n default:\n return 'Unrecognized error code';\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.iframeclient.IframeWrapper used to communicate\n * with the hidden iframe to detect Auth events.\n */\n\ngoog.provide('fireauth.iframeclient.IframeWrapper');\n\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.net.jsloader');\ngoog.require('goog.string.Const');\n\n\n/**\n * Defines the hidden iframe wrapper for cross origin communications.\n * @param {string} url The hidden iframe src URL.\n * @constructor\n */\nfireauth.iframeclient.IframeWrapper = function(url) {\n /** @private {string} The hidden iframe URL. */\n this.url_ = url;\n\n /**\n * @type {?gapi.iframes.Iframe}\n * @private\n */\n this.iframe_ = null;\n\n /** @private {!goog.Promise} A promise that resolves on iframe open. */\n this.onIframeOpen_ = this.open_();\n};\n\n\n/**\n * @typedef {{\n * type: string\n * }}\n */\nfireauth.iframeclient.IframeWrapper.Message;\n\n/**\n * Returns URL, src of the hidden iframe.\n * @return {string}\n * @private\n */\nfireauth.iframeclient.IframeWrapper.prototype.getPath_ = function() {\n return this.url_;\n};\n\n\n/**\n * @return {!goog.Promise} The promise that resolves when the iframe is ready.\n */\nfireauth.iframeclient.IframeWrapper.prototype.onReady = function() {\n return this.onIframeOpen_;\n};\n\n\n/**\n * Returns options used to open the iframe.\n * @return {!gapi.iframes.OptionsBag}\n * @private\n */\nfireauth.iframeclient.IframeWrapper.prototype.getOptions_ = function() {\n var options = /** @type {!gapi.iframes.OptionsBag} */ ({\n 'where': document.body,\n 'url': this.getPath_(),\n 'messageHandlersFilter': /** @type {!gapi.iframes.IframesFilter} */ (\n fireauth.util.getObjectRef(\n 'gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER')),\n 'attributes': {\n 'style': {\n 'position': 'absolute',\n 'top': '-100px',\n 'width': '1px',\n 'height': '1px'\n }\n },\n 'dontclear': true\n });\n return options;\n};\n\n\n/**\n * Opens an iframe.\n * @return {!goog.Promise} A promise that resolves on successful iframe open.\n * @private\n */\nfireauth.iframeclient.IframeWrapper.prototype.open_ = function() {\n var self = this;\n return fireauth.iframeclient.IframeWrapper.loadGApiJs_().then(function() {\n return new goog.Promise(function(resolve, reject) {\n /**\n * @param {?gapi.iframes.Iframe} iframe The new opened iframe.\n */\n var onOpen = function(iframe) {\n self.iframe_ = iframe;\n self.iframe_.restyle({\n // Prevent iframe from closing on mouse out.\n 'setHideOnLeave': false\n });\n // Confirm iframe is correctly loaded.\n // To fallback on failure, set a timeout.\n var networkErrorTimer = setTimeout(function() {\n reject(new Error('Network Error'));\n }, fireauth.iframeclient.IframeWrapper.PING_TIMEOUT_.get());\n // Clear timer and resolve pending iframe ready promise.\n var clearTimerAndResolve = function() {\n clearTimeout(networkErrorTimer);\n resolve();\n };\n // This returns an IThenable. However the reject part does not call\n // when the iframe is not loaded.\n iframe.ping(clearTimerAndResolve).then(\n clearTimerAndResolve,\n function(error) { reject(new Error('Network Error')); });\n };\n /** @type {function():!gapi.iframes.Context} */ (\n fireauth.util.getObjectRef('gapi.iframes.getContext'))().open(\n self.getOptions_(), onOpen);\n });\n });\n};\n\n\n/**\n * @param {!fireauth.iframeclient.IframeWrapper.Message} message to send.\n * @return {!goog.Promise<?Object>} The promise that resolve when message is\n * sent.\n */\nfireauth.iframeclient.IframeWrapper.prototype.sendMessage = function(message) {\n var self = this;\n return this.onIframeOpen_.then(function() {\n return new goog.Promise(function(resolve, reject) {\n self.iframe_.send(\n message['type'],\n message,\n resolve,\n /** @type {!gapi.iframes.IframesFilter} */ (\n fireauth.util.getObjectRef(\n 'gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER')));\n\n });\n });\n};\n\n\n/**\n * Registers a listener to a post message.\n * @param {string} eventName The message to register for.\n * @param {gapi.iframes.MessageHandler} handler Message handler.\n */\nfireauth.iframeclient.IframeWrapper.prototype.registerEvent =\n function(eventName, handler) {\n var self = this;\n this.onIframeOpen_.then(function() {\n self.iframe_.register(\n eventName,\n /** @type {function(this:gapi.iframes.Iframe,\n * *, gapi.iframes.Iframe): *}\n */ (handler),\n /** @type {!gapi.iframes.IframesFilter} */ (\n fireauth.util.getObjectRef(\n 'gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER')));\n });\n};\n\n\n/**\n * Unregisters a listener to a post message.\n * @param {string} eventName The message to unregister.\n * @param {gapi.iframes.MessageHandler} handler Message handler.\n */\nfireauth.iframeclient.IframeWrapper.prototype.unregisterEvent =\n function(eventName, handler) {\n var self = this;\n this.onIframeOpen_.then(function() {\n self.iframe_.unregister(\n eventName,\n /** @type {(function(this:gapi.iframes.Iframe,\n * *, gapi.iframes.Iframe): *|undefined)}\n */ (handler));\n });\n};\n\n\n/** @private @const {!goog.string.Const} The GApi loader URL. */\nfireauth.iframeclient.IframeWrapper.GAPI_LOADER_SRC_ = goog.string.Const.from(\n 'https://apis.google.com/js/api.js?onload=%{onload}');\n\n\n/**\n * @private @const {!fireauth.util.Delay} The gapi.load network error timeout\n * delay with units in ms.\n */\nfireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_ =\n new fireauth.util.Delay(30000, 60000);\n\n\n/**\n * @private @const {!fireauth.util.Delay} The iframe ping error timeout delay\n * with units in ms.\n */\nfireauth.iframeclient.IframeWrapper.PING_TIMEOUT_ =\n new fireauth.util.Delay(5000, 15000);\n\n\n/** @private {?goog.Promise} The cached GApi loader promise. */\nfireauth.iframeclient.IframeWrapper.cachedGApiLoader_ = null;\n\n\n/** Resets the cached GApi loader. */\nfireauth.iframeclient.IframeWrapper.resetCachedGApiLoader = function() {\n fireauth.iframeclient.IframeWrapper.cachedGApiLoader_ = null;\n};\n\n\n\n/**\n * Loads the GApi client library if it is not loaded for gapi.iframes usage.\n * @return {!goog.Promise} A promise that resolves when gapi.iframes is loaded.\n * @private\n */\nfireauth.iframeclient.IframeWrapper.loadGApiJs_ = function() {\n // If already pending or resolved, return the cached promise.\n if (fireauth.iframeclient.IframeWrapper.cachedGApiLoader_) {\n return fireauth.iframeclient.IframeWrapper.cachedGApiLoader_;\n }\n // If there is no cached promise, initialize a new one.\n fireauth.iframeclient.IframeWrapper.cachedGApiLoader_ =\n new goog.Promise(function(resolve, reject) {\n // Function to run when gapi.load is ready.\n var onGapiLoad = function() {\n // The developer may have tried to previously run gapi.load and failed.\n // Run this to fix that.\n fireauth.util.resetUnloadedGapiModules();\n var loader = /** @type {function(string, !Object)} */ (\n fireauth.util.getObjectRef('gapi.load'));\n loader('gapi.iframes', {\n 'callback': resolve,\n 'ontimeout': function() {\n // The above reset may be sufficient, but having this reset after\n // failure ensures that if the developer calls gapi.load after the\n // connection is re-established and before another attempt to embed\n // the iframe, it would work and would not be broken because of our\n // failed attempt.\n // Timeout when gapi.iframes.Iframe not loaded.\n fireauth.util.resetUnloadedGapiModules();\n reject(new Error('Network Error'));\n },\n 'timeout': fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_.get()\n });\n };\n if (fireauth.util.getObjectRef('gapi.iframes.Iframe')) {\n // If gapi.iframes.Iframe available, resolve.\n resolve();\n } else if (fireauth.util.getObjectRef('gapi.load')) {\n // Gapi loader ready, load gapi.iframes.\n onGapiLoad();\n } else {\n // Create a new iframe callback when this is called so as not to overwrite\n // any previous defined callback. This happens if this method is called\n // multiple times in parallel and could result in the later callback\n // overwriting the previous one. This would end up with a iframe\n // timeout.\n var cbName = '__iframefcb' +\n Math.floor(Math.random() * 1000000).toString();\n // GApi loader not available, dynamically load platform.js.\n goog.global[cbName] = function() {\n // GApi loader should be ready.\n if (fireauth.util.getObjectRef('gapi.load')) {\n onGapiLoad();\n } else {\n // Gapi loader failed, throw error.\n reject(new Error('Network Error'));\n }\n };\n // Build GApi loader.\n var url = goog.html.TrustedResourceUrl.format(\n fireauth.iframeclient.IframeWrapper.GAPI_LOADER_SRC_,\n {'onload': cbName});\n // Load GApi loader.\n var result = goog.Promise.resolve(goog.net.jsloader.safeLoad(url));\n result.thenCatch(function(error) {\n // In case library fails to load, typically due to a network error,\n // reset cached loader to null to force a refresh on a retrial.\n reject(new Error('Network Error'));\n });\n }\n }).thenCatch(function(error) {\n // Reset cached promise to allow for retrial.\n fireauth.iframeclient.IframeWrapper.cachedGApiLoader_ = null;\n throw error;\n });\n return fireauth.iframeclient.IframeWrapper.cachedGApiLoader_;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.AsyncStorage');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.storage.Storage');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\n\n\n/**\n * AsyncStorage provides an interface to the React Native AsyncStorage API.\n * @param {!Object=} opt_asyncStorage The AsyncStorage API. If not provided\n * this method will attempt to fetch an implementation from\n * firebase.INTERNAL.reactNative.\n * @constructor\n * @implements {fireauth.storage.Storage}\n * @see https://facebook.github.io/react-native/docs/asyncstorage.html\n */\nfireauth.storage.AsyncStorage = function(opt_asyncStorage) {\n /**\n * The underlying storage instance for persistent data.\n * @private\n */\n this.storage_ =\n opt_asyncStorage || (firebase.INTERNAL['reactNative'] &&\n firebase.INTERNAL['reactNative']['AsyncStorage']);\n\n if (!this.storage_) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'The React Native compatibility library was not found.');\n }\n /** @public {string} The storage type identifier. */\n this.type = fireauth.storage.Storage.Type.ASYNC_STORAGE;\n};\n\n\n/**\n * Retrieves the value stored at the key.\n * @param {string} key\n * @return {!goog.Promise<*>}\n * @override\n */\nfireauth.storage.AsyncStorage.prototype.get = function(key) {\n return goog.Promise.resolve(this.storage_['getItem'](key))\n .then(function(val) {\n return val && fireauth.util.parseJSON(val);\n });\n};\n\n\n/**\n * Stores the value at the specified key.\n * @param {string} key\n * @param {*} value\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.AsyncStorage.prototype.set = function(key, value) {\n return goog.Promise.resolve(\n this.storage_['setItem'](key, fireauth.util.stringifyJSON(value)));\n};\n\n\n/**\n * Removes the value at the specified key.\n * @param {string} key\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.AsyncStorage.prototype.remove = function(key) {\n return goog.Promise.resolve(this.storage_['removeItem'](key));\n};\n\n\n/**\n * Does nothing. AsyncStorage does not support storage events,\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.AsyncStorage.prototype.addStorageListener = function(\n listener) {};\n\n\n/**\n * Does nothing. AsyncStorage does not support storage events,\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.AsyncStorage.prototype.removeStorageListener = function(\n listener) {};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.Storage');\n\n\n\n/**\n * Defines a generic interface to storage APIs across platforms.\n * @interface\n */\nfireauth.storage.Storage = function() {};\n\n\n/**\n * Retrieves the value stored at the key.\n * @param {string} key\n * @return {!goog.Promise<*>}\n */\nfireauth.storage.Storage.prototype.get = function(key) {};\n\n\n/**\n * Stores the value at the specified key.\n * @param {string} key\n * @param {*} value\n * @return {!goog.Promise<void>}\n */\nfireauth.storage.Storage.prototype.set = function(key, value) {};\n\n\n/**\n * Removes the value at the specified key.\n * @param {string} key\n * @return {!goog.Promise<void>}\n */\nfireauth.storage.Storage.prototype.remove = function(key) {};\n\n\n/**\n * Adds a listener to storage event change.\n * @param {function(!goog.events.BrowserEvent)|function(!Array<string>)}\n * listener The storage event listener.\n */\nfireauth.storage.Storage.prototype.addStorageListener = function(listener) {};\n\n\n/**\n * Removes a listener to storage event change.\n * @param {function(!goog.events.BrowserEvent)|function(!Array<string>)}\n * listener The storage event listener.\n */\nfireauth.storage.Storage.prototype.removeStorageListener = function(listener) {\n};\n\n\n/** @type {string} The storage type identifier. */\nfireauth.storage.Storage.prototype.type;\n\n\n/**\n * Enum for the identifier of the type of underlying storage.\n * @enum {string}\n */\nfireauth.storage.Storage.Type = {\n ASYNC_STORAGE: 'asyncStorage',\n IN_MEMORY: 'inMemory',\n INDEXEDDB: 'indexedDB',\n LOCAL_STORAGE: 'localStorage',\n MOCK_STORAGE: 'mockStorage',\n NULL_STORAGE: 'nullStorage',\n SESSION_STORAGE: 'sessionStorage'\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 MessageChannel based wrapper for receiving\n * messages from other windows or workers.\n */\n\ngoog.provide('fireauth.messagechannel.Receiver');\n\ngoog.require('fireauth.messagechannel.Status');\ngoog.require('goog.Promise');\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n/**\n * Initializes a channel to receive specific messages from a specified event\n * target.\n * Note receivers should not be manually instantiated. Instead `getInstance()`\n * should be used instead to get a receiver instance for a specified event\n * target.\n * @param {!EventTarget} eventTarget The event target to listen to.\n * @constructor\n */\nfireauth.messagechannel.Receiver = function(eventTarget) {\n /**\n * @const @private {!EventTarget} The messageChannel event target.\n */\n this.eventTarget_ = eventTarget;\n /**\n * @const @private {!Object.<string,\n * !Array<function(string, *):!goog.Promise<?>|void>>}\n * This is the event type to handlers hash map. It is used to hold the\n * corresponding handlers for specified events.\n */\n this.eventHandlers_ = {};\n /**\n * @const @private {function(!Event)} The internal 'message' event handler\n * used to reroute the request to corresponding subscribed handlers.\n */\n this.messageEventHandler_ = goog.bind(this.handleEvent_, this);\n};\n\n\n/**\n * @param {!EventTarget} eventTarget The event target to check for.\n * @return {boolean} Whether the receiver is listening to the specified event\n * target.\n */\nfireauth.messagechannel.Receiver.prototype.isListeningTo =\n function(eventTarget) {\n return this.eventTarget_ == eventTarget;\n};\n\n\n/**\n * @const @private {!Array<!fireauth.messagechannel.Receiver>} The list of all\n * created `fireauth.messagechannel.Receiver` instances.\n */\nfireauth.messagechannel.Receiver.receivers_ = [];\n\n\n/**\n * Return a receiver instance for the specified event target. This is needed\n * since one instance can be available per event target. Otherwise receivers\n * could clobber each other.\n * @param {!EventTarget} eventTarget The event target to listen to.\n * @return {!fireauth.messagechannel.Receiver} The receiver instance for the\n * specified event target.\n */\nfireauth.messagechannel.Receiver.getInstance = function(eventTarget) {\n // The results are stored in an array since objects can't be keys for other\n // objects. In addition, setting a unique property on an event target as a\n // hash map key may not be allowed due to CORS restrictions.\n var instance;\n goog.array.forEach(\n fireauth.messagechannel.Receiver.receivers_,\n function(receiver) {\n if (receiver.isListeningTo(eventTarget)) {\n instance = receiver;\n }\n });\n if (!instance) {\n instance = new fireauth.messagechannel.Receiver(eventTarget);\n fireauth.messagechannel.Receiver.receivers_.push(instance);\n }\n return instance;\n};\n\n\n/**\n * Handles a PostMessage event based on the following protocol:\n * <ul>\n * <li>When an event is first detected, check there is a subscribed handler.\n * If not, do nothing as there could be other listeners.</li>\n * <li>If there is a subscribed event, reply with an ACK event to notify the\n * sender that the event can be handled.</li>\n * <li>Trigger the subscribed handlers.</li>\n * <li>Reply again with the combined results of all subscribed handlers and\n * return the response back.</li>\n * </ul>\n *\n * @param {!Event} event The PostMessage event to handle.\n * @private\n */\nfireauth.messagechannel.Receiver.prototype.handleEvent_ = function(event) {\n // Respond to sender first with ack reply. This will let the client\n // know that the service worker can handle this event.\n var eventType = event.data['eventType'];\n var eventId = event.data['eventId'];\n var handlers = this.eventHandlers_[eventType];\n if (handlers && handlers.length > 0) {\n // Event can be handled.\n event.ports[0].postMessage({\n 'status': fireauth.messagechannel.Status.ACK,\n 'eventId': eventId,\n 'eventType': eventType,\n 'response': null\n });\n var promises = [];\n goog.array.forEach(handlers, function(handler) {\n // Wrap in promise in case the handler doesn't return a promise.\n promises.push(goog.Promise.resolve().then(function() {\n return handler(event.origin, event.data['data']);\n }));\n });\n // allSettled is more flexible as it executes all the promises passed and\n // returns whether they succeeded or failed.\n goog.Promise.allSettled(promises)\n .then(function(result) {\n // allResponse has the format:\n // !Array<!{fulfilled: boolean, value: (*|undefined),\n // reason: (*|undefined)}>\n // Respond to sender with ack reply.\n // De-obfuscate the allSettled result.\n var allResponses = [];\n goog.array.forEach(result, function(item) {\n allResponses.push({\n 'fulfilled': item.fulfilled,\n 'value': item.value,\n // Error cannot be clone in postMessage.\n 'reason': item.reason ? item.reason.message : undefined\n });\n });\n // Remove undefined fields.\n goog.array.forEach(allResponses, function(item) {\n for (var key in item) {\n if (typeof item[key] === 'undefined') {\n delete item[key];\n }\n }\n });\n event.ports[0].postMessage({\n 'status': fireauth.messagechannel.Status.DONE,\n 'eventId': eventId,\n 'eventType': eventType,\n 'response': allResponses\n });\n });\n }\n // Let unsupported events time out, as there could be external receivers\n // that can handle them.\n};\n\n\n/**\n * Subscribes to events of the specified type.\n * @param {string} eventType The event type to listen to.\n * @param {function(string, *):!goog.Promise<?>|void} handler The async callback\n * function to run when the event is triggered.\n */\nfireauth.messagechannel.Receiver.prototype.subscribe =\n function(eventType, handler) {\n if (goog.object.isEmpty(this.eventHandlers_)) {\n this.eventTarget_.addEventListener('message', this.messageEventHandler_);\n }\n if (typeof this.eventHandlers_[eventType] === 'undefined') {\n this.eventHandlers_[eventType] = [];\n }\n this.eventHandlers_[eventType].push(handler);\n};\n\n\n/**\n * Unsubscribes the specified handler from the specified event. If no handler\n * is specified, all handlers are unsubscribed.\n * @param {string} eventType The event type to unsubscribe from.\n * @param {?function(string, *):!goog.Promise<?>|void=} opt_handler The\n * callback function to unsubscribe from the specified event type. If none\n * is specified, all handlers are unsubscribed.\n */\nfireauth.messagechannel.Receiver.prototype.unsubscribe =\n function(eventType, opt_handler) {\n if (typeof this.eventHandlers_[eventType] !== 'undefined' && opt_handler) {\n goog.array.removeAllIf(this.eventHandlers_[eventType], function(ele) {\n return ele == opt_handler;\n });\n if (this.eventHandlers_[eventType].length == 0) {\n delete this.eventHandlers_[eventType];\n }\n } else if (!opt_handler) {\n // Unsubscribe all handlers for speficied event.\n delete this.eventHandlers_[eventType];\n }\n if (goog.object.isEmpty(this.eventHandlers_)) {\n this.eventTarget_.removeEventListener('message', this.messageEventHandler_);\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 a local storage interface with an indexedDB\n * implementation to be used as a fallback with browsers that do not synchronize\n * local storage changes between different windows of the same origin.\n */\n\ngoog.provide('fireauth.storage.IndexedDB');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.messagechannel.Receiver');\ngoog.require('fireauth.messagechannel.Sender');\ngoog.require('fireauth.messagechannel.WorkerClientPostMessager');\ngoog.require('fireauth.storage.Storage');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.Timer');\ngoog.require('goog.array');\n\n\n\n/**\n * Initialize an indexedDB local storage manager used to mimic local storage\n * using an indexedDB underlying implementation including the ability to listen\n * to storage changes by key similar to localstorage storage event.\n * @param {string} dbName The indexedDB database name where all local storage\n * data is to be stored.\n * @param {string} objectStoreName The indexedDB object store name where all\n * local storage data is to be stored.\n * @param {string} dataKeyPath The indexedDB object store index name used to key\n * all local storage data.\n * @param {string} valueKeyPath The indexedDB object store value field for each\n * entry.\n * @param {number} version The indexedDB database version number.\n * @param {?IDBFactory=} opt_indexedDB The optional IndexedDB factory object.\n * @implements {fireauth.storage.Storage}\n * @constructor\n */\nfireauth.storage.IndexedDB = function(\n dbName,\n objectStoreName,\n dataKeyPath,\n valueKeyPath,\n version,\n opt_indexedDB) {\n // indexedDB not available, fail hard.\n if (!fireauth.storage.IndexedDB.isAvailable()) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.WEB_STORAGE_UNSUPPORTED);\n }\n /**\n * @const @private {string} The indexedDB database name where all local\n * storage data is to be stored.\n */\n this.dbName_ = dbName;\n /**\n * @const @private {string} The indexedDB object store name where all local\n * storage data is to be stored.\n */\n this.objectStoreName_ = objectStoreName;\n /**\n * @const @private {string} The indexedDB object store index name used to key\n * all local storage data.\n */\n this.dataKeyPath_ = dataKeyPath;\n /**\n * @const @private {string} The indexedDB object store value field for each\n * entry.\n */\n this.valueKeyPath_ = valueKeyPath;\n /** @const @private {number} The indexedDB database version number. */\n this.version_ = version;\n /** @private {!Object.<string, *>} The local indexedDB map copy. */\n this.localMap_ = {};\n /**\n * @private {!Array<function(!Array<string>)>} Listeners to storage events.\n */\n this.storageListeners_ = [];\n /** @private {number} The indexedDB pending write operations tracker. */\n this.pendingOpsTracker_ = 0;\n /** @private {!IDBFactory} The indexedDB factory object. */\n this.indexedDB_ = /** @type {!IDBFactory} */ (\n opt_indexedDB || goog.global.indexedDB);\n /** @public {string} The storage type identifier. */\n this.type = fireauth.storage.Storage.Type.INDEXEDDB;\n /**\n * @private {?goog.Promise<void>} The pending polling promise for syncing\n * unprocessed indexedDB external changes.\n */\n this.poll_ = null;\n /**\n * @private {?number} The poll timer ID for syncing external indexedDB\n * changes.\n */\n this.pollTimerId_ = null;\n /**\n * @private {?fireauth.messagechannel.Receiver} The messageChannel receiver if\n * running from a serviceworker.\n */\n this.receiver_ = null;\n /**\n * @private {?fireauth.messagechannel.Sender} The messageChannel sender to\n * send keyChanged messages to the service worker from the client.\n */\n this.sender_ = null;\n /**\n * @private {boolean} Whether the service worker has a receiver for the\n * keyChanged events.\n */\n this.serviceWorkerReceiverAvailable_ = false;\n /** @private {?ServiceWorker} The current active service worker. */\n this.activeServiceWorker_ = null;\n var scope = this;\n if (fireauth.util.getWorkerGlobalScope()) {\n this.receiver_ = fireauth.messagechannel.Receiver.getInstance(\n /** @type {!WorkerGlobalScope} */ (\n fireauth.util.getWorkerGlobalScope()));\n // Listen to indexedDB changes.\n this.receiver_.subscribe('keyChanged', function(origin, request) {\n // Sync data.\n return scope.sync_().then(function(keys) {\n // Trigger listeners if unhandled changes are detected.\n if (keys.length > 0) {\n goog.array.forEach(\n scope.storageListeners_,\n function(listener) {\n listener(keys);\n });\n }\n // When this is false, it means the change was already\n // detected and processed before the notification.\n return {\n 'keyProcessed': goog.array.contains(keys, request['key'])\n };\n });\n });\n // Used to inform sender that service worker what events it supports.\n this.receiver_.subscribe('ping', function(origin, request) {\n return goog.Promise.resolve(['keyChanged']);\n });\n } else {\n // Get active service worker when its available.\n fireauth.util.getActiveServiceWorker()\n .then(function(sw) {\n scope.activeServiceWorker_ = sw;\n if (sw) {\n // Initialize the sender.\n scope.sender_ = new fireauth.messagechannel.Sender(\n new fireauth.messagechannel.WorkerClientPostMessager(sw));\n // Ping the service worker to check what events they can handle.\n // Use long timeout.\n scope.sender_.send('ping', null, true)\n .then(function(results) {\n // Check if keyChanged is supported.\n if (results[0]['fulfilled'] &&\n goog.array.contains(results[0]['value'], 'keyChanged')) {\n scope.serviceWorkerReceiverAvailable_ = true;\n }\n })\n .thenCatch(function(error) {\n // Ignore error.\n });\n }\n });\n }\n};\n\n\n\n/**\n * The indexedDB database name where all local storage data is to be stored.\n * @private @const {string}\n */\nfireauth.storage.IndexedDB.DB_NAME_ = 'firebaseLocalStorageDb';\n\n\n/**\n * The indexedDB object store name where all local storage data is to be stored.\n * @private @const {string}\n */\nfireauth.storage.IndexedDB.DATA_OBJECT_STORE_NAME_ = 'firebaseLocalStorage';\n\n\n/**\n * The indexedDB object store index name used to key all local storage data.\n * @private @const {string}\n */\nfireauth.storage.IndexedDB.DATA_KEY_PATH_ = 'fbase_key';\n\n\n/**\n * The indexedDB object store value field for each entry.\n * @private @const {string}\n */\nfireauth.storage.IndexedDB.VALUE_KEY_PATH_ = 'value';\n\n\n/**\n * The indexedDB database version number.\n * @private @const {number}\n */\nfireauth.storage.IndexedDB.VERSION_ = 1;\n\n\n/**\n * The indexedDB polling delay time in milliseconds.\n * @private @const {number}\n */\nfireauth.storage.IndexedDB.POLLING_DELAY_ = 800;\n\n\n/**\n * The indexedDB polling stop error.\n * @private @const {string}\n */\nfireauth.storage.IndexedDB.STOP_ERROR_ = 'STOP_EVENT';\n\n\n\n/**\n * @return {!fireauth.storage.IndexedDB} The Firebase Auth indexedDB\n * local storage manager.\n */\nfireauth.storage.IndexedDB.getFireauthManager = function() {\n if (!fireauth.storage.IndexedDB.managerInstance_) {\n fireauth.storage.IndexedDB.managerInstance_ =\n new fireauth.storage.IndexedDB(\n fireauth.storage.IndexedDB.DB_NAME_,\n fireauth.storage.IndexedDB.DATA_OBJECT_STORE_NAME_,\n fireauth.storage.IndexedDB.DATA_KEY_PATH_,\n fireauth.storage.IndexedDB.VALUE_KEY_PATH_,\n fireauth.storage.IndexedDB.VERSION_);\n }\n return fireauth.storage.IndexedDB.managerInstance_;\n};\n\n\n/**\n * Delete the indexedDB database.\n * @return {!goog.Promise<!IDBDatabase>} A promise that resolves on successful\n * database deletion.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.deleteDb_ = function() {\n var self = this;\n return new goog.Promise(function(resolve, reject) {\n var request = self.indexedDB_.deleteDatabase(self.dbName_);\n request.onsuccess = function(event) {\n resolve();\n };\n request.onerror = function(event) {\n reject(new Error(event.target.error));\n };\n });\n};\n\n\n/**\n * Initializes The indexedDB database, creates it if not already created and\n * opens it.\n * @return {!goog.Promise<!IDBDatabase>} A promise for the database object.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.initializeDb_ = function() {\n var self = this;\n return new goog.Promise(function(resolve, reject) {\n var request = self.indexedDB_.open(self.dbName_, self.version_);\n request.onerror = function(event) {\n // Suppress this from surfacing to browser console.\n try {\n event.preventDefault();\n } catch (e) {}\n reject(new Error(event.target.error));\n };\n request.onupgradeneeded = function(event) {\n var db = event.target.result;\n try {\n db.createObjectStore(\n self.objectStoreName_,\n {\n 'keyPath': self.dataKeyPath_\n });\n } catch (e) {\n reject(e);\n }\n };\n request.onsuccess = function(event) {\n var db = event.target.result;\n // Strange bug that occurs in Firefox when multiple tabs are opened at the\n // same time. The only way to recover seems to be deleting the database\n // and re-initializing it.\n // https://github.com/firebase/firebase-js-sdk/issues/634\n if (!db.objectStoreNames.contains(self.objectStoreName_)) {\n self.deleteDb_()\n .then(function() {\n return self.initializeDb_();\n })\n .then(function(newDb) {\n resolve(newDb);\n })\n .thenCatch(function(e) {\n reject(e);\n });\n } else {\n resolve(db);\n }\n };\n });\n};\n\n\n/**\n * Checks if indexedDB is initialized, if so, the callback is run, otherwise,\n * it waits for the db to initialize and then runs the callback function.\n * @return {!goog.Promise<!IDBDatabase>} A promise for the initialized indexedDB\n * database.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.initializeDbAndRun_ =\n function() {\n if (!this.initPromise_) {\n this.initPromise_ = this.initializeDb_();\n }\n return this.initPromise_;\n};\n\n\n/**\n * @return {boolean} Whether indexedDB is available or not.\n */\nfireauth.storage.IndexedDB.isAvailable = function() {\n try {\n return !!goog.global['indexedDB'];\n } catch (e) {\n return false;\n }\n};\n\n\n/**\n * Creates a reference for the local storage indexedDB object store and returns\n * it.\n * @param {!IDBTransaction} tx The IDB transaction instance.\n * @return {!IDBObjectStore} The indexedDB object store.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.getDataObjectStore_ =\n function(tx) {\n return tx.objectStore(this.objectStoreName_);\n};\n\n\n/**\n * Creates an IDB transaction and returns it.\n * @param {!IDBDatabase} db The indexedDB instance.\n * @param {boolean} isReadWrite Whether the current indexedDB operation is a\n * read/write operation or not.\n * @return {!IDBTransaction} The requested IDB transaction instance.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.getTransaction_ =\n function(db, isReadWrite) {\n var tx = db.transaction(\n [this.objectStoreName_],\n isReadWrite ? 'readwrite' : 'readonly');\n return tx;\n};\n\n\n/**\n * @param {!IDBRequest} request The IDB request instance.\n * @return {!goog.Promise} The promise to resolve on transaction completion.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.onIDBRequest_ =\n function(request) {\n return new goog.Promise(function(resolve, reject) {\n request.onsuccess = function(event) {\n if (event && event.target) {\n resolve(event.target.result);\n } else {\n resolve();\n }\n };\n request.onerror = function(event) {\n reject(event.target.error);\n };\n });\n};\n\n\n/**\n * Sets the item's identified by the key provided to the value passed. If the\n * item does not exist, it is created. An optional callback is run on success.\n * @param {string} key The storage key for the item to set. If the item exists,\n * it is updated, otherwise created.\n * @param {*} value The value to store for the item to set.\n * @return {!goog.Promise<void>} A promise that resolves on operation success.\n * @override\n */\nfireauth.storage.IndexedDB.prototype.set = function(key, value) {\n var isLocked = false;\n var dbTemp;\n var self = this;\n return this.initializeDbAndRun_()\n .then(function(db) {\n dbTemp = db;\n var objectStore = self.getDataObjectStore_(\n self.getTransaction_(dbTemp, true));\n return self.onIDBRequest_(objectStore.get(key));\n })\n .then(function(data) {\n var objectStore = self.getDataObjectStore_(\n self.getTransaction_(dbTemp, true));\n if (data) {\n // Update the value(s) in the object that you want to change\n data.value = value;\n // Put this updated object back into the database.\n return self.onIDBRequest_(objectStore.put(data));\n }\n self.pendingOpsTracker_++;\n isLocked = true;\n var obj = {};\n obj[self.dataKeyPath_] = key;\n obj[self.valueKeyPath_] = value;\n return self.onIDBRequest_(objectStore.add(obj));\n })\n .then(function() {\n // Save in local copy to avoid triggering false external event.\n self.localMap_[key] = value;\n // Announce change in key to service worker.\n return self.notifySW_(key);\n })\n .thenAlways(function() {\n if (isLocked) {\n self.pendingOpsTracker_--;\n }\n });\n};\n\n\n/**\n * Notify the service worker of the indexeDB write operation.\n * Waits until the operation is processed.\n * @param {string} key The key which is changing.\n * @return {!goog.Promise<void>} A promise that resolves on delivery.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.notifySW_ = function(key) {\n // If sender is available.\n // Run some sanity check to confirm no sw change occurred.\n // For now, we support one service worker per page.\n if (this.sender_ &&\n this.activeServiceWorker_ &&\n fireauth.util.getServiceWorkerController() ===\n this.activeServiceWorker_) {\n return this.sender_.send(\n 'keyChanged',\n {'key': key},\n // Use long timeout if receiver is known to be available.\n this.serviceWorkerReceiverAvailable_)\n .then(function(responses) {\n // Return nothing.\n })\n .thenCatch(function(error) {\n // This is a best effort approach. Ignore errors.\n });\n }\n return goog.Promise.resolve();\n};\n\n\n/**\n * Retrieves a stored item identified by the key provided asynchronously.\n * The value is passed to the callback function provided.\n * @param {string} key The storage key for the item to fetch.\n * @return {!goog.Promise} A promise that resolves with the item's value, or\n * null if the item is not found.\n * @override\n */\nfireauth.storage.IndexedDB.prototype.get = function(key) {\n var self = this;\n return this.initializeDbAndRun_()\n .then(function(db) {\n return self.onIDBRequest_(\n self.getDataObjectStore_(self.getTransaction_(db, false)).get(key));\n })\n .then(function(response) {\n return response && response.value;\n });\n};\n\n\n/**\n * Deletes the item identified by the key provided and on success, runs the\n * optional callback.\n * @param {string} key The storage key for the item to remove.\n * @return {!goog.Promise<void>} A promise that resolves on operation success.\n * @override\n */\nfireauth.storage.IndexedDB.prototype.remove = function(key) {\n var isLocked = false;\n var self = this;\n return this.initializeDbAndRun_()\n .then(function(db) {\n isLocked = true;\n self.pendingOpsTracker_++;\n return self.onIDBRequest_(\n self.getDataObjectStore_(\n self.getTransaction_(db, true))['delete'](key));\n }).then(function() {\n // Delete from local copy to avoid triggering false external event.\n delete self.localMap_[key];\n // Announce change in key to service worker.\n return self.notifySW_(key);\n }).thenAlways(function() {\n if (isLocked) {\n self.pendingOpsTracker_--;\n }\n });\n};\n\n\n/**\n * @return {!goog.Promise<!Array<string>>} A promise that resolved with all the\n * storage keys that have changed.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.sync_ = function() {\n var self = this;\n return this.initializeDbAndRun_()\n .then(function(db) {\n var objectStore =\n self.getDataObjectStore_(self.getTransaction_(db, false));\n if (objectStore['getAll']) {\n // Get all keys and value pairs using getAll if supported.\n return self.onIDBRequest_(objectStore['getAll']());\n } else {\n // If getAll isn't supported, fallback to cursor.\n return new goog.Promise(function(resolve, reject) {\n var res = [];\n var request = objectStore.openCursor();\n request.onsuccess = function(event) {\n var cursor = event.target.result;\n if (cursor) {\n res.push(cursor.value);\n cursor['continue']();\n } else {\n resolve(res);\n }\n };\n request.onerror = function(event) {\n reject(event.target.error);\n };\n });\n }\n }).then(function(res) {\n var centralCopy = {};\n // List of keys differing from central copy.\n var diffKeys = [];\n // Build central copy (external copy).\n if (self.pendingOpsTracker_ == 0) {\n for (var i = 0; i < res.length; i++) {\n centralCopy[res[i][self.dataKeyPath_]] =\n res[i][self.valueKeyPath_];\n }\n // Get diff of central copy and local copy.\n diffKeys = fireauth.util.getKeyDiff(self.localMap_, centralCopy);\n // Update local copy.\n self.localMap_ = centralCopy;\n }\n // Return modified keys.\n return diffKeys;\n });\n};\n\n\n/**\n * Adds a listener to storage event change.\n * @param {function(!Array<string>)} listener The storage event listener.\n * @override\n */\nfireauth.storage.IndexedDB.prototype.addStorageListener =\n function(listener) {\n // First listener, start listeners.\n if (this.storageListeners_.length == 0) {\n this.startListeners_();\n }\n this.storageListeners_.push(listener);\n};\n\n\n/**\n * Removes a listener to storage event change.\n * @param {function(!Array<string>)} listener The storage event listener.\n * @override\n */\nfireauth.storage.IndexedDB.prototype.removeStorageListener =\n function(listener) {\n goog.array.removeAllIf(\n this.storageListeners_,\n function(ele) {\n return ele == listener;\n });\n // No more listeners, stop.\n if (this.storageListeners_.length == 0) {\n this.stopListeners_();\n }\n};\n\n\n/**\n * Removes all listeners to storage event change.\n */\nfireauth.storage.IndexedDB.prototype.removeAllStorageListeners =\n function() {\n this.storageListeners_ = [];\n // No more listeners, stop.\n this.stopListeners_();\n};\n\n\n/**\n * Starts the listener to storage events.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.startListeners_ = function() {\n var self = this;\n // Stop any previous listeners.\n this.stopListeners_();\n var repeat = function() {\n self.pollTimerId_ = setTimeout(\n function() {\n self.poll_ = self.sync_()\n .then(function(keys) {\n // If keys modified, call listeners.\n if (keys.length > 0) {\n goog.array.forEach(\n self.storageListeners_,\n function(listener) {\n listener(keys);\n });\n }\n })\n .then(function() {\n repeat();\n })\n .thenCatch(function(error) {\n if (error.message != fireauth.storage.IndexedDB.STOP_ERROR_) {\n repeat();\n }\n });\n },\n fireauth.storage.IndexedDB.POLLING_DELAY_);\n };\n repeat();\n};\n\n\n/**\n * Stops the listener to storage events.\n * @private\n */\nfireauth.storage.IndexedDB.prototype.stopListeners_ = function() {\n if (this.poll_) {\n // Cancel polling function.\n this.poll_.cancel(fireauth.storage.IndexedDB.STOP_ERROR_);\n }\n // Clear any pending polling timer.\n if (this.pollTimerId_) {\n clearTimeout(this.pollTimerId_);\n this.pollTimerId_ = null;\n }\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 PostMessager interface needed for the\n * `fireauth.messagechannel.Sender`, in addition to 2 types of implementations.\n */\n\ngoog.provide('fireauth.messagechannel.PostMessager');\ngoog.provide('fireauth.messagechannel.WindowPostMessager');\ngoog.provide('fireauth.messagechannel.WorkerClientPostMessager');\n\n\n/**\n * This is the interface defining the postMessage format of a window which\n * takes an additional second parameter for target origin.\n *\n * @typedef {{\n * postMessage: function(*, string, !Array<!Transferable>)\n * }}\n */\nfireauth.messagechannel.Window;\n\n\n/**\n * This is the interface defining the postMessage format of a worker or\n * ServiceWorkerClient, etc. which just takes a message and a list of\n * Transferables.\n *\n * @typedef {{\n * postMessage: function(*, !Array<!Transferable>)\n * }}\n */\nfireauth.messagechannel.WorkerClient;\n\n\n/**\n * Defines a common interface to postMessage data to a specified PostMessager.\n * @interface\n */\nfireauth.messagechannel.PostMessager = function() {};\n\n\n/**\n * Sends a message to the specified context.\n * @param {*} message The message to send.\n * @param {!Array<!Transferable>} transfer The list of `Transferable` objects\n * that are transferred with the message. The ownsership fo these objects is\n * given to the destination side and they are no longer usable on the\n * sending side.\n */\nfireauth.messagechannel.PostMessager.prototype.postMessage =\n function(message, transfer) {};\n\n\n\n/**\n * Defines the implementation for postMessaging to a window context.\n * @param {!fireauth.messagechannel.Window} win The window PostMessager.\n * @param {?string=} opt_targetOrigin The target origin.\n * @constructor\n * @implements {fireauth.messagechannel.PostMessager}\n */\nfireauth.messagechannel.WindowPostMessager = function(win, opt_targetOrigin) {\n /**\n * @const @private {!fireauth.messagechannel.Window} The window PostMessager.\n */\n this.win_ = win;\n /** @const @private {string} The postMessage target origin. */\n this.targetOrigin_ = opt_targetOrigin || '*';\n};\n\n\n/**\n * Sends a message to the specified window context.\n * @param {*} message The message to send.\n * @param {!Array<!Transferable>} transfer The list of `Transferable` objects\n * that are transferred with the message. The ownsership fo these objects is\n * given to the destination side and they are no longer usable on the\n * sending side.\n * @override\n */\nfireauth.messagechannel.WindowPostMessager.prototype.postMessage =\n function(message, transfer) {\n this.win_.postMessage(message, this.targetOrigin_, transfer);\n};\n\n\n/**\n * Defines the implementation for postMessaging to a worker/client context.\n * @param {!fireauth.messagechannel.WorkerClient} worker The worker/client\n * PostMessager.\n * @constructor\n * @implements {fireauth.messagechannel.PostMessager}\n */\nfireauth.messagechannel.WorkerClientPostMessager = function(worker) {\n /**\n * @const @private {!fireauth.messagechannel.WorkerClient} The worker/client\n * PostMessager.\n */\n this.worker_ = worker;\n};\n\n\n/**\n * Sends a message to the specified worker/client context.\n * @param {*} message The message to send.\n * @param {!Array<!Transferable>} transfer The list of `Transferable` objects\n * that are transferred with the message. The ownsership fo these objects is\n * given to the destination side and they are no longer usable on the\n * sending side.\n * @override\n */\nfireauth.messagechannel.WorkerClientPostMessager.prototype.postMessage =\n function(message, transfer) {\n this.worker_.postMessage(message, transfer);\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 MessageChannel based wrapper for sending messages\n * to other windows or workers.\n */\n\ngoog.provide('fireauth.messagechannel.Sender');\n\ngoog.require('fireauth.messagechannel.Error');\ngoog.require('fireauth.messagechannel.PostMessager');\ngoog.require('fireauth.messagechannel.Status');\ngoog.require('fireauth.messagechannel.TimeoutDuration');\ngoog.require('fireauth.messagechannel.utils');\ngoog.require('goog.Promise');\ngoog.require('goog.array');\n\n\n/**\n * This is the interface defining a MessageChannel/handler pair.\n *\n * @typedef {{\n * onMessage: function(!Event),\n * messageChannel: !MessageChannel\n * }}\n */\nfireauth.messagechannel.MessageHandler;\n\n\n/**\n * Helper static function to create messageChannel errors.\n * @param {!fireauth.messagechannel.Error} errorId The error identifier.\n * @param {?string=} opt_message The optional error message used for generic\n * error types.\n * @return {!Error} The constructed error to return.\n * @private\n */\nfireauth.messagechannel.createError_ = function(errorId, opt_message) {\n if (errorId != fireauth.messagechannel.Error.UNKNOWN || !opt_message) {\n return new Error(errorId);\n } else {\n return new Error(opt_message);\n }\n};\n\n\n/**\n * Initializes a channel to send specific messages to a specified PostMessage.\n * @param {!fireauth.messagechannel.PostMessager} postMessager The post messager\n * to send messages to.\n * @constructor\n */\nfireauth.messagechannel.Sender = function(postMessager) {\n /**\n * @const @private {!fireauth.messagechannel.PostMessager} The messageChannel\n * PostMessager.\n */\n this.postMessager_ = postMessager;\n /** @private {boolean} Whether the connection was closed. */\n this.closed_ = false;\n /**\n * @const @private {!Array<!fireauth.messagechannel.MessageHandler>} The list\n * of subscribed message handlers and their corresponding MessageChannels.\n */\n this.messageHandlers_ = [];\n};\n\n\n/**\n * Sends a message to the receiver. The message is identified by an event\n * type and can carry additional payload data.\n * The sender protocol works as follows:\n * <ul>\n * <li>The request is constructed and postMessaged to the receiver with the port\n * used to reply back to sender.</li>\n * <li>The operation will block until an ACK response is received. If not, it\n * will timeout and reject with an error.</li>\n * <li>If an ACK response is received, it will wait longer for the full\n * processed response.</li>\n * <li>Once the response is received, the operation will resolve with that\n * result.</li>\n * </ul>\n *\n * @param {string} eventType The event type identifying the message. This is\n * used to help the receiver handle this message.\n * @param {?Object=} opt_data The optional data to send along the message.\n * @param {?boolean=} opt_useLongTimeout Whether long timeout should be used\n * for ACK responses.\n * @return {!goog.Promise<!Array<{fulfilled: boolean,\n * value: (*|undefined),\n * reason: (*|undefined)}>>} A promise that\n * resolves with the receiver responses.\n */\nfireauth.messagechannel.Sender.prototype.send = function(\n eventType, opt_data, opt_useLongTimeout) {\n var self = this;\n var eventId;\n var data = opt_data || {};\n var onMessage;\n var ackTimer;\n var completionTimer;\n var entry = null;\n if (this.closed_) {\n return goog.Promise.reject(fireauth.messagechannel.createError_(\n fireauth.messagechannel.Error.CONNECTION_UNAVAILABLE));\n }\n var ackTimeout =\n !!opt_useLongTimeout ?\n fireauth.messagechannel.TimeoutDuration.LONG_ACK :\n fireauth.messagechannel.TimeoutDuration.ACK;\n var messageChannel =\n fireauth.messagechannel.utils.initializeMessageChannel();\n return new goog.Promise(function(resolve, reject) {\n // Send message along with port for reply\n if (messageChannel) {\n eventId = fireauth.messagechannel.utils.generateEventId();\n // Start the connection if not already started.\n messageChannel.port1.start();\n // Handler for receiving message reply from receiver.\n // Blocks promise resolution until service worker detects the change.\n ackTimer = setTimeout(function() {\n // The receiver may not be able to handle the response for various\n // reasons: library not included, or an incompatible version of\n // the library is included.\n // Timeout after some time.\n reject(fireauth.messagechannel.createError_(\n fireauth.messagechannel.Error.UNSUPPORTED_EVENT));\n }, ackTimeout);\n onMessage = function(event) {\n // Process only the expected events that match current event ID.\n if (event.data['eventId'] !== eventId) {\n return;\n }\n // This avoids adding a long wait when the receiver is unable to handle\n // the event.\n if (event.data['status'] === fireauth.messagechannel.Status.ACK) {\n clearTimeout(ackTimer);\n // Set longer timeout to allow receiver to process.\n completionTimer = setTimeout(function() {\n reject(fireauth.messagechannel.createError_(\n fireauth.messagechannel.Error.TIMEOUT));\n }, fireauth.messagechannel.TimeoutDuration.COMPLETION);\n return;\n } else if (event.data['status'] ===\n fireauth.messagechannel.Status.DONE) {\n clearTimeout(completionTimer);\n if (typeof event.data['response'] !== 'undefined') {\n resolve(event.data['response']);\n } else {\n reject(fireauth.messagechannel.createError_(\n fireauth.messagechannel.Error.UNKNOWN));\n }\n } else {\n clearTimeout(ackTimer);\n clearTimeout(completionTimer);\n reject(fireauth.messagechannel.createError_(\n fireauth.messagechannel.Error.INVALID_RESPONSE));\n }\n };\n entry = {\n 'messageChannel': messageChannel,\n 'onMessage': onMessage\n };\n self.messageHandlers_.push(entry);\n messageChannel.port1.addEventListener('message', onMessage);\n var request = {\n 'eventType': eventType,\n 'eventId': eventId,\n 'data': data\n };\n // It is possible the receiver cannot handle this result.\n // For example, the developer may not be including the library in the\n // receiver or using an outdated version.\n self.postMessager_.postMessage(\n request,\n [messageChannel.port2]);\n } else {\n // No connection available.\n reject(fireauth.messagechannel.createError_(\n fireauth.messagechannel.Error.CONNECTION_UNAVAILABLE));\n }\n }).then(function(result) {\n // On completion, remove the message handler. A new one is needed for a\n // new message.\n self.removeMessageHandler_(entry);\n return result;\n }).thenCatch(function(error) {\n // On failure, remove the message handler. A new one is needed for a new\n // message.\n self.removeMessageHandler_(entry);\n throw error;\n });\n};\n\n\n/**\n * Removes the onMessage handler for the specified messageChannel.\n * @param {?fireauth.messagechannel.MessageHandler} messageHandler\n * @private\n */\nfireauth.messagechannel.Sender.prototype.removeMessageHandler_ =\n function(messageHandler) {\n if (!messageHandler) {\n return;\n }\n var messageChannel = messageHandler['messageChannel'];\n var onMessage = messageHandler['onMessage'];\n if (messageChannel) {\n messageChannel.port1.removeEventListener('message', onMessage);\n messageChannel.port1.close();\n }\n goog.array.removeAllIf(this.messageHandlers_, function(ele) {\n return ele == messageHandler;\n });\n};\n\n\n/** Closes the underlying MessageChannel connection. */\nfireauth.messagechannel.Sender.prototype.close = function() {\n // Any pending event will timeout.\n while (this.messageHandlers_.length > 0) {\n this.removeMessageHandler_(this.messageHandlers_[0]);\n }\n this.closed_ = true;\n};\n\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 MessageChannel common utilities and enums.\n */\n\ngoog.provide('fireauth.messagechannel.Error');\ngoog.provide('fireauth.messagechannel.Status');\ngoog.provide('fireauth.messagechannel.TimeoutDuration');\ngoog.provide('fireauth.messagechannel.utils');\n\n\n/**\n * Enum for the messagechannel error messages. These errors are not meant to be\n * user facing.\n * @enum {string}\n */\nfireauth.messagechannel.Error = {\n CONNECTION_CLOSED: 'connection_closed',\n CONNECTION_UNAVAILABLE: 'connection_unavailable',\n INVALID_RESPONSE: 'invalid_response',\n TIMEOUT: 'timeout',\n UNKNOWN: 'unknown_error',\n UNSUPPORTED_EVENT: 'unsupported_event'\n};\n\n\n/**\n * Enum for the message channel request status labels.\n * @enum {string}\n */\nfireauth.messagechannel.Status = {\n ACK: 'ack',\n DONE: 'done'\n};\n\n\n/**\n * Enum for the timeout durations in milliseconds for different contexts.\n * @enum {number}\n */\nfireauth.messagechannel.TimeoutDuration = {\n ACK: 50,\n COMPLETION: 3000,\n // Used when a handler is confirmed to be available on the other side.\n LONG_ACK: 800\n};\n\n\n/**\n * @param {?string=} opt_prefix An optional prefix string to prepend to ID.\n * @param {?number=} opt_digits An optional number of digits used for event ID.\n * @return {string} The generated event ID used to identify a generic event.\n */\nfireauth.messagechannel.utils.generateEventId =\n function(opt_prefix, opt_digits) {\n // 0, null and undefined will default to 20.\n var digits = opt_digits || 20;\n return opt_prefix ? opt_prefix : '' +\n Math.floor(Math.random() * Math.pow(10, digits)).toString();\n};\n\n\n/**\n * @return {?MessageChannel} The initialized MessageChannel instance if\n * supported.\n */\nfireauth.messagechannel.utils.initializeMessageChannel = function() {\n return typeof MessageChannel !== 'undefined' ? new MessageChannel() : null;\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.HybridIndexedDB');\n\ngoog.require('fireauth.storage.IndexedDB');\ngoog.require('fireauth.storage.Storage');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.array');\n\n/**\n * HybridStorage provides an interface to indexedDB, the persistent Web\n * Storage API for browsers that support it. This will fallback to the provided\n * fallback storage when indexedDB is not supported which is determined\n * asynchronously.\n * @param {!fireauth.storage.Storage} fallbackStorage The storage to fallback to\n * when indexedDB is not available.\n * @constructor\n * @implements {fireauth.storage.Storage}\n */\nfireauth.storage.HybridIndexedDB = function(fallbackStorage) {\n var self = this;\n var storage = null;\n /**\n * @const @private {!Array<function((!goog.events.BrowserEvent|\n * !Array<string>))>} The storage listeners.\n */\n this.storageListeners_ = [];\n // This type may change if the fallback is used.\n /** @public {string} The storage type identifier. */\n this.type = fireauth.storage.Storage.Type.INDEXEDDB;\n /**\n * @const @private {!fireauth.storage.Storage} The fallback storage when\n * indexedDB is unavailable.\n */\n this.fallbackStorage_ = fallbackStorage;\n /**\n * @const @private {!goog.Promise<!fireauth.storage.Storage>} A promise that\n * resolves with the underlying indexedDB storage or a fallback when not\n * supported.\n */\n this.underlyingStoragePromise_ = goog.Promise.resolve().then(function() {\n // Initial check shows indexedDB is available. This is not enough.\n // Try to write/read from indexedDB. If it fails, switch to fallback.\n if (fireauth.storage.IndexedDB.isAvailable()) {\n // Test write/read using a random key. This is important for the following\n // reasons:\n // 1. Double inclusion of the firebase-auth.js library.\n // 2. Multiple windows opened at the same time.\n // The above may cause collision if multiple instances try to\n // write/read/delete from the same entry.\n var randomId = fireauth.util.generateEventId();\n var randomKey = fireauth.storage.HybridIndexedDB.KEY_ + randomId;\n storage = fireauth.storage.IndexedDB.getFireauthManager();\n return storage.set(randomKey, randomId)\n .then(function() {\n return storage.get(randomKey);\n })\n .then(function(value) {\n if (value !== randomId) {\n throw new Error('indexedDB not supported!');\n }\n return storage.remove(randomKey);\n })\n .then(function() {\n return storage;\n })\n .thenCatch(function(error) {\n return self.fallbackStorage_;\n });\n } else {\n // indexedDB not available, use fallback.\n return self.fallbackStorage_;\n }\n }).then(function(storage) {\n // Update type.\n self.type = storage.type;\n // Listen to all storage changes.\n storage.addStorageListener(function(key) {\n // Trigger all attached storage listeners.\n goog.array.forEach(self.storageListeners_, function(listener) {\n listener(key);\n });\n });\n return storage;\n });\n};\n\n\n/**\n * The key used to check if the storage instance is available.\n * @private {string}\n * @const\n */\nfireauth.storage.HybridIndexedDB.KEY_ = '__sak';\n\n\n/**\n * Retrieves the value stored at the key.\n * @param {string} key\n * @return {!goog.Promise<*>}\n * @override\n */\nfireauth.storage.HybridIndexedDB.prototype.get = function(key) {\n return this.underlyingStoragePromise_.then(function(storage) {\n return storage.get(key);\n });\n};\n\n\n/**\n * Stores the value at the specified key.\n * @param {string} key\n * @param {*} value\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.HybridIndexedDB.prototype.set = function(key, value) {\n return this.underlyingStoragePromise_.then(function(storage) {\n return storage.set(key, value);\n });\n};\n\n\n/**\n * Removes the value at the specified key.\n * @param {string} key\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.HybridIndexedDB.prototype.remove = function(key) {\n return this.underlyingStoragePromise_.then(function(storage) {\n return storage.remove(key);\n });\n};\n\n\n/**\n * Adds a listener to storage event change.\n * @param {function((!goog.events.BrowserEvent|!Array<string>))} listener The\n * storage event listener.\n * @override\n */\nfireauth.storage.HybridIndexedDB.prototype.addStorageListener =\n function(listener) {\n this.storageListeners_.push(listener);\n};\n\n\n/**\n * Removes a listener to storage event change.\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.HybridIndexedDB.prototype.removeStorageListener =\n function(listener) {\n goog.array.removeAllIf(this.storageListeners_, function(ele) {\n return ele == listener;\n });\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.InMemoryStorage');\n\ngoog.require('goog.Promise');\n\n\n\n/**\n * InMemoryStorage provides an implementation of Storage that will only persist\n * data in memory. This data is volatile and in a browser environment, will\n * be lost on page unload and will only be available in the current window.\n * This is a useful fallback for browsers where web storage is disabled or\n * environments where the preferred storage mechanism is not available or not\n * supported.\n * @constructor\n * @implements {fireauth.storage.Storage}\n */\nfireauth.storage.InMemoryStorage = function() {\n /** @protected {!Object} The object where we store values. */\n this.storage = {};\n /** @public {string} The storage type identifier. */\n this.type = fireauth.storage.Storage.Type.IN_MEMORY;\n};\n\n\n/**\n * @param {string} key\n * @return {!goog.Promise<*>}\n * @override\n */\nfireauth.storage.InMemoryStorage.prototype.get = function(key) {\n return goog.Promise.resolve(/** @type {*} */ (this.storage[key]));\n};\n\n\n/**\n * @param {string} key\n * @param {*} value\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.InMemoryStorage.prototype.set = function(key, value) {\n this.storage[key] = value;\n return goog.Promise.resolve();\n};\n\n\n/**\n * @param {string} key\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.InMemoryStorage.prototype.remove = function(key) {\n delete this.storage[key];\n return goog.Promise.resolve();\n};\n\n\n/**\n * @param {function((!goog.events.BrowserEvent|!Array<string>))} listener The\n * storage event listener.\n * @override\n */\nfireauth.storage.InMemoryStorage.prototype.addStorageListener =\n function(listener) {\n};\n\n\n/**\n * @param {function((!goog.events.BrowserEvent|!Array<string>))} listener The\n * storage event listener.\n * @override\n */\nfireauth.storage.InMemoryStorage.prototype.removeStorageListener = function(\n listener) {};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.LocalStorage');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.storage.Storage');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.events');\n\n\n\n/**\n * LocalStorage provides an interface to localStorage, the persistent Web\n * Storage API.\n * @constructor\n * @implements {fireauth.storage.Storage}\n */\nfireauth.storage.LocalStorage = function() {\n // Check is localStorage available in the current environment.\n if (!fireauth.storage.LocalStorage.isAvailable()) {\n // In a Node.js environment, dom-storage module needs to be required.\n if (fireauth.util.getEnvironment() == fireauth.util.Env.NODE) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'The LocalStorage compatibility library was not found.');\n }\n throw new fireauth.AuthError(\n fireauth.authenum.Error.WEB_STORAGE_UNSUPPORTED);\n }\n\n /**\n * The underlying storage instance for persistent data.\n * @private {!Storage}\n */\n this.storage_ = /** @type {!Storage} */ (\n fireauth.storage.LocalStorage.getGlobalStorage() ||\n firebase.INTERNAL['node']['localStorage']);\n /** @public {string} The storage type identifier. */\n this.type = fireauth.storage.Storage.Type.LOCAL_STORAGE;\n};\n\n\n/** @return {?Storage|undefined} The global localStorage instance. */\nfireauth.storage.LocalStorage.getGlobalStorage = function() {\n try {\n var storage = goog.global['localStorage'];\n // Try editing web storage. If an error is thrown, it may be disabled.\n var key = fireauth.util.generateEventId();\n if (storage) {\n storage['setItem'](key, '1');\n storage['removeItem'](key);\n }\n return storage;\n } catch (e) {\n // In some cases, browsers with web storage disabled throw an error simply\n // on access.\n return null;\n }\n};\n\n\n/**\n * The key used to check if the storage instance is available.\n * @private {string}\n * @const\n */\nfireauth.storage.LocalStorage.STORAGE_AVAILABLE_KEY_ = '__sak';\n\n\n/** @return {boolean} Whether localStorage is available. */\nfireauth.storage.LocalStorage.isAvailable = function() {\n // In Node.js localStorage is polyfilled.\n var isNode = fireauth.util.getEnvironment() == fireauth.util.Env.NODE;\n // Either window should provide this storage mechanism or in case of Node.js,\n // firebase.INTERNAL should provide it.\n var storage = fireauth.storage.LocalStorage.getGlobalStorage() ||\n (isNode &&\n firebase.INTERNAL['node'] &&\n firebase.INTERNAL['node']['localStorage']);\n if (!storage) {\n return false;\n }\n try {\n // setItem will throw an exception if we cannot access web storage (e.g.,\n // Safari in private mode).\n storage.setItem(fireauth.storage.LocalStorage.STORAGE_AVAILABLE_KEY_, '1');\n storage.removeItem(fireauth.storage.LocalStorage.STORAGE_AVAILABLE_KEY_);\n return true;\n } catch (e) {\n return false;\n }\n};\n\n\n/**\n * Retrieves the value stored at the key.\n * @param {string} key\n * @return {!goog.Promise<*>}\n * @override\n */\nfireauth.storage.LocalStorage.prototype.get = function(key) {\n var self = this;\n return goog.Promise.resolve()\n .then(function() {\n var json = self.storage_.getItem(key);\n return fireauth.util.parseJSON(json);\n });\n};\n\n\n/**\n * Stores the value at the specified key.\n * @param {string} key\n * @param {*} value\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.LocalStorage.prototype.set = function(key, value) {\n var self = this;\n return goog.Promise.resolve()\n .then(function() {\n var obj = fireauth.util.stringifyJSON(value);\n if (obj === null) {\n self.remove(key);\n } else {\n self.storage_.setItem(key, obj);\n }\n });\n};\n\n\n/**\n * Removes the value at the specified key.\n * @param {string} key\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.LocalStorage.prototype.remove = function(key) {\n var self = this;\n return goog.Promise.resolve()\n .then(function() {\n self.storage_.removeItem(key);\n });\n};\n\n\n/**\n * Adds a listener to storage event change.\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.LocalStorage.prototype.addStorageListener = function(\n listener) {\n if (goog.global['window']) {\n goog.events.listen(goog.global['window'], 'storage', listener);\n }\n};\n\n\n/**\n * Removes a listener to storage event change.\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.LocalStorage.prototype.removeStorageListener = function(\n listener) {\n if (goog.global['window']) {\n goog.events.unlisten(goog.global['window'], 'storage', listener);\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.NullStorage');\n\ngoog.require('fireauth.storage.Storage');\ngoog.require('goog.Promise');\n\n\n\n/**\n * NullStorage provides an implementation of Storage that does always returns\n * null. This can be used if a type of storage is unsupported on a platform.\n * @constructor\n * @implements {fireauth.storage.Storage}\n */\nfireauth.storage.NullStorage = function() {\n /** @private {!Object} The object where we store values. */\n this.storage_ = {};\n /** @public {string} The storage type identifier. */\n this.type = fireauth.storage.Storage.Type.NULL_STORAGE;\n};\n\n\n/**\n * @param {string} key\n * @return {!goog.Promise<*>}\n * @override\n */\nfireauth.storage.NullStorage.prototype.get = function(key) {\n return goog.Promise.resolve(/** @type {*} */ (null));\n};\n\n\n/**\n * @param {string} key\n * @param {*} value\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.NullStorage.prototype.set = function(key, value) {\n return goog.Promise.resolve();\n};\n\n\n/**\n * @param {string} key\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.NullStorage.prototype.remove = function(key) {\n return goog.Promise.resolve();\n};\n\n\n/**\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.NullStorage.prototype.addStorageListener = function(listener) {\n};\n\n\n/**\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.NullStorage.prototype.removeStorageListener = function(\n listener) {};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.SessionStorage');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.storage.Storage');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\n\n\n\n/**\n * SessionStorage provides an interface to sessionStorage, the temporary web\n * storage API.\n * @constructor\n * @implements {fireauth.storage.Storage}\n */\nfireauth.storage.SessionStorage = function() {\n // Check is sessionStorage available in the current environment.\n if (!fireauth.storage.SessionStorage.isAvailable()) {\n // In a Node.js environment, dom-storage module needs to be required.\n if (fireauth.util.getEnvironment() == fireauth.util.Env.NODE) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'The SessionStorage compatibility library was not found.');\n }\n throw new fireauth.AuthError(\n fireauth.authenum.Error.WEB_STORAGE_UNSUPPORTED);\n }\n\n /**\n * The underlying storage instance for temporary data.\n * @private {!Storage}\n */\n this.storage_ = /** @type {!Storage} */ (\n fireauth.storage.SessionStorage.getGlobalStorage() ||\n firebase.INTERNAL['node']['sessionStorage']);\n /** @public {string} The storage type identifier. */\n this.type = fireauth.storage.Storage.Type.SESSION_STORAGE;\n};\n\n\n/** @return {?Storage|undefined} The global sessionStorage instance. */\nfireauth.storage.SessionStorage.getGlobalStorage = function() {\n try {\n var storage = goog.global['sessionStorage'];\n // Try editing web storage. If an error is thrown, it may be disabled.\n var key = fireauth.util.generateEventId();\n if (storage) {\n storage['setItem'](key, '1');\n storage['removeItem'](key);\n }\n return storage;\n } catch (e) {\n // In some cases, browsers with web storage disabled throw an error simply\n // on access.\n return null;\n }\n};\n\n\n/**\n * The key used to check if the storage instance is available.\n * @private {string}\n * @const\n */\nfireauth.storage.SessionStorage.STORAGE_AVAILABLE_KEY_ = '__sak';\n\n\n/** @return {boolean} Whether sessionStorage is available. */\nfireauth.storage.SessionStorage.isAvailable = function() {\n // In Node.js sessionStorage is polyfilled.\n var isNode = fireauth.util.getEnvironment() == fireauth.util.Env.NODE;\n // Either window should provide this storage mechanism or in case of Node.js,\n // firebase.INTERNAL should provide it.\n var storage = fireauth.storage.SessionStorage.getGlobalStorage() ||\n (isNode &&\n firebase.INTERNAL['node'] &&\n firebase.INTERNAL['node']['sessionStorage']);\n if (!storage) {\n return false;\n }\n try {\n // setItem will throw an exception if we cannot access web storage (e.g.,\n // Safari in private mode).\n storage.setItem(\n fireauth.storage.SessionStorage.STORAGE_AVAILABLE_KEY_, '1');\n storage.removeItem(fireauth.storage.SessionStorage.STORAGE_AVAILABLE_KEY_);\n return true;\n } catch (e) {\n return false;\n }\n};\n\n\n/**\n * Retrieves the value stored at the key.\n * @param {string} key\n * @return {!goog.Promise<*>}\n * @override\n */\nfireauth.storage.SessionStorage.prototype.get = function(key) {\n var self = this;\n return goog.Promise.resolve()\n .then(function() {\n var json = self.storage_.getItem(key);\n return fireauth.util.parseJSON(json);\n });\n};\n\n\n/**\n * Stores the value at the specified key.\n * @param {string} key\n * @param {*} value\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.SessionStorage.prototype.set = function(key, value) {\n var self = this;\n return goog.Promise.resolve()\n .then(function() {\n var obj = fireauth.util.stringifyJSON(value);\n if (obj === null) {\n self.remove(key);\n } else {\n self.storage_.setItem(key, obj);\n }\n });\n};\n\n\n/**\n * Removes the value at the specified key.\n * @param {string} key\n * @return {!goog.Promise<void>}\n * @override\n */\nfireauth.storage.SessionStorage.prototype.remove = function(key) {\n var self = this;\n return goog.Promise.resolve()\n .then(function() {\n self.storage_.removeItem(key);\n });\n};\n\n\n/**\n * Adds a listener to storage event change.\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.SessionStorage.prototype.addStorageListener = function(\n listener) {};\n\n\n/**\n * Removes a listener to storage event change.\n * @param {function(!goog.events.BrowserEvent)} listener The storage event\n * listener.\n * @override\n */\nfireauth.storage.SessionStorage.prototype.removeStorageListener = function(\n listener) {};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.storage.Factory');\ngoog.provide('fireauth.storage.Factory.EnvConfig');\n\ngoog.require('fireauth.storage.AsyncStorage');\ngoog.require('fireauth.storage.HybridIndexedDB');\ngoog.require('fireauth.storage.InMemoryStorage');\ngoog.require('fireauth.storage.LocalStorage');\ngoog.require('fireauth.storage.NullStorage');\ngoog.require('fireauth.storage.SessionStorage');\ngoog.require('fireauth.util');\n\n\n/**\n * Factory manages the storage implementations and determines the correct one\n * for the current environment.\n * @param {!fireauth.storage.Factory.EnvConfigType} env The storage\n * configuration for the current environment.\n * @constructor\n */\nfireauth.storage.Factory = function(env) {\n /** @const @private {!fireauth.storage.Factory.EnvConfigType} */\n this.env_ = env;\n};\n\n\n/**\n * Construct the singleton instance of the Factory, automatically detecting\n * the current environment.\n * @return {!fireauth.storage.Factory}\n */\nfireauth.storage.Factory.getInstance = function() {\n if (!fireauth.storage.Factory.instance_) {\n fireauth.storage.Factory.instance_ =\n new fireauth.storage.Factory(fireauth.storage.Factory.getEnvConfig());\n }\n return fireauth.storage.Factory.instance_;\n};\n\n\n/**\n * @typedef {{\n * persistent: function(new:fireauth.storage.Storage),\n * temporary: function(new:fireauth.storage.Storage)\n * }}\n */\nfireauth.storage.Factory.EnvConfigType;\n\n\n/**\n * Configurations of storage for different environments.\n * @enum {!fireauth.storage.Factory.EnvConfigType}\n */\nfireauth.storage.Factory.EnvConfig = {\n BROWSER: {\n persistent: fireauth.storage.LocalStorage,\n temporary: fireauth.storage.SessionStorage\n },\n NODE: {\n persistent: fireauth.storage.LocalStorage,\n temporary: fireauth.storage.SessionStorage\n },\n REACT_NATIVE: {\n persistent: fireauth.storage.AsyncStorage,\n temporary: fireauth.storage.NullStorage\n },\n WORKER: {\n persistent: fireauth.storage.LocalStorage,\n temporary: fireauth.storage.NullStorage\n }\n};\n\n\n/**\n * Detects the current environment and returns the appropriate environment\n * configuration.\n * @return {!fireauth.storage.Factory.EnvConfigType}\n */\nfireauth.storage.Factory.getEnvConfig = function() {\n var envMap = {};\n envMap[fireauth.util.Env.BROWSER] =\n fireauth.storage.Factory.EnvConfig.BROWSER;\n envMap[fireauth.util.Env.NODE] =\n fireauth.storage.Factory.EnvConfig.NODE;\n envMap[fireauth.util.Env.REACT_NATIVE] =\n fireauth.storage.Factory.EnvConfig.REACT_NATIVE;\n envMap[fireauth.util.Env.WORKER] =\n fireauth.storage.Factory.EnvConfig.WORKER; \n return envMap[fireauth.util.getEnvironment()];\n};\n\n\n/**\n * @return {!fireauth.storage.Storage} The persistent storage instance.\n */\nfireauth.storage.Factory.prototype.makePersistentStorage = function() {\n if (fireauth.util.persistsStorageWithIndexedDB()) {\n // If persistent storage is implemented using indexedDB, use indexedDB.\n // Use HybridIndexedDB instead of indexedDB directly since this will\n // fallback to a fallback storage when indexedDB is not supported (private\n // browsing mode, etc).\n return new fireauth.storage.HybridIndexedDB(\n fireauth.util.isWorker() ?\n new fireauth.storage.InMemoryStorage() : new this.env_.persistent());\n }\n return new this.env_.persistent();\n};\n\n\n/**\n * @return {!fireauth.storage.Storage} The temporary storage instance.\n */\nfireauth.storage.Factory.prototype.makeTemporaryStorage = function() {\n return new this.env_.temporary();\n};\n\n\n/**\n * @return {!fireauth.storage.Storage} An in memory storage instance.\n */\nfireauth.storage.Factory.prototype.makeInMemoryStorage = function() {\n return new fireauth.storage.InMemoryStorage();\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 utilities for session management.\n */\n\ngoog.provide('fireauth.authStorage');\ngoog.provide('fireauth.authStorage.Key');\ngoog.provide('fireauth.authStorage.Manager');\ngoog.provide('fireauth.authStorage.Persistence');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.storage.Factory');\ngoog.require('fireauth.storage.Storage');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.array');\ngoog.require('goog.events');\ngoog.require('goog.object');\n\n\n\n/**\n * The namespace for Firebase Auth storage.\n * @private @const {string}\n */\nfireauth.authStorage.NAMESPACE_ = 'firebase';\n\n\n/**\n * The separator for Firebase Auth storage with App ID key.\n * @private @const {string}\n */\nfireauth.authStorage.SEPARATOR_ = ':';\n\n\n/**\n * @const {number} The IE 10 localStorage cross tab synchronization delay in\n * milliseconds.\n */\nfireauth.authStorage.IE10_LOCAL_STORAGE_SYNC_DELAY = 10;\n\n\n/**\n * Enums for Auth state persistence.\n * @enum {string}\n */\nfireauth.authStorage.Persistence = {\n // State will persist even when the browser window is closed or the activity\n // is destroyed in react-native.\n LOCAL: 'local',\n // State is only stored in memory and will be cleared when the window or\n // activity is refreshed.\n NONE: 'none',\n // State will only persist in current session/tab, relevant to web only, and\n // will be cleared when the tab is closed.\n SESSION: 'session'\n};\n\n\n/**\n * Validates that an argument is a valid persistence value. If an invalid type\n * is specified, an error is thrown synchronously.\n * @param {*} arg The argument to validate.\n */\nfireauth.authStorage.validatePersistenceArgument =\n function(arg) {\n // Invalid type error.\n var invalidTypeError = new fireauth.AuthError(\n fireauth.authenum.Error.INVALID_PERSISTENCE);\n // Unsupported type error.\n var unsupportedTypeError = new fireauth.AuthError(\n fireauth.authenum.Error.UNSUPPORTED_PERSISTENCE);\n // Check if the persistence type is a valid one.\n // Throw invalid type error if not valid.\n if (!goog.object.containsValue(fireauth.authStorage.Persistence, arg) ||\n // goog.object.containsValue(fireauth.authStorage.Persistence, ['none'])\n // returns true.\n typeof arg !== 'string') {\n throw invalidTypeError;\n }\n // Validate if the specified type is supported in the current environment.\n switch (fireauth.util.getEnvironment()) {\n case fireauth.util.Env.REACT_NATIVE:\n // This is only supported in a browser.\n if (arg === fireauth.authStorage.Persistence.SESSION) {\n throw unsupportedTypeError;\n }\n break;\n case fireauth.util.Env.NODE:\n // Only none is supported in Node.js.\n if (arg !== fireauth.authStorage.Persistence.NONE) {\n throw unsupportedTypeError;\n }\n break;\n case fireauth.util.Env.BROWSER:\n default:\n // This is restricted by what the browser supports.\n if (!fireauth.util.isWebStorageSupported() &&\n arg !== fireauth.authStorage.Persistence.NONE) {\n throw unsupportedTypeError;\n }\n break;\n }\n};\n\n\n/**\n * Storage key metadata.\n * @typedef {{name: string, persistent: !fireauth.authStorage.Persistence}}\n */\nfireauth.authStorage.Key;\n\n\n/**\n * Storage manager.\n * @param {string} namespace The optional namespace.\n * @param {string} separator The optional separator.\n * @param {boolean} safariLocalStorageNotSynced Whether browser has Safari\n * iframe restriction with storage event triggering but storage not updated.\n * @param {boolean} runsInBackground Whether browser can detect storage event\n * when it had already been pushed to the background. This may happen in\n * some mobile browsers. A localStorage change in the foreground window\n * will not be detected in the background window via the storage event.\n * This was detected in iOS 7.x mobile browsers.\n * @param {boolean} webStorageSupported Whether browser web storage is\n * supported.\n * @constructor @struct @final\n */\nfireauth.authStorage.Manager = function(\n namespace,\n separator,\n safariLocalStorageNotSynced,\n runsInBackground,\n webStorageSupported) {\n /** @const @private {string} Storage namespace. */\n this.namespace_ = namespace;\n /** @const @private {string} Storage namespace key separator. */\n this.separator_ = separator;\n /**\n * @const @private {boolean} Whether browser has Safari iframe restriction\n * with storage event triggering but storage not updated.\n */\n this.safariLocalStorageNotSynced_ = safariLocalStorageNotSynced;\n /**\n * @private {boolean} Whether browser can detect storage event when it\n * had already been pushed to the background. This may happen in some\n * mobile browsers.\n */\n this.runsInBackground_ = runsInBackground;\n /** @const @private {boolean} Whether browser web storage is supported. */\n this.webStorageSupported_ = webStorageSupported;\n\n /**\n * @const @private {!Object.<string, !Array<function()>>} The storage event\n * key to listeners map.\n */\n this.listeners_ = {};\n\n var storageFactory = fireauth.storage.Factory.getInstance();\n try {\n /**\n * @private {!fireauth.storage.Storage} Persistence storage.\n */\n this.persistentStorage_ = storageFactory.makePersistentStorage();\n } catch (e) {\n // Default to in memory storage if the preferred persistent storage is not\n // supported.\n this.persistentStorage_ = storageFactory.makeInMemoryStorage();\n // Do not use indexedDB fallback.\n this.localStorageNotSynchronized_ = false;\n // Do not set polling functions on window.localStorage.\n this.runsInBackground_ = true;\n }\n try {\n /**\n * @private {!fireauth.storage.Storage} Temporary session storage.\n */\n this.temporaryStorage_ = storageFactory.makeTemporaryStorage();\n } catch (e) {\n // Default to in memory storage if the preferred temporary storage is not\n // supported. This should be a different in memory instance as the\n // persistent storage, since the same key could be available for both types\n // of storage.\n this.temporaryStorage_ = storageFactory.makeInMemoryStorage();\n }\n /**\n * @private {!fireauth.storage.Storage} In memory storage.\n */\n this.inMemoryStorage_ = storageFactory.makeInMemoryStorage();\n\n /**\n * @const @private {function(!goog.events.BrowserEvent)|\n * function(!Array<string>)} Storage change handler.\n */\n this.storageChangeEventHandler_ = goog.bind(this.storageChangeEvent_, this);\n /** @private {!Object.<string, *>} Local map for localStorage. */\n this.localMap_ = {};\n};\n\n\n/**\n * @return {!fireauth.authStorage.Manager} The default Auth storage manager\n * instance.\n */\nfireauth.authStorage.Manager.getInstance = function() {\n // Creates the default instance for Auth storage maanger.\n if (!fireauth.authStorage.Manager.instance_) {\n /**\n * @private {?fireauth.authStorage.Manager} The default storage manager\n * instance.\n */\n fireauth.authStorage.Manager.instance_ = new fireauth.authStorage.Manager(\n fireauth.authStorage.NAMESPACE_,\n fireauth.authStorage.SEPARATOR_,\n fireauth.util.isSafariLocalStorageNotSynced(),\n fireauth.util.runsInBackground(),\n fireauth.util.isWebStorageSupported());\n }\n return fireauth.authStorage.Manager.instance_;\n};\n\n\n/** Clears storage manager instances. This is used for testing. */\nfireauth.authStorage.Manager.clear = function() {\n fireauth.authStorage.Manager.instance_ = null;\n};\n\n\n/**\n * Returns the storage corresponding to the specified persistence.\n * @param {!fireauth.authStorage.Persistence} persistent The type of storage\n * persistence.\n * @return {!fireauth.storage.Storage} The corresponding storage instance.\n * @private\n */\nfireauth.authStorage.Manager.prototype.getStorage_ = function(persistent) {\n switch (persistent) {\n case fireauth.authStorage.Persistence.SESSION:\n return this.temporaryStorage_;\n case fireauth.authStorage.Persistence.NONE:\n return this.inMemoryStorage_;\n case fireauth.authStorage.Persistence.LOCAL:\n default:\n return this.persistentStorage_;\n }\n};\n\n\n/**\n * Constructs the corresponding storage key name.\n * @param {fireauth.authStorage.Key} dataKey The key under which the value is\n * stored.\n * @param {?string=} opt_id This ID associates storage values with specific\n * apps.\n * @return {string} The corresponding key name with namespace prefixed.\n * @private\n */\nfireauth.authStorage.Manager.prototype.getKeyName_ = function(dataKey, opt_id) {\n return this.namespace_ + this.separator_ + dataKey.name +\n (opt_id ? this.separator_ + opt_id : '');\n};\n\n\n/**\n * Migrates window.localStorage to the provided persistent storage.\n * @param {fireauth.authStorage.Key} dataKey The key under which the persistent\n * value is supposed to be stored.\n * @param {?string=} opt_id When operating in multiple app mode, this ID\n * associates storage values with specific apps.\n * @return {!goog.Promise<void>} A promise that resolves when the data stored\n * in window.localStorage is migrated to the provided persistent storage\n * identified by the provided data key.\n */\nfireauth.authStorage.Manager.prototype.migrateFromLocalStorage =\n function(dataKey, opt_id) {\n var self = this;\n var key = this.getKeyName_(dataKey, opt_id);\n var storage = this.getStorage_(dataKey.persistent);\n // Get data stored in the default persistent storage identified by dataKey.\n return this.get(dataKey, opt_id).then(function(response) {\n // Get the stored value in window.localStorage if available.\n var oldStorageValue = null;\n try {\n oldStorageValue = fireauth.util.parseJSON(\n goog.global['localStorage']['getItem'](key));\n } catch (e) {\n // Set value as null. This will resolve the promise immediately.\n }\n // If data is stored in window.localStorage but no data is available in\n // default persistent storage, migrate data from window.localStorage to\n // default persistent storage.\n if (oldStorageValue && !response) {\n // This condition may fail in situations where a user opens a tab with\n // an old version while using a tab with a new version, or when a\n // developer switches back and forth between and old and new version of\n // the library.\n goog.global['localStorage']['removeItem'](key);\n // Migrate the value to new default persistent storage.\n return self.set(dataKey, oldStorageValue, opt_id);\n } else if (oldStorageValue &&\n response &&\n storage.type != fireauth.storage.Storage.Type.LOCAL_STORAGE) {\n // Data stored in both localStorage and new persistent storage (eg.\n // indexedDB) for some reason.\n // This could happen if the developer is migrating back and forth.\n // The new default persistent storage (eg. indexedDB) takes precedence.\n goog.global['localStorage']['removeItem'](key);\n }\n });\n};\n\n\n/**\n * Gets the stored value from the corresponding storage.\n * @param {fireauth.authStorage.Key} dataKey The key under which the value is\n * stored.\n * @param {?string=} opt_id When operating in multiple app mode, this ID\n * associates storage values with specific apps.\n * @return {!goog.Promise} A Promise that resolves with the stored value.\n */\nfireauth.authStorage.Manager.prototype.get = function(dataKey, opt_id) {\n var keyName = this.getKeyName_(dataKey, opt_id);\n return this.getStorage_(dataKey.persistent).get(keyName);\n};\n\n\n/**\n * Removes the stored value from the corresponding storage.\n * @param {fireauth.authStorage.Key} dataKey The key under which the value is\n * stored.\n * @param {?string=} opt_id When operating in multiple app mode, this ID\n * associates storage values with specific apps.\n * @return {!goog.Promise<void>} A Promise that resolves when the operation is\n * completed.\n */\nfireauth.authStorage.Manager.prototype.remove = function(dataKey, opt_id) {\n var keyName = this.getKeyName_(dataKey, opt_id);\n // Keep local map up to date for requested key if persistent storage is used.\n if (dataKey.persistent == fireauth.authStorage.Persistence.LOCAL) {\n this.localMap_[keyName] = null;\n }\n return this.getStorage_(dataKey.persistent).remove(keyName);\n};\n\n\n/**\n * Stores the value in the corresponding storage.\n * @param {fireauth.authStorage.Key} dataKey The key under which the value is\n * stored.\n * @param {*} value The value to be stored.\n * @param {?string=} opt_id When operating in multiple app mode, this ID\n * associates storage values with specific apps.\n * @return {!goog.Promise<void>} A Promise that resolves when the operation is\n * completed.\n */\nfireauth.authStorage.Manager.prototype.set = function(dataKey, value, opt_id) {\n var keyName = this.getKeyName_(dataKey, opt_id);\n var self = this;\n var storage = this.getStorage_(dataKey.persistent);\n return storage.set(keyName, value)\n .then(function() {\n return storage.get(keyName);\n })\n .then(function(serializedValue) {\n // Keep local map up to date for requested key if persistent storage is\n // used.\n if (dataKey.persistent == fireauth.authStorage.Persistence.LOCAL) {\n self.localMap_[keyName] = serializedValue;\n }\n });\n};\n\n\n/**\n * @param {fireauth.authStorage.Key} dataKey The key under which the value is\n * stored.\n * @param {?string} id When operating in multiple app mode, this ID associates\n * storage values with specific apps.\n * @param {function()} listener The callback listener to run on storage event\n * related to key.\n */\nfireauth.authStorage.Manager.prototype.addListener =\n function(dataKey, id, listener) {\n var key = this.getKeyName_(dataKey, id);\n // Initialize local map for current key if web storage is supported.\n if (this.webStorageSupported_) {\n this.localMap_[key] = goog.global['localStorage']['getItem'](key);\n }\n if (goog.object.isEmpty(this.listeners_)) {\n // Start listeners.\n this.startListeners_();\n }\n if (!this.listeners_[key]) {\n this.listeners_[key] = [];\n }\n this.listeners_[key].push(listener);\n};\n\n\n/**\n * @param {fireauth.authStorage.Key} dataKey The key under which the value is\n * stored.\n * @param {?string} id When operating in multiple app mode, this ID associates\n * storage values with specific apps.\n * @param {function()} listener The listener to remove.\n */\nfireauth.authStorage.Manager.prototype.removeListener =\n function(dataKey, id, listener) {\n var key = this.getKeyName_(dataKey, id);\n if (this.listeners_[key]) {\n goog.array.removeAllIf(\n this.listeners_[key],\n function(ele) {\n return ele == listener;\n });\n if (this.listeners_[key].length == 0) {\n delete this.listeners_[key];\n }\n }\n if (goog.object.isEmpty(this.listeners_)) {\n // Stop listeners.\n this.stopListeners_();\n }\n};\n\n\n/**\n * The delay to wait between continuous checks of localStorage on browsers where\n * tabs do not run in the background. After each interval wait, we check for\n * external changes in localStorage that were not detected in the current tab.\n * @const {number}\n * @private\n */\nfireauth.authStorage.Manager.LOCAL_STORAGE_POLLING_TIMER_ = 1000;\n\n\n/**\n * Starts all storage event listeners.\n * @private\n */\nfireauth.authStorage.Manager.prototype.startListeners_ = function() {\n this.getStorage_(fireauth.authStorage.Persistence.LOCAL)\n .addStorageListener(this.storageChangeEventHandler_);\n // TODO: refactor this implementation to be handled by the underlying\n // storage mechanism.\n if (!this.runsInBackground_ &&\n // Add an exception for browsers that persist storage with indexedDB, we\n // should stick with indexedDB listener implementation in that case.\n !fireauth.util.persistsStorageWithIndexedDB() &&\n // Confirm browser web storage is supported as polling relies on it.\n this.webStorageSupported_) {\n this.startManualListeners_();\n }\n};\n\n/**\n * Starts manual polling function to detect storage event changes.\n * @private\n */\nfireauth.authStorage.Manager.prototype.startManualListeners_ = function() {\n var self = this;\n this.stopManualListeners_();\n /** @private {?number} The interval timer for manual storage checking. */\n this.manualListenerTimer_ = setInterval(function() {\n // Check all keys with listeners on them.\n for (var key in self.listeners_) {\n // Get value from localStorage.\n var currentValue = goog.global['localStorage']['getItem'](key);\n var oldValue = self.localMap_[key];\n // If local map value does not match, trigger listener with storage event.\n if (currentValue != oldValue) {\n self.localMap_[key] = currentValue;\n var event = new goog.events.BrowserEvent(/** @type {!Event} */ ({\n type: 'storage',\n key: key,\n target: window,\n oldValue: oldValue,\n newValue: currentValue,\n // Differentiate this simulated event from the real storage event.\n poll: true\n }));\n self.storageChangeEvent_(event);\n }\n }\n }, fireauth.authStorage.Manager.LOCAL_STORAGE_POLLING_TIMER_);\n};\n\n\n/**\n * Stops manual polling function to detect storage event changes.\n * @private\n */\nfireauth.authStorage.Manager.prototype.stopManualListeners_ = function() {\n if (this.manualListenerTimer_) {\n clearInterval(this.manualListenerTimer_);\n this.manualListenerTimer_ = null;\n }\n};\n\n\n/**\n * Stops all storage event listeners.\n * @private\n */\nfireauth.authStorage.Manager.prototype.stopListeners_ = function() {\n this.getStorage_(fireauth.authStorage.Persistence.LOCAL)\n .removeStorageListener(this.storageChangeEventHandler_);\n this.stopManualListeners_();\n};\n\n\n/**\n * @param {!goog.events.BrowserEvent|!Array<string>} data The storage event\n * triggered or the array of keys modified.\n * @private\n */\nfireauth.authStorage.Manager.prototype.storageChangeEvent_ = function(data) {\n if (data && data.getBrowserEvent) {\n var event = /** @type {!goog.events.BrowserEvent} */ (data);\n var key = event.getBrowserEvent().key;\n // Key would be null in some situations, like when localStorage is cleared\n // from the browser developer tools.\n if (key == null) {\n // For all keys of interest.\n for (var keyName in this.listeners_) {\n // Check if something changed in this key's real value.\n var storedValue = this.localMap_[keyName];\n // localStorage returns null when a field is not found.\n if (typeof storedValue === 'undefined') {\n storedValue = null;\n }\n var realValue = goog.global['localStorage']['getItem'](keyName);\n if (realValue !== storedValue) {\n // Update local map with real value.\n this.localMap_[keyName] = realValue;\n // Trigger that key's listener.\n this.callListeners_(keyName);\n }\n }\n return;\n }\n // Check if the key is Firebase Auth related, otherwise ignore.\n if (key.indexOf(this.namespace_ + this.separator_) != 0 ||\n // Ignore keys that have no listeners.\n !this.listeners_[key]) {\n return;\n }\n // Check the mechanism how this event was detected.\n // The first event will dictate the mechanism to be used.\n // Do not use hasOwnProperty('poll') as poll gets obfuscated.\n if (typeof event.getBrowserEvent().poll !== 'undefined') {\n // Environment detects storage changes via polling.\n // Remove storage event listener to prevent possible event duplication.\n this.getStorage_(fireauth.authStorage.Persistence.LOCAL)\n .removeStorageListener(this.storageChangeEventHandler_);\n } else {\n // Environment detects storage changes via storage event listener.\n // Remove polling listener to prevent possible event duplication.\n this.stopManualListeners_();\n }\n // Safari embedded iframe. Storage event will trigger with the delta changes\n // but no changes will be applied to the iframe localStorage.\n if (this.safariLocalStorageNotSynced_) {\n // Get current iframe page value, old value and new value.\n var currentValue = goog.global['localStorage']['getItem'](key);\n var newValue = event.getBrowserEvent().newValue;\n // Value not synchronized, synchronize manually.\n if (newValue !== currentValue) {\n if (newValue !== null) {\n // Value changed from current value.\n goog.global['localStorage']['setItem'](key, newValue);\n } else {\n // Current value deleted.\n goog.global['localStorage']['removeItem'](key);\n }\n } else {\n // Already detected and processed, do not trigger listeners again.\n if (this.localMap_[key] === newValue &&\n // Real storage event.\n typeof event.getBrowserEvent().poll === 'undefined') {\n return;\n }\n }\n }\n var self = this;\n var triggerListeners = function() {\n // Keep local map up to date in case storage event is triggered before\n // poll.\n if (typeof event.getBrowserEvent().poll === 'undefined' &&\n self.localMap_[key] === goog.global['localStorage']['getItem'](key)) {\n // Real storage event which has already been detected, do nothing.\n // This seems to trigger in some IE browsers for some reason.\n return;\n }\n self.localMap_[key] = goog.global['localStorage']['getItem'](key);\n self.callListeners_(key);\n };\n if (fireauth.util.isIe10() &&\n goog.global['localStorage']['getItem'](key) !==\n event.getBrowserEvent().newValue &&\n event.getBrowserEvent().newValue !== event.getBrowserEvent().oldValue) {\n // IE 10 has this weird bug where a storage event would trigger with the\n // correct key, oldValue and newValue but localStorage.getItem(key) does\n // not yield the updated value until a few milliseconds. This ensures this\n // recovers from that situation.\n setTimeout(\n triggerListeners, fireauth.authStorage.IE10_LOCAL_STORAGE_SYNC_DELAY);\n } else {\n triggerListeners();\n }\n } else {\n var keys = /** @type {!Array<string>} */ (data);\n goog.array.forEach(keys, goog.bind(this.callListeners_, this));\n }\n};\n\n\n/**\n * Calls all listeners for specified storage event key.\n * @param {string} key The storage event key whose listeners are to be run.\n * @private\n */\nfireauth.authStorage.Manager.prototype.callListeners_ = function(key) {\n if (this.listeners_[key]) {\n goog.array.forEach(\n this.listeners_[key],\n function(listener) {\n listener();\n });\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.storage.AuthEventManager class used by\n * the iframe to retrieve and delete Auth events triggered through an OAuth\n * flow.\n */\n\ngoog.provide('fireauth.storage.AuthEventManager');\ngoog.provide('fireauth.storage.AuthEventManager.Keys');\n\ngoog.require('fireauth.AuthEvent');\ngoog.require('fireauth.authStorage');\n\n\n/**\n * Defines the Auth event storage manager. It provides methods to\n * load and delete Auth events as well as listen to external OAuth changes on\n * them.\n * @param {string} appId The Auth event's application ID.\n * @param {?fireauth.authStorage.Manager=} opt_manager The underlying storage\n * manager to use. If none is provided, the default global instance is used.\n * @constructor @struct @final\n */\nfireauth.storage.AuthEventManager = function(appId, opt_manager) {\n /** @const @private{string} appId The Auth event's application ID. */\n this.appId_ = appId;\n /**\n * @const @private{!fireauth.authStorage.Manager} The underlying storage\n * manager.\n */\n this.manager_ = opt_manager || fireauth.authStorage.Manager.getInstance();\n};\n\n\n/**\n * Valid keys for Auth event manager data.\n * @enum {!fireauth.authStorage.Key}\n */\nfireauth.storage.AuthEventManager.Keys = {\n AUTH_EVENT: {\n name: 'authEvent',\n persistent: fireauth.authStorage.Persistence.LOCAL\n },\n REDIRECT_EVENT: {\n name: 'redirectEvent',\n persistent: fireauth.authStorage.Persistence.SESSION\n }\n};\n\n\n/**\n * @return {!goog.Promise<?fireauth.AuthEvent>} A promise that resolves on\n * success with the stored Auth event.\n */\nfireauth.storage.AuthEventManager.prototype.getAuthEvent = function() {\n return this.manager_.get(\n fireauth.storage.AuthEventManager.Keys.AUTH_EVENT, this.appId_)\n .then(function(response) {\n return fireauth.AuthEvent.fromPlainObject(response);\n });\n};\n\n\n/**\n * Removes the identifier's Auth event if it exists.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.AuthEventManager.prototype.removeAuthEvent = function() {\n return this.manager_.remove(\n fireauth.storage.AuthEventManager.Keys.AUTH_EVENT, this.appId_);\n};\n\n\n/**\n * Adds a listener to Auth event for App ID provided.\n * @param {!function()} listener The listener to run on Auth event.\n */\nfireauth.storage.AuthEventManager.prototype.addAuthEventListener =\n function(listener) {\n this.manager_.addListener(\n fireauth.storage.AuthEventManager.Keys.AUTH_EVENT, this.appId_, listener);\n};\n\n\n/**\n * Removes a listener to Auth event for App ID provided.\n * @param {!function()} listener The listener to run on Auth event.\n */\nfireauth.storage.AuthEventManager.prototype.removeAuthEventListener =\n function(listener) {\n this.manager_.removeListener(\n fireauth.storage.AuthEventManager.Keys.AUTH_EVENT, this.appId_, listener);\n};\n\n\n/**\n * @return {!goog.Promise<?fireauth.AuthEvent>} A promise that resolves on\n * success with the stored redirect Auth event.\n */\nfireauth.storage.AuthEventManager.prototype.getRedirectEvent =\n function() {\n return this.manager_.get(\n fireauth.storage.AuthEventManager.Keys.REDIRECT_EVENT,\n this.appId_).then(function(response) {\n return fireauth.AuthEvent.fromPlainObject(response);\n });\n};\n\n\n/**\n * Removes the identifier's redirect Auth event if it exists.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.AuthEventManager.prototype.removeRedirectEvent = function() {\n return this.manager_.remove(\n fireauth.storage.AuthEventManager.Keys.REDIRECT_EVENT, this.appId_);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Base class for SHA-2 cryptographic hash.\n *\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 * Some code similar to SHA1 are borrowed from sha1.js written by mschilder@.\n */\n\ngoog.provide('goog.crypt.Sha2');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.crypt.Hash');\n\n\n\n/**\n * SHA-2 cryptographic hash constructor.\n * This constructor should not be used directly to create the object. Rather,\n * one should use the constructor of the sub-classes.\n * @param {number} numHashBlocks The size of output in 16-byte blocks.\n * @param {!Array<number>} initHashBlocks The hash-specific initialization\n * @constructor\n * @extends {goog.crypt.Hash}\n * @struct\n */\ngoog.crypt.Sha2 = function(numHashBlocks, initHashBlocks) {\n goog.crypt.Sha2.base(this, 'constructor');\n\n this.blockSize = goog.crypt.Sha2.BLOCKSIZE_;\n\n /**\n * A chunk holding the currently processed message bytes. Once the chunk has\n * 64 bytes, we feed it into computeChunk_ function and reset this.chunk_.\n * @private {!Array<number>|!Uint8Array}\n */\n this.chunk_ = goog.global['Uint8Array'] ? new Uint8Array(this.blockSize) :\n new Array(this.blockSize);\n\n /**\n * Current number of bytes in this.chunk_.\n * @private {number}\n */\n this.inChunk_ = 0;\n\n /**\n * Total number of bytes in currently processed message.\n * @private {number}\n */\n this.total_ = 0;\n\n\n /**\n * Holds the previous values of accumulated hash a-h in the computeChunk_\n * function.\n * @private {!Array<number>|!Int32Array}\n */\n this.hash_ = [];\n\n /**\n * The number of output hash blocks (each block is 4 bytes long).\n * @private {number}\n */\n this.numHashBlocks_ = numHashBlocks;\n\n /**\n * @private {!Array<number>} initHashBlocks\n */\n this.initHashBlocks_ = initHashBlocks;\n\n /**\n * Temporary array used in chunk computation. Allocate here as a\n * member rather than as a local within computeChunk_() as a\n * performance optimization to reduce the number of allocations and\n * reduce garbage collection.\n * @private {!Int32Array|!Array<number>}\n */\n this.w_ = goog.global['Int32Array'] ? new Int32Array(64) : new Array(64);\n\n if (goog.crypt.Sha2.Kx_ === undefined) {\n // This is the first time this constructor has been called.\n if (goog.global['Int32Array']) {\n // Typed arrays exist\n goog.crypt.Sha2.Kx_ = new Int32Array(goog.crypt.Sha2.K_);\n } else {\n // Typed arrays do not exist\n goog.crypt.Sha2.Kx_ = goog.crypt.Sha2.K_;\n }\n }\n\n this.reset();\n};\ngoog.inherits(goog.crypt.Sha2, goog.crypt.Hash);\n\n\n/**\n * The block size\n * @private {number}\n */\ngoog.crypt.Sha2.BLOCKSIZE_ = 512 / 8;\n\n\n/**\n * Contains data needed to pad messages less than BLOCK_SIZE_ bytes.\n * @private {!Array<number>}\n */\ngoog.crypt.Sha2.PADDING_ = goog.array.concat(\n 128, goog.array.repeat(0, goog.crypt.Sha2.BLOCKSIZE_ - 1));\n\n\n/** @override */\ngoog.crypt.Sha2.prototype.reset = function() {\n this.inChunk_ = 0;\n this.total_ = 0;\n this.hash_ = goog.global['Int32Array'] ?\n new Int32Array(this.initHashBlocks_) :\n goog.array.clone(this.initHashBlocks_);\n};\n\n\n/**\n * Helper function to compute the hashes for a given 512-bit message chunk.\n * @private\n */\ngoog.crypt.Sha2.prototype.computeChunk_ = function() {\n var chunk = this.chunk_;\n goog.asserts.assert(chunk.length == this.blockSize);\n var rounds = 64;\n\n // Divide the chunk into 16 32-bit-words.\n var w = this.w_;\n var index = 0;\n var offset = 0;\n while (offset < chunk.length) {\n w[index++] = (chunk[offset] << 24) | (chunk[offset + 1] << 16) |\n (chunk[offset + 2] << 8) | (chunk[offset + 3]);\n offset = index * 4;\n }\n\n // Extend the w[] array to be the number of rounds.\n for (var i = 16; i < rounds; i++) {\n var w_15 = w[i - 15] | 0;\n var s0 = ((w_15 >>> 7) | (w_15 << 25)) ^ ((w_15 >>> 18) | (w_15 << 14)) ^\n (w_15 >>> 3);\n var w_2 = w[i - 2] | 0;\n var s1 = ((w_2 >>> 17) | (w_2 << 15)) ^ ((w_2 >>> 19) | (w_2 << 13)) ^\n (w_2 >>> 10);\n\n // As a performance optimization, construct the sum a pair at a time\n // with casting to integer (bitwise OR) to eliminate unnecessary\n // double<->integer conversions.\n var partialSum1 = ((w[i - 16] | 0) + s0) | 0;\n var partialSum2 = ((w[i - 7] | 0) + s1) | 0;\n w[i] = (partialSum1 + partialSum2) | 0;\n }\n\n var a = this.hash_[0] | 0;\n var b = this.hash_[1] | 0;\n var c = this.hash_[2] | 0;\n var d = this.hash_[3] | 0;\n var e = this.hash_[4] | 0;\n var f = this.hash_[5] | 0;\n var g = this.hash_[6] | 0;\n var h = this.hash_[7] | 0;\n for (var i = 0; i < rounds; i++) {\n var S0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^\n ((a >>> 22) | (a << 10));\n var maj = ((a & b) ^ (a & c) ^ (b & c));\n var t2 = (S0 + maj) | 0;\n var S1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^\n ((e >>> 25) | (e << 7));\n var ch = ((e & f) ^ ((~e) & g));\n\n // As a performance optimization, construct the sum a pair at a time\n // with casting to integer (bitwise OR) to eliminate unnecessary\n // double<->integer conversions.\n var partialSum1 = (h + S1) | 0;\n var partialSum2 = (ch + (goog.crypt.Sha2.Kx_[i] | 0)) | 0;\n var partialSum3 = (partialSum2 + (w[i] | 0)) | 0;\n var t1 = (partialSum1 + partialSum3) | 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + t1) | 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) | 0;\n }\n\n this.hash_[0] = (this.hash_[0] + a) | 0;\n this.hash_[1] = (this.hash_[1] + b) | 0;\n this.hash_[2] = (this.hash_[2] + c) | 0;\n this.hash_[3] = (this.hash_[3] + d) | 0;\n this.hash_[4] = (this.hash_[4] + e) | 0;\n this.hash_[5] = (this.hash_[5] + f) | 0;\n this.hash_[6] = (this.hash_[6] + g) | 0;\n this.hash_[7] = (this.hash_[7] + h) | 0;\n};\n\n\n/** @override */\ngoog.crypt.Sha2.prototype.update = function(message, opt_length) {\n if (opt_length === undefined) {\n opt_length = message.length;\n }\n // Process the message from left to right up to |opt_length| bytes.\n // When we get a 512-bit chunk, compute the hash of it and reset\n // this.chunk_. The message might not be multiple of 512 bits so we\n // might end up with a chunk that is less than 512 bits. We store\n // such partial chunk in this.chunk_ and it will be filled up later\n // in digest().\n var n = 0;\n var inChunk = this.inChunk_;\n\n // The input message could be either byte array of string.\n if (typeof message === 'string') {\n while (n < opt_length) {\n this.chunk_[inChunk++] = message.charCodeAt(n++);\n if (inChunk == this.blockSize) {\n this.computeChunk_();\n inChunk = 0;\n }\n }\n } else if (goog.isArrayLike(message)) {\n while (n < opt_length) {\n var b = message[n++];\n if (!('number' == typeof b && 0 <= b && 255 >= b && b == (b | 0))) {\n throw new Error('message must be a byte array');\n }\n this.chunk_[inChunk++] = b;\n if (inChunk == this.blockSize) {\n this.computeChunk_();\n inChunk = 0;\n }\n }\n } else {\n throw new Error('message must be string or array');\n }\n\n // Record the current bytes in chunk to support partial update.\n this.inChunk_ = inChunk;\n\n // Record total message bytes we have processed so far.\n this.total_ += opt_length;\n};\n\n\n/** @override */\ngoog.crypt.Sha2.prototype.digest = function() {\n var digest = [];\n var totalBits = this.total_ * 8;\n\n // Append pad 0x80 0x00*.\n if (this.inChunk_ < 56) {\n this.update(goog.crypt.Sha2.PADDING_, 56 - this.inChunk_);\n } else {\n this.update(\n goog.crypt.Sha2.PADDING_, this.blockSize - (this.inChunk_ - 56));\n }\n\n // Append # bits in the 64-bit big-endian format.\n for (var i = 63; i >= 56; i--) {\n this.chunk_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n this.computeChunk_();\n\n // Finally, output the result digest.\n var n = 0;\n for (var i = 0; i < this.numHashBlocks_; i++) {\n for (var j = 24; j >= 0; j -= 8) {\n digest[n++] = ((this.hash_[i] >> j) & 255);\n }\n }\n return digest;\n};\n\n\n/**\n * Constants used in SHA-2.\n * @const\n * @private {!Array<number>}\n */\ngoog.crypt.Sha2.K_ = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,\n 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,\n 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,\n 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,\n 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,\n 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,\n 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,\n 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,\n 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n];\n\n\n/**\n * Sha2.K as an Int32Array if this JS supports typed arrays; otherwise,\n * the same array as Sha2.K.\n *\n * The compiler cannot remove an Int32Array, even if it is not needed\n * (There are certain cases where creating an Int32Array is not\n * side-effect free). Instead, the first time we construct a Sha2\n * instance, we convert or assign Sha2.K as appropriate.\n * @private {undefined|!Array<number>|!Int32Array}\n */\ngoog.crypt.Sha2.Kx_;\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.storage.OAuthHandlerManager class which\n * provides utilities to the OAuth handler widget to set Auth events after an\n * IDP sign in attempt and to store state during the OAuth handshake with IDP.\n */\n\ngoog.provide('fireauth.storage.OAuthHandlerManager');\n\ngoog.require('fireauth.AuthEvent');\ngoog.require('fireauth.OAuthHelperState');\ngoog.require('fireauth.authStorage');\ngoog.require('fireauth.storage.AuthEventManager.Keys');\n\n\n/**\n * Defines the OAuth handler storage manager. It provides methods to\n * store, load and delete OAuth handler widget state, properties and setting\n * Auth events.\n * @param {?fireauth.authStorage.Manager=} opt_manager The underlying storage\n * manager to use. If none is provided, the default global instance is used.\n * @constructor @struct @final\n */\nfireauth.storage.OAuthHandlerManager = function(opt_manager) {\n /**\n * @const @private{!fireauth.authStorage.Manager} The underlying storage\n * manager.\n */\n this.manager_ = opt_manager || fireauth.authStorage.Manager.getInstance();\n};\n\n\n/**\n * Valid keys for OAuth handler manager data.\n * @private @enum {!fireauth.authStorage.Key}\n */\nfireauth.storage.OAuthHandlerManager.Keys_ = {\n OAUTH_HELPER_STATE: {\n name: 'oauthHelperState',\n persistent: fireauth.authStorage.Persistence.SESSION\n },\n SESSION_ID: {\n name: 'sessionId',\n persistent: fireauth.authStorage.Persistence.SESSION\n }\n};\n\n\n/**\n * @param {string} appId The Auth state's application ID.\n * @return {!goog.Promise<?string|undefined>} A promise that resolves on success\n * with the stored session ID.\n */\nfireauth.storage.OAuthHandlerManager.prototype.getSessionId = function(appId) {\n return this.manager_.get(\n fireauth.storage.OAuthHandlerManager.Keys_.SESSION_ID, appId);\n};\n\n\n/**\n * Removes the session ID string if it exists.\n * @param {string} appId The Auth state's application ID.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.OAuthHandlerManager.prototype.removeSessionId =\n function(appId) {\n return this.manager_.remove(\n fireauth.storage.OAuthHandlerManager.Keys_.SESSION_ID, appId);\n};\n\n\n/**\n * Stores the session ID string.\n * @param {string} appId The Auth state's application ID.\n * @param {string} sessionId The session ID string to store.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.OAuthHandlerManager.prototype.setSessionId =\n function(appId, sessionId) {\n return this.manager_.set(\n fireauth.storage.OAuthHandlerManager.Keys_.SESSION_ID, sessionId, appId);\n};\n\n\n/**\n * @return {!goog.Promise<?fireauth.OAuthHelperState>} A promise that resolves\n * on success with the stored OAuth helper state.\n */\nfireauth.storage.OAuthHandlerManager.prototype.getOAuthHelperState =\n function() {\n return this.manager_.get(\n fireauth.storage.OAuthHandlerManager.Keys_.OAUTH_HELPER_STATE)\n .then(function(response) {\n return fireauth.OAuthHelperState.fromPlainObject(response);\n });\n};\n\n\n/**\n * Removes the current OAuth helper state if it exists.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.OAuthHandlerManager.prototype.removeOAuthHelperState =\n function() {\n return this.manager_.remove(\n fireauth.storage.OAuthHandlerManager.Keys_.OAUTH_HELPER_STATE);\n};\n\n\n/**\n * Stores the current OAuth helper state.\n * @param {!fireauth.OAuthHelperState} state The OAuth helper state.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.OAuthHandlerManager.prototype.setOAuthHelperState =\n function(state) {\n return this.manager_.set(\n fireauth.storage.OAuthHandlerManager.Keys_.OAUTH_HELPER_STATE,\n state.toPlainObject());\n};\n\n\n/**\n * Stores the Auth event for specified identifier.\n * @param {string} appId The Auth state's application ID.\n * @param {!fireauth.AuthEvent} authEvent The Auth event.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.OAuthHandlerManager.prototype.setAuthEvent =\n function(appId, authEvent) {\n return this.manager_.set(\n fireauth.storage.AuthEventManager.Keys.AUTH_EVENT,\n authEvent.toPlainObject(),\n appId);\n};\n\n\n/**\n * Stores the redirect Auth event for specified identifier.\n * @param {string} appId The Auth state's application ID.\n * @param {!fireauth.AuthEvent} authEvent The redirect Auth event.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.OAuthHandlerManager.prototype.setRedirectEvent =\n function(appId, authEvent) {\n return this.manager_.set(\n fireauth.storage.AuthEventManager.Keys.REDIRECT_EVENT,\n authEvent.toPlainObject(),\n appId);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Abstract cryptographic hash interface.\n *\n * See goog.crypt.Sha1 and goog.crypt.Md5 for sample implementations.\n */\n\ngoog.provide('goog.crypt.Hash');\n\n\n\n/**\n * Create a cryptographic hash instance.\n *\n * @constructor\n * @struct\n */\ngoog.crypt.Hash = function() {\n /**\n * The block size for the hasher.\n * @type {number}\n */\n this.blockSize = -1;\n};\n\n\n/**\n * Resets the internal accumulator.\n */\ngoog.crypt.Hash.prototype.reset = goog.abstractMethod;\n\n\n/**\n * Adds a byte array (array with values in [0-255] range) or a string (must\n * only contain 8-bit, i.e., Latin1 characters) to the internal accumulator.\n *\n * Many hash functions operate on blocks of data and implement optimizations\n * when a full chunk of data is readily available. Hence it is often preferable\n * to provide large chunks of data (a kilobyte or more) than to repeatedly\n * call the update method with few tens of bytes. If this is not possible, or\n * not feasible, it might be good to provide data in multiplies of hash block\n * size (often 64 bytes). Please see the implementation and performance tests\n * of your favourite hash.\n *\n * @param {Array<number>|Uint8Array|string} bytes Data used for the update.\n * @param {number=} opt_length Number of bytes to use.\n */\ngoog.crypt.Hash.prototype.update = goog.abstractMethod;\n\n\n/**\n * @return {!Array<number>} The finalized hash computed\n * from the internal accumulator.\n */\ngoog.crypt.Hash.prototype.digest = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview SHA-256 cryptographic hash.\n *\n * Usage:\n * var sha256 = new goog.crypt.Sha256();\n * sha256.update(bytes);\n * var hash = sha256.digest();\n */\n\ngoog.provide('goog.crypt.Sha256');\n\ngoog.require('goog.crypt.Sha2');\n\n\n\n/**\n * SHA-256 cryptographic hash constructor.\n *\n * @constructor\n * @extends {goog.crypt.Sha2}\n * @final\n * @struct\n */\ngoog.crypt.Sha256 = function() {\n goog.crypt.Sha256.base(\n this, 'constructor', 8, goog.crypt.Sha256.INIT_HASH_BLOCK_);\n};\ngoog.inherits(goog.crypt.Sha256, goog.crypt.Sha2);\n\n\n/** @private {!Array<number>} */\ngoog.crypt.Sha256.INIT_HASH_BLOCK_ = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c,\n 0x1f83d9ab, 0x5be0cd19\n];\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Cordova utility and helper functions.\n * The following plugins must be installed:\n * cordova plugin add cordova-plugin-buildinfo\n * cordova plugin add cordova-universal-links-plugin-fix\n * cordova plugin add cordova-plugin-browsertab\n * cordova plugin add cordova-plugin-inappbrowser\n * iOS custom scheme support:\n * cordova plugin add cordova-plugin-customurlscheme --variable \\\n * URL_SCHEME=com.firebase.example\n * Console logging in iOS:\n * cordova plugin add cordova-plugin-console\n */\n\ngoog.provide('fireauth.CordovaHandler');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthEvent');\ngoog.require('fireauth.AuthProvider');\ngoog.require('fireauth.DynamicLink');\ngoog.require('fireauth.OAuthSignInHandler');\ngoog.require('fireauth.UniversalLinkSubscriber');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.iframeclient.IfcHandler');\ngoog.require('fireauth.storage.AuthEventManager');\ngoog.require('fireauth.storage.OAuthHandlerManager');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.Timer');\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.crypt');\ngoog.require('goog.crypt.Sha256');\n\n\n/**\n * Cordova environment utility and helper functions.\n * @param {string} authDomain The application authDomain.\n * @param {string} apiKey The API key.\n * @param {string} appName The App name.\n * @param {?string=} opt_clientVersion The optional client version string.\n * @param {number=} opt_initialTimeout Initial Auth event timeout.\n * @param {number=} opt_redirectTimeout Redirect result timeout.\n * @param {?string=} opt_endpointId The endpoint ID (staging, test Gaia, etc).\n * @constructor\n * @implements {fireauth.OAuthSignInHandler}\n */\nfireauth.CordovaHandler = function(authDomain, apiKey, appName,\n opt_clientVersion, opt_initialTimeout, opt_redirectTimeout,\n opt_endpointId) {\n /** @private {string} The application authDomain. */\n this.authDomain_ = authDomain;\n /** @private {string} The application API key. */\n this.apiKey_ = apiKey;\n /** @private {string} The application name. */\n this.appName_ = appName;\n /** @private {?string} The client version */\n this.clientVersion_ = opt_clientVersion || null;\n /** @private {?string} The Auth endpoint ID. */\n this.endpointId_ = opt_endpointId || null;\n /** @private {string} The storage key. */\n this.storageKey_ = fireauth.util.createStorageKey(apiKey, appName);\n /**\n * @private {!fireauth.storage.OAuthHandlerManager} The OAuth handler\n * storage manager reference, used to save a partial Auth event when\n * redirect operation is triggered.\n */\n this.savePartialEventManager_ = new fireauth.storage.OAuthHandlerManager();\n /**\n * @private {!fireauth.storage.AuthEventManager} The Auth event storage\n * manager reference. This is used to get back the saved partial Auth\n * event and then delete on successful handling.\n */\n this.getAndDeletePartialEventManager_ =\n new fireauth.storage.AuthEventManager(this.storageKey_);\n /**\n * @private {?goog.Promise<!fireauth.AuthEvent>} A promise that resolves with\n * the OAuth redirect URL response.\n */\n this.initialAuthEvent_ = null;\n /**\n * @private {!Array<!function(?fireauth.AuthEvent)>} The Auth event\n * listeners.\n */\n this.authEventListeners_ = [];\n /** @private {number} The initial Auth event timeout. */\n this.initialTimeout_ = opt_initialTimeout ||\n fireauth.CordovaHandler.INITIAL_TIMEOUT_MS_;\n /** @private {number} The return to app after redirect timeout. */\n this.redirectTimeout_ = opt_redirectTimeout ||\n fireauth.CordovaHandler.REDIRECT_TIMEOUT_MS_;\n /**\n * @private {?goog.Promise} The last pending redirect promise. This is null if\n * already completed.\n */\n this.pendingRedirect_ = null;\n /**\n * @private {?Object} The inAppBrowser reference window if available. This is\n * relevant to iOS 7 and 8 embedded webviews.\n */\n this.inAppBrowserRef_ = null;\n};\n\n\n/**\n * The total number of chars used to generate the session ID string.\n * @const {number}\n * @private\n */\nfireauth.CordovaHandler.SESSION_ID_TOTAL_CHARS_ = 20;\n\n\n/**\n * The default initial Auth event timeout in ms.\n * @const {number}\n * @private\n */\nfireauth.CordovaHandler.INITIAL_TIMEOUT_MS_ = 500;\n\n\n/**\n * The default timeout in milliseconds for a pending redirect operation after\n * returning to the app.\n * @const {number}\n * @private\n */\nfireauth.CordovaHandler.REDIRECT_TIMEOUT_MS_ = 2000;\n\n\n/**\n * Constructs a Cordova configuration error message.\n * @param {?string=} opt_message The optional error message to be used. This\n * will override the existing default one.\n * @return {!fireauth.AuthError} The Cordova invalid configuration error with\n * the custom message provided. If no message is provided, the default\n * message is used.\n * @private\n */\nfireauth.CordovaHandler.getError_ = function(opt_message) {\n return new fireauth.AuthError(\n fireauth.authenum.Error.INVALID_CORDOVA_CONFIGURATION,\n opt_message);\n};\n\n\n/**\n * Initializes the Cordova environment and waits for it to be ready.\n * @return {!goog.Promise} A promise that resolves if the current environment is\n * a Cordova environment.\n * @override\n */\nfireauth.CordovaHandler.prototype.initializeAndWait = function() {\n if (this.isReady_) {\n return this.isReady_;\n }\n this.isReady_ = fireauth.util.checkIfCordova().then(function() {\n // Check all dependencies installed.\n // Note that cordova-universal-links-plugin has been abandoned.\n // A fork with latest fixes is available at:\n // https://www.npmjs.com/package/cordova-universal-links-plugin-fix\n var subscribe = fireauth.util.getObjectRef(\n 'universalLinks.subscribe', goog.global);\n if (typeof subscribe !== 'function') {\n throw fireauth.CordovaHandler.getError_(\n 'cordova-universal-links-plugin-fix is not installed');\n }\n // https://www.npmjs.com/package/cordova-plugin-buildinfo\n var appIdentifier =\n fireauth.util.getObjectRef('BuildInfo.packageName', goog.global);\n if (typeof appIdentifier === 'undefined') {\n throw fireauth.CordovaHandler.getError_(\n 'cordova-plugin-buildinfo is not installed');\n }\n // https://github.com/google/cordova-plugin-browsertab\n var openUrl = fireauth.util.getObjectRef(\n 'cordova.plugins.browsertab.openUrl', goog.global);\n if (typeof openUrl !== 'function') {\n throw fireauth.CordovaHandler.getError_(\n 'cordova-plugin-browsertab is not installed');\n }\n // https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/\n var openInAppBrowser = fireauth.util.getObjectRef(\n 'cordova.InAppBrowser.open', goog.global);\n if (typeof openInAppBrowser !== 'function') {\n throw fireauth.CordovaHandler.getError_(\n 'cordova-plugin-inappbrowser is not installed');\n }\n }, function(error) {\n // If not supported.\n throw new fireauth.AuthError(fireauth.authenum.Error.CORDOVA_NOT_READY);\n });\n return this.isReady_;\n};\n\n\n/**\n * Generates a session ID. Used to prevent session fixation attacks.\n * @param {number} numOfChars The number of characters to generate.\n * @return {string} The generated session ID.\n * @private\n */\nfireauth.CordovaHandler.prototype.generateSessionId_ = function(numOfChars) {\n var chars = [];\n var allowedChars =\n '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n while (numOfChars > 0) {\n var index = Math.floor(Math.random() * allowedChars.length);\n chars.push(allowedChars.charAt(index));\n numOfChars--;\n }\n return chars.join('');\n};\n\n\n/**\n * Computes the sha256 hash of a session ID.\n * @param {string} str The string to hash.\n * @return {string} The hashed string.\n * @private\n */\nfireauth.CordovaHandler.prototype.computeSecureHash_ = function(str) {\n // sha256 the sessionId. This will be passed to the OAuth backend.\n // When exchanging the Auth code with a firebase ID token, the raw session ID\n // needs to be provided.\n var sha256 = new goog.crypt.Sha256();\n sha256.update(str);\n return goog.crypt.byteArrayToHex(sha256.digest());\n};\n\n\n/**\n * Waits for popup window to close and time out if the result is unhandled.\n * This is not supported in Cordova.\n * @param {!Window} popupWin The popup window.\n * @param {!function(!fireauth.AuthError)} onError The on error callback.\n * @return {!goog.Promise}\n * @override\n */\nfireauth.CordovaHandler.prototype.startPopupTimeout =\n function(popupWin, onError, timeoutDuration) {\n // Not supported operation, check processPopup for details.\n onError(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n return goog.Promise.resolve();\n};\n\n\n/**\n * Processes the popup request. This is not supported in Cordova.\n * @param {?Window} popupWin The popup window reference.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {function()} onInitialize The function to call on initialization.\n * @param {function(*)} onError The function to call on error.\n * @param {string=} opt_eventId The optional event ID.\n * @param {boolean=} opt_alreadyRedirected Whether popup is already redirected\n * to final destination.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {!goog.Promise} The popup window promise.\n * @override\n */\nfireauth.CordovaHandler.prototype.processPopup = function(\n popupWin,\n mode,\n provider,\n onInitialize,\n onError,\n opt_eventId,\n opt_alreadyRedirected,\n opt_tenantId) {\n // Popups not supported in Cordova as the activity could be destroyed in\n // some cases. Redirect works better as getRedirectResult can be used as a\n // fallback to get the result when the activity is detroyed.\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n};\n\n\n/**\n * @return {boolean} Whether the handler will unload the current page on\n * redirect operations.\n * @override\n */\nfireauth.CordovaHandler.prototype.unloadsOnRedirect = function() {\n // Does not necessarily unload the page on redirect.\n return false;\n};\n\n\n/**\n * @return {boolean} Whether the handler should be initialized early.\n * @override\n */\nfireauth.CordovaHandler.prototype.shouldBeInitializedEarly = function() {\n // Initialize early to detect incoming link. This is not an expensive\n // operation, unlike embedding an iframe.\n return true;\n};\n\n\n/**\n * @return {boolean} Whether the sign-in handler in the current environment\n * has volatile session storage.\n * @override\n */\nfireauth.CordovaHandler.prototype.hasVolatileStorage = function() {\n // An activity can be destroyed and thereby sessionStorage wiped out.\n return true;\n};\n\n\n/**\n * Processes the OAuth redirect request. Will resolve when the OAuth response\n * is detected in the incoming link and the corresponding Auth event is\n * triggered.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {?string=} opt_eventId The optional event ID.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {!goog.Promise}\n * @override\n */\nfireauth.CordovaHandler.prototype.processRedirect = function(\n mode,\n provider,\n opt_eventId,\n opt_tenantId) {\n // If there is already a pending redirect, throw an error.\n if (this.pendingRedirect_) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.REDIRECT_OPERATION_PENDING));\n }\n var self = this;\n var doc = goog.global.document;\n // On close timer promise.\n var onClose = null;\n // Auth event detection callback;\n var authEventCallback = null;\n // On resume (return from the redirect operation).\n var onResume = null;\n // On visibility change used to detect return to app in certain versions,\n // currently iOS.\n var onVisibilityChange = null;\n // When the processRedirect promise completes, clean up any remaining\n // temporary listeners and timers.\n var cleanup = function() {\n // Remove current resume listener.\n if (onResume) {\n doc.removeEventListener('resume', onResume, false);\n }\n // Remove visibility change listener.\n if (onVisibilityChange) {\n doc.removeEventListener('visibilitychange', onVisibilityChange, false);\n }\n // Cancel onClose promise if not already cancelled.\n if (onClose) {\n onClose.cancel();\n }\n // Remove Auth event callback.\n if (authEventCallback) {\n self.removeAuthEventListener(authEventCallback);\n }\n // Clear any pending redirect now that it is completed.\n self.pendingRedirect_ = null;\n };\n // Save the pending redirect promise and clear it on completion.\n this.pendingRedirect_ = goog.Promise.resolve().then(function() {\n // Validate provider.\n // Fail fast in this case.\n fireauth.AuthProvider.checkIfOAuthSupported(provider);\n return self.getInitialAuthEvent_();\n }).then(function() {\n return self.processRedirectInternal_(\n mode, provider, opt_eventId, opt_tenantId);\n }).then(function() {\n // Wait for result (universal link) before resolving this operation.\n // This ensures that if the activity is not destroyed, we can still\n // return the result of this operation.\n return new goog.Promise(function(resolve, reject) {\n /**\n * @param {?fireauth.AuthEvent} event The Auth event detected.\n * @return {boolean}\n */\n authEventCallback = function(event) {\n // Auth event detected, resolve promise.\n // Close SFSVC if still open.\n var closeBrowsertab = fireauth.util.getObjectRef(\n 'cordova.plugins.browsertab.close', goog.global);\n resolve();\n // Close the SFSVC if it is still open (iOS 9+).\n if (typeof closeBrowsertab === 'function') {\n closeBrowsertab();\n }\n // Close inappbrowser emebedded webview in iOS7 and 8 case if still\n // open.\n if (self.inAppBrowserRef_ &&\n typeof self.inAppBrowserRef_['close'] === 'function') {\n self.inAppBrowserRef_['close']();\n // Reset reference.\n self.inAppBrowserRef_ = null;\n }\n return false;\n };\n // Wait and listen for the operation to complete (Auth event would\n // trigger).\n self.addAuthEventListener(authEventCallback);\n // On resume (return from the redirect operation).\n onResume = function() {\n // Already resumed. Do not run again.\n if (onClose) {\n return;\n }\n // Wait for some time before throwing the error that the flow was\n // cancelled by the user.\n onClose = goog.Timer.promise(self.redirectTimeout_).then(function() {\n // Throw the redirect cancelled by user error.\n reject(new fireauth.AuthError(\n fireauth.authenum.Error.REDIRECT_CANCELLED_BY_USER));\n });\n };\n onVisibilityChange = function() {\n // If app is visible, run onResume. Otherwise, ignore.\n if (fireauth.util.isAppVisible()) {\n onResume();\n }\n };\n // Listen to resume event (will trigger when the user returns to the app).\n doc.addEventListener('resume', onResume, false);\n // Listen to visibility change. This is used for iOS Cordova Safari 7+.\n // Does not work in Android stock browser versions older than 4.4.\n // We rely on resume event in Android as it works reliably in all\n // versions.\n if (!fireauth.util.isAndroid()) {\n doc.addEventListener('visibilitychange', onVisibilityChange, false);\n }\n }).thenCatch(function(error) {\n // Remove any pending partial event.\n return self.getPartialStoredEvent_().then(function() {\n throw error;\n });\n });\n }).thenAlways(cleanup);\n // Return the pending redirect promise.\n return this.pendingRedirect_;\n};\n\n/**\n * Processes the OAuth redirect request.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {?string=} opt_eventId The optional event ID.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {!goog.Promise}\n * @private\n */\nfireauth.CordovaHandler.prototype.processRedirectInternal_ = function(\n mode,\n provider,\n opt_eventId,\n opt_tenantId) {\n var self = this;\n // https://github.com/google/cordova-plugin-browsertab\n // Opens chrome custom tab in Android if chrome is installed,\n // SFSafariViewController in iOS if supported.\n // If the above are not supported, opens the system browser.\n // Opening a system browser could result in an app being rejected in the App\n // Store. The only solution here is to use an insecure embedded UIWebView.\n // This applies to older iOS versions 8 and under.\n // Generate a random session ID.\n var sessionId = this.generateSessionId_(\n fireauth.CordovaHandler.SESSION_ID_TOTAL_CHARS_);\n // Create the partial Auth event.\n var event = new fireauth.AuthEvent(\n mode,\n opt_eventId,\n null,\n sessionId,\n new fireauth.AuthError(fireauth.authenum.Error.NO_AUTH_EVENT),\n null,\n opt_tenantId);\n // Use buildinfo package to get app metadata.\n // https://www.npmjs.com/package/cordova-plugin-buildinfo\n // Get app identifier.\n var appIdentifier =\n fireauth.util.getObjectRef('BuildInfo.packageName', goog.global);\n // initializeAndWait will ensure this does not happen.\n if (typeof appIdentifier !== 'string') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INVALID_CORDOVA_CONFIGURATION);\n }\n // Get app display name.\n var appDisplayName =\n fireauth.util.getObjectRef('BuildInfo.displayName', goog.global);\n // Construct additional params to pass to OAuth handler.\n var additionalParams = {};\n // Append app identifier.\n if (fireauth.util.isIOS()) {\n // iOS app.\n additionalParams['ibi'] = appIdentifier;\n } else if (fireauth.util.isAndroid()) {\n // Android app.\n additionalParams['apn'] = appIdentifier;\n } else {\n // This should not happen as Cordova handler should not even be used in this\n // case.\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n }\n // Pass app display name.\n if (appDisplayName) {\n additionalParams['appDisplayName'] = appDisplayName;\n }\n // Hash the session ID and pass it to additional params.\n var hashedSessionId = this.computeSecureHash_(sessionId);\n // Append session ID.\n additionalParams['sessionId'] = hashedSessionId;\n // Construct OAuth handler URL.\n var oauthHelperWidgetUrl =\n fireauth.iframeclient.IfcHandler.getOAuthHelperWidgetUrl(\n this.authDomain_,\n this.apiKey_,\n this.appName_,\n mode,\n provider,\n null,\n opt_eventId,\n this.clientVersion_,\n additionalParams,\n this.endpointId_,\n opt_tenantId);\n // Make sure handler initialized and ready.\n // This should also ensure all plugins are installed.\n return this.initializeAndWait().then(function() {\n // Save partial Auth event.\n return self.savePartialEventManager_.setAuthEvent(self.storageKey_, event);\n }).then(function() {\n // initializeAndWait will ensure this plugin is installed.\n var isAvailable = /** @type {!function(!function(*))} */ (\n fireauth.util.getObjectRef(\n 'cordova.plugins.browsertab.isAvailable', goog.global));\n if (typeof isAvailable !== 'function') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INVALID_CORDOVA_CONFIGURATION);\n }\n var openUrl = null;\n // Check if browsertab is supported.\n isAvailable(function(result) {\n if (result) {\n // browsertab supported.\n openUrl = /** @type {!function(string, ...*)} */ (\n fireauth.util.getObjectRef(\n 'cordova.plugins.browsertab.openUrl', goog.global));\n if (typeof openUrl !== 'function') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INVALID_CORDOVA_CONFIGURATION);\n }\n // Open OAuth handler.\n openUrl(oauthHelperWidgetUrl);\n } else {\n // browsertab not supported, switch to inappbrowser.\n openUrl = /** @type {!function(string, string, string=)} */ (\n fireauth.util.getObjectRef(\n 'cordova.InAppBrowser.open', goog.global));\n if (typeof openUrl !== 'function') {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INVALID_CORDOVA_CONFIGURATION);\n }\n // Open in embedded webview for iOS 7 and 8 as Apple rejects apps that\n // switch context.\n // _blank opens an embedded webview.\n // _system opens the system browser.\n // _system (opens a system browser) is used as a fallback when\n // browsertab plugin is unable to open a chromecustomtab or SFSVC.\n // This has to exclude all iOS older versions where switching to a\n // browser is frowned upon by Apple and embedding a UIWebView is the\n // only option but is insecure and deprecated by Google for OAuth\n // sign-in. This will be applicable in old versions of Android.\n self.inAppBrowserRef_ = openUrl(\n oauthHelperWidgetUrl,\n fireauth.util.isIOS7Or8() ? '_blank' : '_system',\n 'location=yes');\n }\n });\n });\n};\n\n\n/**\n * Dispatches the detected Auth event to all subscribed listeners.\n * @param {!fireauth.AuthEvent} event A detected Auth event.\n * @private\n */\nfireauth.CordovaHandler.prototype.dispatchEvent_ = function(event) {\n for (var i = 0; i < this.authEventListeners_.length; i++) {\n try {\n this.authEventListeners_[i](event);\n } catch (e) {\n // If any handler fails, ignore and run next handler.\n }\n }\n};\n\n\n/**\n * Resolves the first redirect Auth event and caches it.\n * @return {!goog.Promise<!fireauth.AuthEvent>} A promise that resolves with the\n * initial Auth event response from a redirect operation. Initializes the\n * internal Auth event listener which will dispatch Auth events to all\n * subscribed listeners.\n * @private\n */\nfireauth.CordovaHandler.prototype.getInitialAuthEvent_ = function() {\n var self = this;\n if (!this.initialAuthEvent_) {\n // Cache this result so on next call, it is not triggered again.\n this.initialAuthEvent_ = this.initializeAndWait().then(function() {\n return new goog.Promise(function(resolve, reject) {\n /**\n * @param {?fireauth.AuthEvent} event The Auth event detected.\n * @return {boolean}\n */\n var authEventCallback = function(event) {\n resolve(event);\n // Remove on completion.\n self.removeAuthEventListener(authEventCallback);\n return false;\n };\n // Listen to Auth events. If resolved, resolve promise.\n self.addAuthEventListener(authEventCallback);\n // This should succeed as initializeAndWait should guarantee plugins are\n // ready.\n self.setAuthEventListener_();\n });\n });\n }\n return this.initialAuthEvent_;\n};\n\n\n/**\n * Gets and deletes the current stored partial event from storage.\n * @return {!goog.Promise<?fireauth.AuthEvent>} A promise that resolves with the\n * stored Auth event.\n * @private\n */\nfireauth.CordovaHandler.prototype.getPartialStoredEvent_ = function() {\n var event = null;\n var self = this;\n // Get any saved partial Auth event.\n return this.getAndDeletePartialEventManager_.getAuthEvent()\n .then(function(authEvent) {\n // Save partial event locally.\n event = authEvent;\n // Delete partial event.\n return self.getAndDeletePartialEventManager_.removeAuthEvent();\n }).then(function() {\n // Return the locally saved partial event.\n return event;\n });\n};\n\n\n/**\n * Extracts the Auth event pertaining to the incoming URL.\n * @param {!fireauth.AuthEvent} partialEvent The partial Auth event.\n * @param {string} url The incoming universal link.\n * @return {?fireauth.AuthEvent} The resolved Auth event corresponding to the\n * callback URL. This is null if no event is found.\n * @private\n */\nfireauth.CordovaHandler.prototype.extractAuthEventFromUrl_ =\n function(partialEvent, url) {\n // Default no redirect event result.\n var authEvent = null;\n // Parse the deep link within the dynamic link URL.\n var callbackUrl = fireauth.DynamicLink.parseDeepLink(url);\n // Confirm it is actually a callback URL.\n // Currently the universal link will be of this format:\n // https://<AUTH_DOMAIN>/__/auth/callback<OAUTH_RESPONSE>\n // This is a fake URL but is not intended to take the user anywhere\n // and just redirect to the app.\n if (callbackUrl.indexOf('/__/auth/callback') != -1) {\n // Check if there is an error in the URL.\n // This mechanism is also used to pass errors back to the app:\n // https://<AUTH_DOMAIN>/__/auth/callback?firebaseError=<STRINGIFIED_ERROR>\n var uri = goog.Uri.parse(callbackUrl);\n // Get the error object corresponding to the stringified error if found.\n var errorObject = fireauth.util.parseJSON(\n uri.getParameterValue('firebaseError') || null);\n var error = typeof errorObject === 'object' ?\n fireauth.AuthError.fromPlainObject(\n /** @type {?Object} */ (errorObject)) :\n null;\n if (error) {\n // Construct the full failed Auth event.\n authEvent = new fireauth.AuthEvent(\n partialEvent.getType(),\n partialEvent.getEventId(),\n null,\n null,\n error,\n null,\n partialEvent.getTenantId());\n } else {\n // Construct the full successful Auth event.\n authEvent = new fireauth.AuthEvent(\n partialEvent.getType(),\n partialEvent.getEventId(),\n callbackUrl,\n partialEvent.getSessionId(),\n null,\n null,\n partialEvent.getTenantId());\n }\n }\n return authEvent;\n};\n\n\n/**\n * Sets the internal Auth event listener. This listens to incoming universal\n * links and on detection, repackages them into an Auth event and then\n * dispatches the events in all event listeners.\n * @private\n */\nfireauth.CordovaHandler.prototype.setAuthEventListener_ = function() {\n // https://github.com/nordnet/cordova-universal-links-plugin-fix\n var self = this;\n // Default no redirect event result.\n var noEvent = new fireauth.AuthEvent(\n fireauth.AuthEvent.Type.UNKNOWN,\n null,\n null,\n null,\n new fireauth.AuthError(fireauth.authenum.Error.NO_AUTH_EVENT));\n var initialResolve = false;\n // On initialization, if no incoming universal link detected, trigger\n // no Auth event (no redirect operation previously called) after waiting\n // for a short period of time.\n var noEventTimer = goog.Timer.promise(this.initialTimeout_).then(function() {\n // Delete any pending unhandled event.\n return self.getPartialStoredEvent_().then(function(event) {\n // On timeout trigger noEvent if not already resolved in link\n // subscriber.\n if (!initialResolve) {\n self.dispatchEvent_(noEvent);\n }\n });\n });\n // No event name needed, subscribe to all incoming universal links.\n var universalLinkCb = function(eventData) {\n initialResolve = true;\n // Cancel no event timer.\n if (noEventTimer) {\n noEventTimer.cancel();\n }\n // Incoming link detected.\n // Check for any stored partial event.\n self.getPartialStoredEvent_().then(function(event) {\n // Initialize to an unknown event.\n var authEvent = noEvent;\n // Confirm OAuth response included.\n if (event && eventData && eventData['url']) {\n // Construct complete event. Default to unknown event if none found.\n authEvent = self.extractAuthEventFromUrl_(event, eventData['url']) ||\n noEvent;\n }\n // Dispatch Auth event.\n self.dispatchEvent_(authEvent);\n });\n };\n // iOS 7 or 8 custom URL schemes.\n // This is also the current default behavior for iOS 9+.\n // For this to work, cordova-plugin-customurlscheme needs to be installed.\n // https://github.com/EddyVerbruggen/Custom-URL-scheme\n // Do not overwrite the existing developer's URL handler.\n var existingHandlerOpenURL = goog.global['handleOpenURL'];\n goog.global['handleOpenURL'] = function(url) {\n var appIdentifier =\n fireauth.util.getObjectRef('BuildInfo.packageName', goog.global);\n // Apply case insensitive match. While bundle IDs are case sensitive,\n // when creating a new app, Apple verifies the Bundle ID using\n // case-insensitive search. So it is not possible that an app in the app\n // store try to impersonate another one by lower/upper casing characters.\n if (url.toLowerCase().indexOf(appIdentifier.toLowerCase() + '://') == 0) {\n universalLinkCb({\n 'url': url\n });\n }\n // Call the developer's handler if it is present.\n if (typeof existingHandlerOpenURL === 'function') {\n try {\n existingHandlerOpenURL(url);\n } catch(e) {\n // This doesn't swallow the error but also does not interrupt the flow.\n console.error(e);\n }\n }\n };\n fireauth.UniversalLinkSubscriber.getInstance().subscribe(universalLinkCb);\n};\n\n\n/**\n * @param {!function(?fireauth.AuthEvent):boolean} listener The Auth event\n * listener to add.\n * @override\n */\nfireauth.CordovaHandler.prototype.addAuthEventListener = function(listener) {\n // TODO: consider creating an abstract base class that OAuth handlers\n // extend with add, remove Auth event listeners and dispatcher methods.\n this.authEventListeners_.push(listener);\n // Set internal listener to Auth events. This will be ignored on subsequent\n // calls.\n this.getInitialAuthEvent_().thenCatch(function(error) {\n // Suppress this error as it should be caught through other actionable\n // public methods.\n // This would typically happen on invalid Cordova setup, when the OAuth\n // plugins are not installed. This should still trigger the Auth event\n // as developers are not forced to use OAuth sign-in in their Cordova app.\n // This is needed for onAuthStateChanged listener to trigger initially.\n if (error.code === 'auth/invalid-cordova-configuration') {\n var noEvent = new fireauth.AuthEvent(\n fireauth.AuthEvent.Type.UNKNOWN,\n null,\n null,\n null,\n new fireauth.AuthError(fireauth.authenum.Error.NO_AUTH_EVENT));\n listener(noEvent);\n }\n });\n};\n\n\n/**\n * @param {!function(?fireauth.AuthEvent):boolean} listener The Auth event\n * listener to remove.\n * @override\n */\nfireauth.CordovaHandler.prototype.removeAuthEventListener = function(listener) {\n goog.array.removeAllIf(this.authEventListeners_, function(ele) {\n return ele == listener;\n });\n};\n\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Namespace with crypto related helper functions.\n */\n\ngoog.provide('goog.crypt');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\n\n\n/**\n * Turns a string into an array of bytes; a \"byte\" being a JS number in the\n * range 0-255. Multi-byte characters are written as little-endian.\n * @param {string} str String value to arrify.\n * @return {!Array<number>} Array of numbers corresponding to the\n * UCS character codes of each character in str.\n */\ngoog.crypt.stringToByteArray = function(str) {\n var output = [], p = 0;\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\n // NOTE: c <= 0xffff since JavaScript strings are UTF-16.\n if (c > 0xff) {\n output[p++] = c & 0xff;\n c >>= 8;\n }\n output[p++] = c;\n }\n return output;\n};\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 {!Uint8Array|!Array<number>} bytes Array of numbers representing\n * characters.\n * @return {string} Stringification of the array.\n */\ngoog.crypt.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 = goog.array.slice(bytes, i, i + CHUNK_SIZE);\n str += String.fromCharCode.apply(null, chunk);\n }\n return str;\n};\n\n\n/**\n * Turns an array of numbers into the hex string given by the concatenation of\n * the hex values to which the numbers correspond.\n * @param {Uint8Array|Array<number>} array Array of numbers representing\n * characters.\n * @param {string=} opt_separator Optional separator between values\n * @return {string} Hex string.\n */\ngoog.crypt.byteArrayToHex = function(array, opt_separator) {\n return goog.array\n .map(\n array,\n function(numByte) {\n var hexByte = numByte.toString(16);\n return hexByte.length > 1 ? hexByte : '0' + hexByte;\n })\n .join(opt_separator || '');\n};\n\n\n/**\n * Converts a hex string into an integer array.\n * @param {string} hexString Hex string of 16-bit integers (two characters\n * per integer).\n * @return {!Array<number>} Array of {0,255} integers for the given string.\n */\ngoog.crypt.hexToByteArray = function(hexString) {\n goog.asserts.assert(\n hexString.length % 2 == 0, 'Key string length must be multiple of 2');\n var arr = [];\n for (var i = 0; i < hexString.length; i += 2) {\n arr.push(parseInt(hexString.substring(i, i + 2), 16));\n }\n return arr;\n};\n\n\n/**\n * Converts a JS string to a UTF-8 \"byte\" array.\n * @param {string} str 16-bit unicode string.\n * @return {!Array<number>} UTF-8 byte array.\n */\ngoog.crypt.stringToUtf8ByteArray = function(str) {\n // TODO(user): Use native implementations if/when available\n var out = [], p = 0;\n for (var i = 0; i < str.length; i++) {\n var c = str.charCodeAt(i);\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 (\n ((c & 0xFC00) == 0xD800) && (i + 1) < str.length &&\n ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);\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 } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n\n/**\n * Converts a UTF-8 byte array to JavaScript's 16-bit Unicode.\n * @param {Uint8Array|Array<number>} bytes UTF-8 byte array.\n * @return {string} 16-bit Unicode string.\n */\ngoog.crypt.utf8ByteArrayToString = function(bytes) {\n // TODO(user): Use native implementations if/when available\n var out = [], pos = 0, c = 0;\n while (pos < bytes.length) {\n var c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n var c2 = bytes[pos++];\n out[c++] = String.fromCharCode((c1 & 31) << 6 | c2 & 63);\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n var c2 = bytes[pos++];\n var c3 = bytes[pos++];\n var c4 = bytes[pos++];\n var u = ((c1 & 7) << 18 | (c2 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) -\n 0x10000;\n out[c++] = String.fromCharCode(0xD800 + (u >> 10));\n out[c++] = String.fromCharCode(0xDC00 + (u & 1023));\n } else {\n var c2 = bytes[pos++];\n var c3 = bytes[pos++];\n out[c++] =\n String.fromCharCode((c1 & 15) << 12 | (c2 & 63) << 6 | c3 & 63);\n }\n }\n return out.join('');\n};\n\n\n/**\n * XOR two byte arrays.\n * @param {!Uint8Array|!Int8Array|!Array<number>} bytes1 Byte array 1.\n * @param {!Uint8Array|!Int8Array|!Array<number>} bytes2 Byte array 2.\n * @return {!Array<number>} Resulting XOR of the two byte arrays.\n */\ngoog.crypt.xorByteArray = function(bytes1, bytes2) {\n goog.asserts.assert(\n bytes1.length == bytes2.length, 'XOR array lengths must match');\n\n var result = [];\n for (var i = 0; i < bytes1.length; i++) {\n result.push(bytes1[i] ^ bytes2[i]);\n }\n return result;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.storage.PendingRedirectManager class which\n * provides utilities to store, retrieve and delete the state of whether there\n * is a pending redirect operation previously triggered.\n */\n\ngoog.provide('fireauth.storage.PendingRedirectManager');\n\ngoog.require('fireauth.authStorage');\n\n\n/**\n * Defines the pending redirect storage manager. It provides methods\n * to store, retrieve and delete the state of whether there is a pending\n * redirect operation previously triggered.\n * @param {string} appId The Auth state's application ID.\n * @param {?fireauth.authStorage.Manager=} opt_manager The underlying storage\n * manager to use. If none is provided, the default global instance is used.\n * @constructor @struct @final\n */\nfireauth.storage.PendingRedirectManager = function(appId, opt_manager) {\n /** @const @private{string} appId The Auth state's application ID. */\n this.appId_ = appId;\n /**\n * @const @private{!fireauth.authStorage.Manager} The underlying storage\n * manager.\n */\n this.manager_ = opt_manager || fireauth.authStorage.Manager.getInstance();\n};\n\n\n/**\n * @const @private{!string} The pending redirect flag.\n */\nfireauth.storage.PendingRedirectManager.PENDING_FLAG_ = 'pending';\n\n\n/**\n * @const @private{!fireauth.authStorage.Key} The pending redirect status\n * storage identifier key.\n */\nfireauth.storage.PendingRedirectManager.PENDING_REDIRECT_KEY_ = {\n name: 'pendingRedirect',\n persistent: fireauth.authStorage.Persistence.SESSION\n};\n\n\n/**\n * Stores the pending redirect operation for the provided application ID.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.PendingRedirectManager.prototype.setPendingStatus =\n function() {\n return this.manager_.set(\n fireauth.storage.PendingRedirectManager.PENDING_REDIRECT_KEY_,\n fireauth.storage.PendingRedirectManager.PENDING_FLAG_,\n this.appId_);\n};\n\n\n/**\n * Removes the stored pending redirect operation for provided app ID.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.PendingRedirectManager.prototype.removePendingStatus =\n function() {\n return this.manager_.remove(\n fireauth.storage.PendingRedirectManager.PENDING_REDIRECT_KEY_,\n this.appId_);\n};\n\n\n/**\n * @return {!goog.Promise<boolean>} A promise that resolves with a boolean\n * whether there is a pending redirect operaiton for the provided app ID.\n */\nfireauth.storage.PendingRedirectManager.prototype.getPendingStatus =\n function() {\n return this.manager_.get(\n fireauth.storage.PendingRedirectManager.PENDING_REDIRECT_KEY_,\n this.appId_).then(function(response) {\n return response ==\n fireauth.storage.PendingRedirectManager.PENDING_FLAG_;\n });\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Auth event manager instance.\n */\n\ngoog.provide('fireauth.AuthEventHandler');\ngoog.provide('fireauth.AuthEventManager');\ngoog.provide('fireauth.AuthEventManager.Result');\ngoog.provide('fireauth.PopupAuthEventProcessor');\ngoog.provide('fireauth.RedirectAuthEventProcessor');\n\ngoog.require('fireauth.AuthCredential');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthEvent');\ngoog.require('fireauth.CordovaHandler');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.iframeclient.IfcHandler');\ngoog.require('fireauth.storage.PendingRedirectManager');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.Timer');\ngoog.require('goog.array');\n\n\n/**\n * Initializes the Auth event manager which provides the mechanism to connect\n * external Auth events to their corresponding listeners.\n * @param {string} authDomain The Firebase authDomain used to determine the\n * OAuth helper page domain.\n * @param {string} apiKey The API key for sending backend Auth requests.\n * @param {string} appName The App ID for the Auth instance that triggered this\n * request.\n * @constructor\n */\nfireauth.AuthEventManager = function(authDomain, apiKey, appName) {\n /**\n * @private {!Object<string, boolean>} The map of processed auth event IDs.\n */\n this.processedEvents_ = {};\n /** @private {number} The last saved processed event time in milliseconds. */\n this.lastProcessedEventTime_ = 0;\n /** @private {string} The Auth domain. */\n this.authDomain_ = authDomain;\n /** @private {string} The browser API key. */\n this.apiKey_ = apiKey;\n /** @private {string} The App name. */\n this.appName_ = appName;\n /**\n * @private {!Array<!fireauth.AuthEventHandler>} List of subscribed handlers.\n */\n this.subscribedHandlers_ = [];\n /**\n * @private {boolean} Whether the Auth event manager instance is initialized.\n */\n this.initialized_ = false;\n /** @private {function(?fireauth.AuthEvent)} The Auth event handler. */\n this.authEventHandler_ = goog.bind(this.handleAuthEvent_, this);\n /** @private {!fireauth.RedirectAuthEventProcessor} The redirect event\n * processor. */\n this.redirectAuthEventProcessor_ =\n new fireauth.RedirectAuthEventProcessor(this);\n /** @private {!fireauth.PopupAuthEventProcessor} The popup event processor. */\n this.popupAuthEventProcessor_ = new fireauth.PopupAuthEventProcessor(this);\n /**\n * @private {!fireauth.storage.PendingRedirectManager} The pending redirect\n * storage manager instance.\n */\n this.pendingRedirectStorageManager_ =\n new fireauth.storage.PendingRedirectManager(\n fireauth.AuthEventManager.getKey_(this.apiKey_, this.appName_));\n\n /**\n * @private {!Object.<!fireauth.AuthEvent.Type, !fireauth.AuthEventProcessor>}\n * Map containing Firebase event processor instances keyed by event type.\n */\n this.typeToManager_ = {};\n this.typeToManager_[fireauth.AuthEvent.Type.UNKNOWN] =\n this.redirectAuthEventProcessor_;\n this.typeToManager_[fireauth.AuthEvent.Type.SIGN_IN_VIA_REDIRECT] =\n this.redirectAuthEventProcessor_;\n this.typeToManager_[fireauth.AuthEvent.Type.LINK_VIA_REDIRECT] =\n this.redirectAuthEventProcessor_;\n this.typeToManager_[fireauth.AuthEvent.Type.REAUTH_VIA_REDIRECT] =\n this.redirectAuthEventProcessor_;\n this.typeToManager_[fireauth.AuthEvent.Type.SIGN_IN_VIA_POPUP] =\n this.popupAuthEventProcessor_;\n this.typeToManager_[fireauth.AuthEvent.Type.LINK_VIA_POPUP] =\n this.popupAuthEventProcessor_;\n this.typeToManager_[fireauth.AuthEvent.Type.REAUTH_VIA_POPUP] =\n this.popupAuthEventProcessor_;\n /**\n * @private {!fireauth.OAuthSignInHandler} The OAuth sign in handler depending\n * on the current environment.\n */\n this.oauthSignInHandler_ =\n fireauth.AuthEventManager.instantiateOAuthSignInHandler(\n this.authDomain_, this.apiKey_, this.appName_,\n firebase.SDK_VERSION || null,\n fireauth.constants.clientEndpoint);\n};\n\n\n/**\n * @const {number} The number of milliseconds since the last processed\n * event before the event duplication cache is cleared. This is currently\n * 10 minutes.\n */\nfireauth.AuthEventManager.EVENT_DUPLICATION_CACHE_DURATION = 10 * 60 * 1000;\n\n\n/**\n * @return {!fireauth.RedirectAuthEventProcessor} The redirect event processor.\n */\nfireauth.AuthEventManager.prototype.getRedirectAuthEventProcessor = function() {\n return this.redirectAuthEventProcessor_;\n};\n\n\n/** @return {!fireauth.PopupAuthEventProcessor} The popup event processor. */\nfireauth.AuthEventManager.prototype.getPopupAuthEventProcessor = function() {\n return this.popupAuthEventProcessor_;\n};\n\n\n/**\n * Instantiates an OAuth sign-in handler depending on the current environment\n * and returns it.\n * @param {string} authDomain The Firebase authDomain used to determine the\n * OAuth helper page domain.\n * @param {string} apiKey The API key for sending backend Auth requests.\n * @param {string} appName The App ID for the Auth instance that triggered this\n * request.\n * @param {?string} version The SDK client version.\n * @param {?string=} opt_endpointId The endpoint ID (staging, test Gaia, etc).\n * @return {!fireauth.OAuthSignInHandler} The OAuth sign in handler depending\n * on the current environment.\n */\nfireauth.AuthEventManager.instantiateOAuthSignInHandler =\n function(authDomain, apiKey, appName, version, opt_endpointId) {\n // This assumes that android/iOS file environment must be a Cordova\n // environment which is not true. This is the best way currently available\n // to instantiate this synchronously without waiting for checkIfCordova to\n // resolve. If it is determined that the Cordova was falsely detected, it will\n // be caught via actionable public popup and redirect methods.\n return fireauth.util.isAndroidOrIosCordovaScheme() ?\n new fireauth.CordovaHandler(\n authDomain, apiKey, appName, version, undefined, undefined,\n opt_endpointId) :\n new fireauth.iframeclient.IfcHandler(\n authDomain, apiKey, appName, version, opt_endpointId);\n};\n\n\n/** Reset iframe. This will require reinitializing it.*/\nfireauth.AuthEventManager.prototype.reset = function() {\n // Reset initialized status. This will force a popup request to re-initialize\n // the iframe.\n this.initialized_ = false;\n // Remove any previous existing Auth event listener.\n this.oauthSignInHandler_.removeAuthEventListener(this.authEventHandler_);\n // Construct a new instance of OAuth sign in handler.\n\n this.oauthSignInHandler_ =\n fireauth.AuthEventManager.instantiateOAuthSignInHandler(\n this.authDomain_, this.apiKey_, this.appName_,\n firebase.SDK_VERSION || null);\n this.processedEvents_ = {};\n};\n\n\n/**\n * Clears the cached redirect result as long as there is no pending redirect\n * result being processed. Unrecoverable errors will not be cleared.\n */\nfireauth.AuthEventManager.prototype.clearRedirectResult = function() {\n this.redirectAuthEventProcessor_.clearRedirectResult();\n};\n\n\n/**\n * @typedef {{\n * user: (?fireauth.AuthUser|undefined),\n * credential: (?fireauth.AuthCredential|undefined),\n * operationType: (?string|undefined),\n * additionalUserInfo: (?fireauth.AdditionalUserInfo|undefined)\n * }}\n */\nfireauth.AuthEventManager.Result;\n\n\n/**\n * Whether to enable Auth event manager subscription.\n * @const {boolean}\n */\nfireauth.AuthEventManager.ENABLED = true;\n\n\n/**\n * Initializes the ifchandler and add Auth event listener on it.\n * @return {!goog.Promise} The promise that resolves when the iframe is ready.\n */\nfireauth.AuthEventManager.prototype.initialize = function() {\n var self = this;\n // Initialize once.\n if (!this.initialized_) {\n this.initialized_ = true;\n // Listen to Auth events on iframe.\n this.oauthSignInHandler_.addAuthEventListener(this.authEventHandler_);\n }\n var previousOauthSignInHandler = this.oauthSignInHandler_;\n // This should initialize ifchandler underneath.\n // Return on OAuth handler ready promise.\n // Check for error in ifcHandler used to embed the iframe.\n return this.oauthSignInHandler_.initializeAndWait()\n .thenCatch(function(error) {\n // Force ifchandler to reinitialize on retrial.\n if (self.oauthSignInHandler_ == previousOauthSignInHandler) {\n // If a new OAuth sign in handler was already created, do not reset.\n self.reset();\n }\n throw error;\n });\n};\n\n\n/**\n * Called after it is determined that there is no pending redirect result.\n * Will populate the redirect result if it is guaranteed to be null and will\n * force an early initialization of the OAuth sign in handler if the\n * environment requires it.\n * @private\n */\nfireauth.AuthEventManager.prototype.initializeWithNoPendingRedirectResult_ =\n function() {\n var self = this;\n // Check if the OAuth sign in handler should be initialized early in all\n // cases.\n if (this.oauthSignInHandler_.shouldBeInitializedEarly()) {\n this.initialize().thenCatch(function(error) {\n // Current environment was falsely detected as Cordova, trigger a fake\n // Auth event to notify getRedirectResult that operation is not supported.\n var notSupportedEvent = new fireauth.AuthEvent(\n fireauth.AuthEvent.Type.UNKNOWN,\n null,\n null,\n null,\n new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n if (fireauth.AuthEventManager.isCordovaFalsePositive_(\n /** @type {?fireauth.AuthError} */ (error))) {\n self.handleAuthEvent_(notSupportedEvent);\n }\n });\n }\n // For environments where storage is volatile, we can't determine that\n // there is no pending redirect response. This is true in Cordova\n // where an activity would be destroyed in some cases and the\n // sessionStorage is lost.\n if (!this.oauthSignInHandler_.hasVolatileStorage()) {\n // Since there is no redirect result, it is safe to default to empty\n // redirect result instead of blocking on this.\n // The downside here is that on iOS devices, calling signInWithPopup\n // after getRedirectResult resolves and the iframe does not finish\n // loading, the popup event propagating to the iframe would not be\n // detected. This is because in iOS devices, storage events only trigger\n // in iframes but are not actually saved in web storage. The iframe must\n // be embedded and ready before the storage event propagates. Otherwise\n // it won't be detected.\n this.redirectAuthEventProcessor_.defaultToEmptyResponse();\n }\n};\n\n\n/**\n * Subscribes an Auth event handler to list of handlers.\n * @param {!fireauth.AuthEventHandler} handler The instance to subscribe.\n */\nfireauth.AuthEventManager.prototype.subscribe = function(handler) {\n if (!goog.array.contains(this.subscribedHandlers_, handler)) {\n this.subscribedHandlers_.push(handler);\n }\n if (this.initialized_) {\n return;\n }\n var self = this;\n // Check pending redirect status.\n this.pendingRedirectStorageManager_.getPendingStatus()\n .then(function(status) {\n // Pending redirect detected.\n if (status) {\n // Remove pending status and initialize.\n self.pendingRedirectStorageManager_.removePendingStatus()\n .then(function() {\n self.initialize().thenCatch(function(error) {\n // Current environment was falsely detected as Cordova, trigger a\n // fake Auth event to notify getRedirectResult that operation is\n // not supported.\n var notSupportedEvent = new fireauth.AuthEvent(\n fireauth.AuthEvent.Type.UNKNOWN,\n null,\n null,\n null,\n new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n if (fireauth.AuthEventManager.isCordovaFalsePositive_(\n /** @type {?fireauth.AuthError} */ (error))) {\n self.handleAuthEvent_(notSupportedEvent);\n }\n });\n });\n } else {\n // No previous redirect, default to empty response.\n self.initializeWithNoPendingRedirectResult_();\n }\n }).thenCatch(function(error) {\n // Error checking pending status, default to empty response.\n self.initializeWithNoPendingRedirectResult_();\n });\n};\n\n\n/**\n * @param {!fireauth.AuthEventHandler} handler The possible subscriber.\n * @return {boolean} Whether the handle is subscribed.\n */\nfireauth.AuthEventManager.prototype.isSubscribed = function(handler) {\n return goog.array.contains(this.subscribedHandlers_, handler);\n};\n\n\n/**\n * Unsubscribes an Auth event handler to list of handlers.\n * @param {!fireauth.AuthEventHandler} handler The instance to unsubscribe.\n */\nfireauth.AuthEventManager.prototype.unsubscribe = function(handler) {\n goog.array.removeAllIf(this.subscribedHandlers_, function(ele) {\n return ele == handler;\n });\n};\n\n\n/**\n * @param {?fireauth.AuthEvent} authEvent External Auth event to check.\n * @return {boolean} Whether the event was previously processed.\n * @private\n */\nfireauth.AuthEventManager.prototype.hasProcessedAuthEvent_ =\n function(authEvent) {\n // Prevent duplicate event tracker from growing too large.\n if (goog.now() - this.lastProcessedEventTime_ >=\n fireauth.AuthEventManager.EVENT_DUPLICATION_CACHE_DURATION) {\n this.processedEvents_ = {};\n this.lastProcessedEventTime_ = 0;\n }\n if (authEvent && authEvent.getUid() &&\n this.processedEvents_.hasOwnProperty(authEvent.getUid())) {\n // If event is already processed, ignore it.\n return true;\n }\n return false;\n};\n\n\n/**\n * Saves the provided event uid to prevent processing duplication.\n * @param {?fireauth.AuthEvent} authEvent External Auth event to track in\n * processed list of events.\n * @private\n */\nfireauth.AuthEventManager.prototype.saveProcessedAuthEvent_ =\n function(authEvent) {\n if (authEvent &&\n (authEvent.getSessionId() || authEvent.getEventId())) {\n // Save processed event ID. We keep the cache for 10 minutes to prevent it\n // from growing too large.\n this.processedEvents_[\n /** @type {string} */ (authEvent.getUid())] = true;\n // Save last processing time.\n this.lastProcessedEventTime_ = goog.now();\n }\n};\n\n\n/**\n * Handles external Auth event detected by the OAuth sign-in handler.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @return {boolean} Whether the event found an appropriate owner that can\n * handle it. This signals to the OAuth helper iframe that the event is safe\n * to delete.\n * @private\n */\nfireauth.AuthEventManager.prototype.handleAuthEvent_ = function(authEvent) {\n // This should not happen as fireauth.iframe.AuthRelay will not send null\n // events.\n if (!authEvent) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT);\n }\n if (this.hasProcessedAuthEvent_(authEvent)) {\n // If event is already processed, ignore it.\n return false;\n }\n // Initialize event processed status to false. When set to false, the event is\n // not clear to delete in the OAuth helper iframe as the owner of this event\n // could be a user in another tab.\n var processed = false;\n // Lookup a potential handler for this event.\n for (var i = 0; i < this.subscribedHandlers_.length; i++) {\n var potentialHandler = this.subscribedHandlers_[i];\n if (potentialHandler.canHandleAuthEvent(\n authEvent.getType(), authEvent.getEventId())) {\n var eventManager = this.typeToManager_[authEvent.getType()];\n if (eventManager) {\n eventManager.processAuthEvent(authEvent, potentialHandler);\n // Prevent events with event IDs or session IDs from duplicate\n // processing.\n this.saveProcessedAuthEvent_(authEvent);\n }\n // Event has been processed, free to clear in OAuth helper.\n processed = true;\n break;\n }\n }\n // If no redirect response ready yet, default to an empty response.\n this.redirectAuthEventProcessor_.defaultToEmptyResponse();\n // Notify iframe of processed status.\n return processed;\n};\n\n\n/**\n * The popup promise timeout delay with units in ms between the time the iframe\n * is ready (successfully embedded on the page) and the time the popup Auth\n * event is detected in the parent container.\n * @const {!fireauth.util.Delay}\n * @private\n */\nfireauth.AuthEventManager.POPUP_TIMEOUT_MS_ =\n new fireauth.util.Delay(2000, 10000);\n\n\n/**\n * The redirect promise timeout delay with units in ms. Unlike the popup\n * timeout, this covers the entire duration from start to getRedirectResult\n * resolution.\n * @const {!fireauth.util.Delay}\n * @private\n */\nfireauth.AuthEventManager.REDIRECT_TIMEOUT_MS_ =\n new fireauth.util.Delay(30000, 60000);\n\n\n/**\n * Returns the redirect result. If coming back from a successful redirect sign\n * in, will resolve to the signed in user. If coming back from an unsuccessful\n * redirect sign, will reject with the proper error. If no redirect operation\n * called, resolves with null.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthEventManager.prototype.getRedirectResult = function() {\n return this.redirectAuthEventProcessor_.getRedirectResult();\n};\n\n\n/**\n * Processes the popup request. The popup instance must be provided externally\n * and on error, the requestor must close the window.\n * @param {?Window} popupWin The popup window reference.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {string=} opt_eventId The optional event ID.\n * @param {boolean=} opt_alreadyRedirected Whether popup is already redirected\n * to final destination.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {!goog.Promise} The popup window promise.\n */\nfireauth.AuthEventManager.prototype.processPopup =\n function(popupWin, mode, provider, opt_eventId, opt_alreadyRedirected,\n opt_tenantId) {\n var self = this;\n return this.oauthSignInHandler_.processPopup(\n popupWin,\n mode,\n provider,\n // On initialization, add Auth event listener if not already added.\n function() {\n if (!self.initialized_) {\n self.initialized_ = true;\n // Listen to Auth events on iframe.\n self.oauthSignInHandler_.addAuthEventListener(self.authEventHandler_);\n }\n },\n // On error, reset to force re-initialization on retrial.\n function(error) {\n self.reset();\n },\n opt_eventId,\n opt_alreadyRedirected,\n opt_tenantId);\n};\n\n\n/**\n * @param {?fireauth.AuthError} error The error to check for Cordova false\n * positive.\n * @return {boolean} Whether the current environment was falsely identified as\n * Cordova.\n * @private\n */\nfireauth.AuthEventManager.isCordovaFalsePositive_ = function(error) {\n if (error && error['code'] == 'auth/cordova-not-ready') {\n return true;\n }\n return false;\n};\n\n\n/**\n * Processes the redirect request.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {string=} opt_eventId The optional event ID.\n * @param {?string=} opt_tenantId The optional tenant ID.\n * @return {!goog.Promise}\n */\nfireauth.AuthEventManager.prototype.processRedirect =\n function(mode, provider, opt_eventId, opt_tenantId) {\n var self = this;\n var error;\n // Save pending status first.\n return this.pendingRedirectStorageManager_.setPendingStatus()\n .then(function() {\n // Try to redirect.\n return self.oauthSignInHandler_.processRedirect(\n mode, provider, opt_eventId, opt_tenantId)\n .thenCatch(function(e) {\n if (fireauth.AuthEventManager.isCordovaFalsePositive_(\n /** @type {?fireauth.AuthError} */ (e))) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED);\n }\n // On failure, remove pending status and rethrow the error.\n error = e;\n return self.pendingRedirectStorageManager_.removePendingStatus()\n .then(function() {\n throw error;\n });\n })\n .then(function() {\n // Resolve, if the OAuth handler unloads the page on redirect.\n if (!self.oauthSignInHandler_.unloadsOnRedirect()) {\n // Relevant to Cordova case, will not matter in web case where\n // browser redirects.\n // In Cordova, the activity could still be running in the background\n // so we need to wait for getRedirectResult to resolve before\n // resolving this current promise.\n // Otherwise, if the activity is destroyed, getRedirectResult would\n // be used.\n // At this point, authEvent should have been triggered.\n // When this promise resolves, the developer should be able to\n // call getRedirectResult to get the result of this operation.\n // Remove pending status as result should be resolved.\n return self.pendingRedirectStorageManager_.removePendingStatus()\n .then(function() {\n // Ensure redirect result ready before resolving.\n return self.getRedirectResult();\n }).then(function(result) {\n // Do nothing. Developer expected to call getRedirectResult to\n // get result.\n }).thenCatch(function(error) {\n // Do nothing. Developer expected to call getRedirectResult to\n // get result.\n });\n } else {\n // For environments that will unload the page on redirect, keep\n // the promise pending on success. This makes it easier to reuse\n // the same code for Cordova environment and browser environment.\n // The developer can always add getRedirectResult on promise\n // resolution and expect that when it runs, the redirect operation\n // was completed.\n return new goog.Promise(function(resolve, reject) {\n // Keep this pending.\n });\n }\n });\n });\n};\n\n\n/**\n * Waits for popup window to close. When closed start timeout listener for popup\n * pending promise. If in the process, it was detected that the iframe does not\n * support web storage, the popup is closed and the web storage unsupported\n * error is thrown.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @param {!fireauth.AuthEvent.Type} mode The Auth event type.\n * @param {!Window} popupWin The popup window.\n * @param {?string=} opt_eventId The event ID.\n * @return {!goog.Promise}\n */\nfireauth.AuthEventManager.prototype.startPopupTimeout =\n function(owner, mode, popupWin, opt_eventId) {\n return this.oauthSignInHandler_.startPopupTimeout(\n popupWin,\n // On popup error such as popup closed by user or web storage not\n // supported.\n function(error) {\n // Notify owner of the error.\n owner.resolvePendingPopupEvent(mode, null, error, opt_eventId);\n },\n fireauth.AuthEventManager.POPUP_TIMEOUT_MS_.get());\n};\n\n\n\n/**\n * @private {!Object.<string, !fireauth.AuthEventManager>} Map containing\n * Firebase event manager instances keyed by Auth event manager ID.\n */\nfireauth.AuthEventManager.manager_ = {};\n\n\n/**\n * The separator for manager keys to concatenate app name and apiKey.\n * @const {string}\n * @private\n */\nfireauth.AuthEventManager.KEY_SEPARATOR_ = ':';\n\n\n/**\n * @param {string} apiKey The API key for sending backend Auth requests.\n * @param {string} appName The Auth instance that initiated the Auth event.\n * @return {string} The key identifying the Auth event manager instance.\n * @private\n */\nfireauth.AuthEventManager.getKey_ = function(apiKey, appName) {\n return apiKey + fireauth.AuthEventManager.KEY_SEPARATOR_ + appName;\n};\n\n\n/**\n * @param {string} authDomain The Firebase authDomain used to determine the\n * OAuth helper page domain.\n * @param {string} apiKey The API key for sending backend Auth requests.\n * @param {string} appName The Auth instance that initiated the Auth event\n * manager.\n * @return {!fireauth.AuthEventManager} the requested manager instance.\n */\nfireauth.AuthEventManager.getManager = function(authDomain, apiKey, appName) {\n // Construct storage key.\n var key = fireauth.AuthEventManager.getKey_(apiKey, appName);\n if (!fireauth.AuthEventManager.manager_[key]) {\n fireauth.AuthEventManager.manager_[key] =\n new fireauth.AuthEventManager(authDomain, apiKey, appName);\n }\n return fireauth.AuthEventManager.manager_[key];\n};\n\n\n\n/**\n * The interface that represents a specific type of Auth event processor.\n * @interface\n */\nfireauth.AuthEventProcessor = function() {};\n\n\n/**\n * Completes the processing of an external Auth event detected by the embedded\n * iframe.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @return {!goog.Promise<undefined>}\n */\nfireauth.AuthEventProcessor.prototype.processAuthEvent =\n function(authEvent, owner) {};\n\n\n\n/**\n * Redirect Auth event manager.\n * @param {!fireauth.AuthEventManager} manager The parent Auth event manager.\n * @constructor\n * @implements {fireauth.AuthEventProcessor}\n */\nfireauth.RedirectAuthEventProcessor = function(manager) {\n this.manager_ = manager;\n // Only one redirect result can be tracked on first load.\n /**\n * @private {?function():!goog.Promise<!fireauth.AuthEventManager.Result>}\n * Redirect result resolver. This will be used to resolve the\n * getRedirectResult promise. When the redirect result is obtained, this\n * field will be set.\n */\n this.redirectedUserPromise_ = null;\n /**\n * @private {!Array<function(!fireauth.AuthEventManager.Result)>} Pending\n * promise redirect resolver. When the redirect result is obtained and the\n * user is detected, this will be called.\n */\n this.redirectResolve_ = [];\n /**\n * @private {!Array<function(*)>} Pending Promise redirect rejecter. When the\n * redirect result is obtained and an error is detected, this will be\n * called.\n */\n this.redirectReject_ = [];\n /** @private {?goog.Promise} Pending timeout promise for redirect. */\n this.redirectTimeoutPromise_ = null;\n /**\n * @private {boolean} Whether redirect result is resolved. This is true\n * when a valid Auth event has been triggered.\n */\n this.redirectResultResolved_ = false;\n /**\n * @private {boolean} Whether an unrecoverable error was detected. This\n * includes web storage unsupported or operation not allowed errors.\n */\n this.unrecoverableErrorDetected_ = false;\n};\n\n\n/** Reset any previous redirect result. */\nfireauth.RedirectAuthEventProcessor.prototype.reset = function() {\n // Reset to allow override getRedirectResult. This is relevant for Cordova\n // environment where redirect events do not necessarily unload the current\n // page.\n this.redirectedUserPromise_ = null;\n if (this.redirectTimeoutPromise_) {\n this.redirectTimeoutPromise_.cancel();\n this.redirectTimeoutPromise_ = null;\n }\n};\n\n\n/**\n * Completes the processing of an external Auth event detected by the embedded\n * iframe.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @return {!goog.Promise<undefined>}\n * @override\n */\nfireauth.RedirectAuthEventProcessor.prototype.processAuthEvent =\n function(authEvent, owner) {\n // This should not happen as fireauth.iframe.AuthRelay will not send null\n // events.\n if (!authEvent) {\n return goog.Promise.reject(\n new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT));\n }\n // Reset any pending redirect result. This event will overwrite it.\n this.reset();\n this.redirectResultResolved_ = true;\n var mode = authEvent.getType();\n var eventId = authEvent.getEventId();\n // Check if web storage is not supported in the iframe.\n var isWebStorageNotSupported =\n authEvent.getError() &&\n authEvent.getError()['code'] == 'auth/web-storage-unsupported';\n /// Check if operation is supported in this environment.\n var isOperationNotSupported =\n authEvent.getError() &&\n authEvent.getError()['code'] == 'auth/operation-not-supported-in-this-' +\n 'environment';\n this.unrecoverableErrorDetected_ =\n !!(isWebStorageNotSupported || isOperationNotSupported);\n // UNKNOWN mode is always triggered on load by iframe when no popup/redirect\n // data is available. If web storage unsupported error is thrown, process as\n // error and not as unknown event. If the operation is not supported in this\n // environment, also treat as an error and not as an unknown event.\n if (mode == fireauth.AuthEvent.Type.UNKNOWN &&\n !isWebStorageNotSupported &&\n !isOperationNotSupported) {\n return this.processUnknownEvent_();\n } else if (authEvent.hasError()) {\n return this.processErrorEvent_(authEvent, owner);\n } else if (owner.getAuthEventHandlerFinisher(mode, eventId)) {\n return this.processSuccessEvent_(authEvent, owner);\n } else {\n return goog.Promise.reject(\n new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT));\n }\n};\n\n\n/**\n * Sets an empty redirect result response when no redirect result is available.\n */\nfireauth.RedirectAuthEventProcessor.prototype.defaultToEmptyResponse =\n function() {\n // If the first event does not resolve redirectResult and no subscriber can\n // handle it, set redirect result to null.\n // An example of this scenario would be a link via redirect that was triggered\n // by a user that was not logged in. canHandleAuthEvent will be false for all\n // subscribers. So make sure getRedirectResult when called will resolve to a\n // null user.\n if (!this.redirectResultResolved_) {\n this.redirectResultResolved_ = true;\n // No Auth event available, getRedirectResult should resolve with null.\n this.setRedirectResult_(false, null, null);\n }\n};\n\n\n/**\n * Clears the cached redirect result as long as there is no pending redirect\n * result being processed. Unrecoverable errors will not be cleared.\n */\nfireauth.RedirectAuthEventProcessor.prototype.clearRedirectResult = function() {\n // Clear the result if it is already resolved and no unrecoverable errors are\n // detected.\n if (this.redirectResultResolved_ && !this.unrecoverableErrorDetected_) {\n this.setRedirectResult_(false, null, null);\n }\n};\n\n\n/**\n * Processes the unknown event.\n * @return {!goog.Promise<undefined>}\n * @private\n */\nfireauth.RedirectAuthEventProcessor.prototype.processUnknownEvent_ =\n function() {\n // No Auth event available, getRedirectResult should resolve with null.\n this.setRedirectResult_(false, null, null);\n return goog.Promise.resolve();\n};\n\n\n/**\n * Processes an error event.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @return {!goog.Promise<undefined>}\n * @private\n */\nfireauth.RedirectAuthEventProcessor.prototype.processErrorEvent_ =\n function(authEvent, owner) {\n // Set redirect result to resolve with null if event is not a redirect or\n // reject with error if event is an error.\n this.setRedirectResult_(true, null, authEvent.getError());\n return goog.Promise.resolve();\n};\n\n\n/**\n * Processes a successful event.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @return {!goog.Promise<undefined>}\n * @private\n */\nfireauth.RedirectAuthEventProcessor.prototype.processSuccessEvent_ =\n function(authEvent, owner) {\n var self = this;\n var eventId = authEvent.getEventId();\n var mode = authEvent.getType();\n var handler = owner.getAuthEventHandlerFinisher(mode, eventId);\n var requestUri = /** @type {string} */ (authEvent.getUrlResponse());\n var sessionId = /** @type {string} */ (authEvent.getSessionId());\n var postBody = /** @type {?string} */ (authEvent.getPostBody());\n var tenantId = /** @type {?string} */ (authEvent.getTenantId());\n var isRedirect = fireauth.AuthEvent.isRedirect(authEvent);\n // Complete sign in or link account operation and then pass result to\n // relevant pending popup promise.\n return handler(requestUri, sessionId, tenantId, postBody)\n .then(function(popupRedirectResponse) {\n // Flow completed.\n // For a redirect operation resolve with the popupRedirectResponse,\n // otherwise resolve with null.\n self.setRedirectResult_(isRedirect, popupRedirectResponse, null);\n }).thenCatch(function(error) {\n // Flow not completed due to error.\n // For a redirect operation reject with the error, otherwise resolve\n // with null.\n self.setRedirectResult_(\n isRedirect, null, /** @type {!fireauth.AuthError} */ (error));\n // Always resolve.\n return;\n });\n};\n\n\n/**\n * Sets redirect error result.\n * @param {!fireauth.AuthError} error The redirect operation error.\n * @private\n */\nfireauth.RedirectAuthEventProcessor.prototype.setRedirectReject_ =\n function(error) {\n // If a redirect error detected, reject getRedirectResult with that error.\n this.redirectedUserPromise_ = function() {\n return goog.Promise.reject(error);\n };\n // Reject all pending getRedirectResult promises.\n if (this.redirectReject_.length) {\n for (var i = 0; i < this.redirectReject_.length; i++) {\n this.redirectReject_[i](error);\n }\n }\n};\n\n\n/**\n * Sets redirect success result.\n * @param {!fireauth.AuthEventManager.Result} popupRedirectResult The\n * resolved user for a successful or null user redirect.\n * @private\n */\nfireauth.RedirectAuthEventProcessor.prototype.setRedirectResolve_ =\n function(popupRedirectResult) {\n // If a redirect user detected, resolve getRedirectResult with the\n // popupRedirectResult.\n // Result should not be null in this case.\n this.redirectedUserPromise_ = function() {\n return goog.Promise.resolve(\n /** @type {!fireauth.AuthEventManager.Result} */ (popupRedirectResult));\n };\n // Resolve all pending getRedirectResult promises.\n if (this.redirectResolve_.length) {\n for (var i = 0; i < this.redirectResolve_.length; i++) {\n this.redirectResolve_[i](\n /** @type {!fireauth.AuthEventManager.Result} */ (\n popupRedirectResult));\n }\n }\n};\n\n\n/**\n * @param {boolean} isRedirect Whether Auth event is a redirect event.\n * @param {?fireauth.AuthEventManager.Result} popupRedirectResult The\n * resolved user for a successful redirect. This user is null if no redirect\n * operation run.\n * @param {?fireauth.AuthError} error The redirect operation error.\n * @private\n */\nfireauth.RedirectAuthEventProcessor.prototype.setRedirectResult_ =\n function(isRedirect, popupRedirectResult, error) {\n if (isRedirect) {\n // This is a redirect operation, either resolves with user or error.\n if (error) {\n // If a redirect error detected, reject getRedirectResult with that error.\n this.setRedirectReject_(error);\n } else {\n // If a redirect user detected, resolve getRedirectResult with the\n // popupRedirectResult.\n // Result should not be null in this case.\n this.setRedirectResolve_(\n /** @type {!fireauth.AuthEventManager.Result} */ (\n popupRedirectResult));\n }\n } else {\n // Not a redirect, set redirectUser_ to return null.\n this.setRedirectResolve_({\n 'user': null\n });\n }\n // Reset all pending promises.\n this.redirectResolve_ = [];\n this.redirectReject_ = [];\n};\n\n\n/**\n * Returns the redirect result. If coming back from a successful redirect sign\n * in, will resolve to the signed in user. If coming back from an unsuccessful\n * redirect sign, will reject with the proper error. If no redirect operation\n * called, resolves with null.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.RedirectAuthEventProcessor.prototype.getRedirectResult = function() {\n var self = this;\n // Initial result could be overridden in the case of Cordova.\n // Auth domain must be included for this to resolve.\n // If still pending just return the pending promise.\n var p = new goog.Promise(function(resolve, reject) {\n // The following logic works if this method was called before Auth event\n // is triggered.\n if (!self.redirectedUserPromise_) {\n // Save resolves and rejects of pending promise for redirect operation.\n self.redirectResolve_.push(resolve);\n self.redirectReject_.push(reject);\n // Start timeout listener to getRedirectResult pending promise.\n // Call this only when redirectedUserPromise_ is not determined.\n self.startRedirectTimeout_();\n } else {\n // Called after Auth event is triggered.\n self.redirectedUserPromise_().then(resolve, reject);\n }\n });\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (p);\n};\n\n\n/**\n * Starts timeout listener for getRedirectResult pending promise. This method\n * should not be called again after getRedirectResult's redirectedUserPromise_\n * is determined.\n * @private\n */\nfireauth.RedirectAuthEventProcessor.prototype.startRedirectTimeout_ =\n function() {\n // Expire pending timeout promise for popup operation.\n var self = this;\n var error = new fireauth.AuthError(\n fireauth.authenum.Error.TIMEOUT);\n if (this.redirectTimeoutPromise_) {\n this.redirectTimeoutPromise_.cancel();\n }\n // For redirect mode.\n this.redirectTimeoutPromise_ =\n goog.Timer.promise(fireauth.AuthEventManager.REDIRECT_TIMEOUT_MS_.get())\n .then(function() {\n // If not resolved yet, reject with timeout error.\n if (!self.redirectedUserPromise_) {\n // Consider redirect result resolved.\n self.redirectResultResolved_ = true;\n self.setRedirectResult_(true, null, error);\n }\n });\n\n};\n\n\n\n/**\n * Popup Auth event manager.\n * @param {!fireauth.AuthEventManager} manager The parent Auth event manager.\n * @constructor\n * @implements {fireauth.AuthEventProcessor}\n */\nfireauth.PopupAuthEventProcessor = function(manager) {\n this.manager_ = manager;\n};\n\n\n/**\n * Completes the processing of an external Auth event detected by the embedded\n * iframe.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @return {!goog.Promise<undefined>}\n * @override\n */\nfireauth.PopupAuthEventProcessor.prototype.processAuthEvent =\n function(authEvent, owner) {\n // This should not happen as fireauth.iframe.AuthRelay will not send null\n // events.\n if (!authEvent) {\n return goog.Promise.reject(\n new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT));\n }\n var mode = authEvent.getType();\n var eventId = authEvent.getEventId();\n if (authEvent.hasError()) {\n return this.processErrorEvent_(authEvent, owner);\n } else if (owner.getAuthEventHandlerFinisher(mode, eventId)) {\n return this.processSuccessEvent_(authEvent, owner);\n } else {\n return goog.Promise.reject(\n new fireauth.AuthError(fireauth.authenum.Error.INVALID_AUTH_EVENT));\n }\n};\n\n\n/**\n * Processes an error event.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @return {!goog.Promise<undefined>}\n * @private\n */\nfireauth.PopupAuthEventProcessor.prototype.processErrorEvent_ =\n function(authEvent, owner) {\n var eventId = authEvent.getEventId();\n var mode = authEvent.getType();\n // For pending popup promises trigger rejects with the error.\n owner.resolvePendingPopupEvent(mode, null, authEvent.getError(), eventId);\n return goog.Promise.resolve();\n};\n\n\n/**\n * Processes a successful event.\n * @param {?fireauth.AuthEvent} authEvent External Auth event detected by\n * iframe.\n * @param {!fireauth.AuthEventHandler} owner The owner of the event.\n * @return {!goog.Promise<undefined>}\n * @private\n */\nfireauth.PopupAuthEventProcessor.prototype.processSuccessEvent_ =\n function(authEvent, owner) {\n var eventId = authEvent.getEventId();\n var mode = authEvent.getType();\n var handler = owner.getAuthEventHandlerFinisher(mode, eventId);\n // Successful operation, complete the exchange for an ID token.\n var requestUri = /** @type {string} */ (authEvent.getUrlResponse());\n var sessionId = /** @type {string} */ (authEvent.getSessionId());\n var postBody = /** @type {?string} */ (authEvent.getPostBody());\n var tenantId = /** @type {?string} */ (authEvent.getTenantId());\n // Complete sign in or link account operation and then pass result to\n // relevant pending popup promise.\n return handler(requestUri, sessionId, tenantId, postBody)\n .then(function(popupRedirectResponse) {\n // Flow completed.\n // Resolve pending popup promise if it exists.\n owner.resolvePendingPopupEvent(mode, popupRedirectResponse, null, eventId);\n }).thenCatch(function(error) {\n // Flow not completed due to error.\n // Resolve pending promise if it exists.\n owner.resolvePendingPopupEvent(\n mode, null, /** @type {!fireauth.AuthError} */ (error), eventId);\n // Always resolve.\n return;\n });\n};\n\n\n\n/**\n * The interface that represents an Auth event handler. It provides the\n * ability for the Auth event manager to determine the owner of an Auth event,\n * the ability to resolve a pending popup event and the appropriate handler for\n * an event.\n * @interface\n */\nfireauth.AuthEventHandler = function() {};\n\n\n/**\n * @param {!fireauth.AuthEvent.Type} mode The Auth type mode.\n * @param {?string=} opt_eventId The event ID.\n * @return {boolean} Whether the Auth event handler can handler the provided\n * event.\n */\nfireauth.AuthEventHandler.prototype.canHandleAuthEvent =\n function(mode, opt_eventId) {};\n\n\n/**\n * Completes the pending popup operation. If error is not null, rejects with the\n * error. Otherwise, it resolves with the popup redirect result.\n * @param {!fireauth.AuthEvent.Type} mode The Auth type mode.\n * @param {?fireauth.AuthEventManager.Result} popupRedirectResult The result\n * to resolve with when no error supplied.\n * @param {?fireauth.AuthError} error When supplied, the promise will reject.\n * @param {?string=} opt_eventId The event ID.\n */\nfireauth.AuthEventHandler.prototype.resolvePendingPopupEvent =\n function(mode, popupRedirectResult, error, opt_eventId) {};\n\n\n/**\n * Returns the handler's appropriate popup and redirect sign in operation\n * finisher.\n * @param {!fireauth.AuthEvent.Type} mode The Auth type mode.\n * @param {?string=} opt_eventId The optional event ID.\n * @return {?function(string, string, ?string,\n * ?string=):!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthEventHandler.prototype.getAuthEventHandlerFinisher =\n function(mode, opt_eventId) {};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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.auth.AuthSettings structure.\n */\n\ngoog.provide('fireauth.AuthSettings');\n\n\n/**\n * The class used to initialize an Auth settings object currently used to\n * enable or disable app verification for testing.\n * @constructor\n */\nfireauth.AuthSettings = function() {\n this.appVerificationDisabledForTesting_ = false;\n Object.defineProperty(\n /** @type {!Object} */ (this),\n 'appVerificationDisabled',\n {\n /**\n * @this {!Object}\n * @return {boolean} The current status.\n */\n get: function() {\n return this.getAppVerificationDisabledForTesting();\n },\n /**\n * @this {!Object}\n * @param {boolean} value The new status.\n */\n set: function(value) {\n this.setAppVerificationDisabledForTesting(value);\n },\n enumerable: false\n });\n};\n\n\n/**\n * Sets whether app verification is disable for testing.\n * @param {boolean} status App verification status for testing.\n */\nfireauth.AuthSettings.prototype.setAppVerificationDisabledForTesting =\n function(status) {\n this.appVerificationDisabledForTesting_ = status;\n};\n\n\n/**\n * @return {boolean} Whether app verification is enabled or disabled for\n * testing.\n */\nfireauth.AuthSettings.prototype.getAppVerificationDisabledForTesting =\n function() {\n return this.appVerificationDisabledForTesting_;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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.auth.ConfirmationResult. This is needed\n * to provide first class support for phone Auth API: signInWithPhoneNumber,\n * linkWithPhoneNumber and reauthenticateWithPhoneNumber.\n */\n\ngoog.provide('fireauth.ConfirmationResult');\n\ngoog.require('fireauth.PhoneAuthProvider');\ngoog.require('fireauth.object');\ngoog.require('goog.Promise');\n\n\n/**\n * The confirmation result class. This takes in the verification ID returned\n * from the phone Auth provider and the credential resolver to run when\n * confirming with a verification code.\n * @param {string} verificationId The verification ID returned from the Phone\n * Auth provider after sending the verification code.\n * @param {!function(!fireauth.AuthCredential):\n * !goog.Promise<!fireauth.AuthEventManager.Result>} credentialResolver a\n * function that takes in an AuthCredential and returns a promise that\n * resolves with a UserCredential object.\n * @constructor\n */\nfireauth.ConfirmationResult = function(verificationId, credentialResolver) {\n /**\n * @const @private {!function(!fireauth.AuthCredential):\n * !goog.Promise<!fireauth.AuthEventManager.Result>} A function that takes\n * in an AuthCredential and returns a promise that resolves with a\n * UserCredential object.\n */\n this.credentialResolver_ = credentialResolver;\n // Set verificationId as read-only property.\n fireauth.object.setReadonlyProperty(this, 'verificationId', verificationId);\n};\n\n\n/**\n * Confirms the verification code and returns a promise that resolves with the\n * User Credential object.\n * @param {string} verificationCode The phone Auth verification code to use to\n * complete the Auth flow.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.ConfirmationResult.prototype.confirm = function(verificationCode) {\n // Initialize a phone Auth credential with the verification ID and code.\n var credential = fireauth.PhoneAuthProvider.credential(\n this['verificationId'], verificationCode);\n // Run the credential resolver with the phone Auth credential and return its\n // result.\n return this.credentialResolver_(credential);\n};\n\n\n/**\n * Initializes a ConfirmationResult using the provided phone number, app\n * verifier and returns it asynchronously. On code confirmation, the result will\n * resolve using the credential resolver provided.\n * @param {!fireauth.Auth} auth The corresponding Auth instance.\n * @param {string} phoneNumber The phone number to authenticate with.\n * @param {!firebase.auth.ApplicationVerifier} appVerifier The application\n * verifier.\n * @param {!function(!fireauth.AuthCredential):\n * !goog.Promise<!fireauth.AuthEventManager.Result>} credentialResolver a\n * function that takes in an AuthCredential and returns a promise that\n * resolves with a UserCredential object.\n * @return {!goog.Promise<!fireauth.ConfirmationResult>}\n */\nfireauth.ConfirmationResult.initialize =\n function(auth, phoneNumber, appVerifier, credentialResolver) {\n // Initialize a phone Auth provider instance using the provided Auth\n // instance.\n var phoneAuthProvider = new fireauth.PhoneAuthProvider(auth);\n // Verify the phone number.\n return phoneAuthProvider.verifyPhoneNumber(phoneNumber, appVerifier)\n .then(function(verificationId) {\n // When code is sent and verification ID is returned, initialize a\n // ConfirmationResult with the returned verification ID and credential\n // resolver, and return that instance.\n return new fireauth.ConfirmationResult(\n verificationId, credentialResolver);\n });\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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.auth.IdTokenResult class that is obtained\n * from getIdTokenResult. It contains the ID token JWT string and other helper\n * properties for getting different data associated with the token as well as\n * all the decoded payload claims.\n */\n\ngoog.provide('fireauth.IdTokenResult');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.IdToken');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.object');\ngoog.require('fireauth.util');\n\n\n\n/**\n * This is the ID token result object obtained from getIdTokenResult. It\n * contains the ID token JWT string and other helper properties for getting\n * different data associated with the token as well as all the decoded payload\n * claims.\n * @param {string} tokenString The JWT token.\n * @constructor\n */\nfireauth.IdTokenResult = function(tokenString) {\n var idToken = fireauth.IdToken.parseIdTokenClaims(tokenString);\n if (!idToken || !idToken['exp'] || !idToken['auth_time'] || !idToken['iat']) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'An internal error occurred. The token obtained by Firebase appears ' +\n 'to be malformed. Please retry the operation.');\n }\n fireauth.object.setReadonlyProperties(this, {\n 'token': tokenString,\n 'expirationTime': fireauth.util.utcTimestampToDateString(\n idToken['exp'] * 1000),\n 'authTime': fireauth.util.utcTimestampToDateString(\n idToken['auth_time'] * 1000),\n 'issuedAtTime': fireauth.util.utcTimestampToDateString(\n idToken['iat'] * 1000),\n 'signInProvider': (idToken['firebase'] &&\n idToken['firebase']['sign_in_provider']) ?\n idToken['firebase']['sign_in_provider'] : null,\n 'signInSecondFactor': (idToken['firebase'] &&\n idToken['firebase']['sign_in_second_factor']) ?\n idToken['firebase']['sign_in_second_factor'] : null,\n 'claims': idToken\n });\n};\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 multi-factor resolver class used to facilitate\n * recovery when a multi-factor user tries to sign-in with a first factor.\n */\n\ngoog.provide('fireauth.MultiFactorResolver');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.MultiFactorInfo');\ngoog.require('fireauth.MultiFactorSession');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.object');\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n/**\n * Initializes a `MultiFactorResolver` instance. This is used when a\n * multi-factor user signs in with the first factor but is required to provide\n * a second factor assertion before completing sign-in.\n *\n * @param {!fireauth.Auth} auth The Auth instance.\n * @param {!fireauth.MultiFactorResolver.ErrorResponse} errorResponse The server\n * error response containing the pending multi-factor credential.\n * @param {function({idToken: string, refreshToken: string}):\n * !goog.Promise<!fireauth.AuthEventManager.Result>} onIdTokenResolver\n * A function that takes the assertion token response and any previous\n * information returned with the error and completes sign in with a\n * `UserCredential`.\n * @constructor\n */\nfireauth.MultiFactorResolver = function(\n auth, errorResponse, onIdTokenResolver) {\n var pendingCredential = errorResponse && errorResponse[\n fireauth.MultiFactorResolver.SignInResponseField.MFA_PENDING_CREDENTIAL];\n if (!pendingCredential) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n 'Internal assert: Invalid MultiFactorResolver');\n }\n /** @const @private {!fireauth.Auth} The Auth instance. */\n this.auth_ = auth;\n /**\n * @const @private {!fireauth.MultiFactorResolver.ErrorResponse} The server\n * error response with the pending credential.\n */\n this.errorResponse_ = goog.object.clone(errorResponse);\n /**\n * @const @private {function({idToken: string, refreshToken: string}):\n * !goog.Promise<!fireauth.AuthEventManager.Result>} The ID\n * token resolver.\n */\n this.onIdTokenResolver_ = onIdTokenResolver;\n /**\n * @const @private {!fireauth.MultiFactorSession} The corresponding\n * multi-factor session.\n */\n this.session_ = new fireauth.MultiFactorSession(\n null,\n pendingCredential);\n /**\n * @const @private {!Array<!fireauth.MultiFactorInfo>} The list of\n * multi-factor hints corresponding to the current user session.\n */\n this.hints_ = [];\n var enrollmentList = errorResponse[\n fireauth.MultiFactorResolver.SignInResponseField.MFA_INFO] || [];\n var self = this;\n goog.array.forEach(enrollmentList, function(mfaEnrollment) {\n var info = fireauth.MultiFactorInfo.fromServerResponse(mfaEnrollment);\n if (info) {\n self.hints_.push(info);\n }\n });\n fireauth.object.setReadonlyProperty(this, 'auth', this.auth_);\n fireauth.object.setReadonlyProperty(this, 'session', this.session_);\n fireauth.object.setReadonlyProperty(\n this, 'hints', this.hints_);\n};\n\n\n/**\n * The server side error response on multi-factor sign-in.\n * @typedef {{\n * mfaInfo: (?Array<!Object>|undefined),\n * mfaPendingCredential: (?string|undefined)\n * }}\n */\nfireauth.MultiFactorResolver.ErrorResponse;\n\n/**\n * Sign in response fields for multi-factor sign-in.\n * @enum {string}\n */\nfireauth.MultiFactorResolver.SignInResponseField = {\n MFA_INFO: 'mfaInfo',\n MFA_PENDING_CREDENTIAL: 'mfaPendingCredential'\n};\n\n\n/**\n * Completes the second factor sign-in with the multi-factor assertion provided\n * and returns a promise that resolves with the `UserCredential` object.\n *\n * @param {!fireauth.MultiFactorAssertion} assertion The multi-factor assertion\n * to resolve sign-in with.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>} A promise that\n * resolves with the `UserCredential` after ID token processing.\n */\nfireauth.MultiFactorResolver.prototype.resolveSignIn = function(assertion) {\n var self = this;\n return assertion.process(this.auth_.getRpcHandler(), this.session_)\n .then(function(result) {\n var newSignInResponse = goog.object.clone(self.errorResponse_);\n // These fields are no longer needed.\n delete newSignInResponse[\n fireauth.MultiFactorResolver.SignInResponseField.MFA_INFO];\n delete newSignInResponse[fireauth.MultiFactorResolver\n .SignInResponseField.MFA_PENDING_CREDENTIAL];\n goog.object.extend(newSignInResponse, result);\n // Return ID token/refresh token result and the original error response.\n // This is needed as the original server response may contain additional\n // data such as OAuth credentials, raw user info, etc that needs to be\n // returned to the developer on successful sign-in.\n return self.onIdTokenResolver_(\n /** @type {{idToken: string, refreshToken: string}} */ (\n newSignInResponse));\n });\n};\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 MultiFactorError class, a subclass of\n * fireauth.AuthError.\n */\n\n\ngoog.provide('fireauth.MultiFactorError');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.MultiFactorResolver');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.object');\ngoog.require('goog.object');\n\n\n/**\n * Multi-factor error with resolver, used to resolve sign-in after a two-factor\n * user signs in with a first factor and is required to prove ownership of the\n * second factor.\n * @param {!fireauth.Auth} auth The Auth instance.\n * @param {!fireauth.MultiFactorResolver.ErrorResponse} errorResponse The server\n * error response containing the pending multi-factor credential.\n * @param {function({idToken: string, refreshToken: string}):\n * !goog.Promise<!fireauth.AuthEventManager.Result>} onIdTokenResolver\n * A function that takes the assertion token response and any previous\n * information returned with the error and completes sign in with a\n * `UserCredential`.\n * @param {string=} message The optional custom human-readable message. If not\n * provided, a default message will be used.\n * @constructor\n * @extends {fireauth.AuthError}\n */\nfireauth.MultiFactorError = function(\n auth, errorResponse, onIdTokenResolver, message) {\n fireauth.MultiFactorError.base(\n this,\n 'constructor',\n fireauth.authenum.Error.MFA_REQUIRED,\n message,\n errorResponse);\n this.serverResponse_ = goog.object.clone(errorResponse);\n /**\n * @const @private {!fireauth.MultiFactorResolver} The multi-factor resolver\n * instance.\n */\n this.resolver_ =\n new fireauth.MultiFactorResolver(auth, errorResponse, onIdTokenResolver);\n fireauth.object.setReadonlyProperty(this, 'resolver', this.resolver_);\n};\ngoog.inherits(fireauth.MultiFactorError, fireauth.AuthError);\n\n\n/**\n * Initializes a `MultiFactorError` from the plain object provided. If the\n * object is not a valid `MultiFactorError`, null is returned.\n * @param {?Object|undefined} response The object response to convert to a\n * fireauth.MultiFactorError.\n * @param {!fireauth.Auth} auth The Auth instance.\n * @param {function({idToken: string, refreshToken: string}):\n * !goog.Promise<!fireauth.AuthEventManager.Result>} onIdTokenResolver\n * A function that takes the assertion token response and any previous\n * information returned with the error and completes sign in with a\n * `UserCredential`.\n * @return {?fireauth.MultiFactorError} The `MultiFactorError` error\n * representation of the response. null is returned if the response is not\n * a valid MultiFactorError plain object representation.\n */\nfireauth.MultiFactorError.fromPlainObject =\n function(response, auth, onIdTokenResolver) {\n if (response &&\n goog.isObject(response['serverResponse']) &&\n response['code'] === 'auth/' + fireauth.authenum.Error.MFA_REQUIRED) {\n try {\n return new fireauth.MultiFactorError(\n auth,\n /** @type {!fireauth.MultiFactorResolver.ErrorResponse} */ (\n response['serverResponse']),\n onIdTokenResolver,\n response['message']);\n } catch (e) {\n return null;\n }\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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.auth.MultiFactorAssertion` abstract class\n * and all its subclasses, such as PhoneMultiFactorAssertion.\n */\n\ngoog.provide('fireauth.AuthCredentialMultiFactorAssertion');\ngoog.provide('fireauth.MultiFactorAssertion');\ngoog.provide('fireauth.PhoneMultiFactorAssertion');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.MultiFactorAuthCredential');\ngoog.require('fireauth.MultiFactorSession');\ngoog.require('fireauth.PhoneAuthProvider');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.object');\n\n\n/**\n * Abstract class representing a `firebase.auth.MultiFactorAssertion` interface.\n * This is used to facilitate enrollment of a second factor on an existing user\n * or sign-in of a user who already verified the first factor.\n * @abstract\n * @constructor\n */\nfireauth.MultiFactorAssertion = function() {};\n\n\n/**\n * Finalizes the 2nd factor enrollment flow with the current\n * MultiFactorAssertion.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorEnrollmentRequestIdentifier} enrollmentRequest\n * The enrollment request identifying the user.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the updated ID and refresh tokens.\n * @protected\n */\nfireauth.MultiFactorAssertion.prototype.finalizeEnrollmentWithVerificationInfo =\n goog.abstractMethod;\n\n\n/**\n * Finalizes the 2nd factor sign-in flow with the current MultiFactorAssertion.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorSignInRequestIdentifier} signInRequest\n * The sign-in request identifying the user.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the signed in user's ID and refresh tokens.\n * @protected\n */\nfireauth.MultiFactorAssertion.prototype.finalizeSignInWithVerificationInfo =\n goog.abstractMethod;\n\n\n/**\n * Processes the `MultiFactorAssertion` instance using the `MultiFactorSession`\n * provided and optional display name for enrollment flows.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorSession} session The multi-factor session\n * instance.\n * @param {?string=} displayName The optional display name for a multi-factor\n * enrollment.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the signed in or enrolled user's ID and refresh\n * tokens.\n */\nfireauth.MultiFactorAssertion.prototype.process =\n function(rpcHandler, session, displayName) {\n // Session obtained from user in enroll.\n // It is obtained from error in resolver.\n if (session.type == fireauth.MultiFactorSession.Type.ENROLL) {\n return this.finalizeMfaEnrollment_(rpcHandler, session, displayName);\n } else {\n return this.finalizeMfaSignIn_(rpcHandler, session);\n }\n};\n\n\n/**\n * Finalizes the multi-factor enrollment.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorSession} session The multi-factor session for\n * the current signed in user.\n * @param {?string=} displayName The optional display name for a multi-factor\n * enrollment.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the enrolled user's ID and refresh tokens.\n * @private\n */\nfireauth.MultiFactorAssertion.prototype.finalizeMfaEnrollment_ =\n function(rpcHandler, session, displayName) {\n var self = this;\n return session.getRawSession().then(function(rawSession) {\n var request = {\n 'idToken': rawSession\n };\n if (typeof displayName !== 'undefined') {\n request['displayName'] = displayName;\n }\n return self.finalizeEnrollmentWithVerificationInfo(rpcHandler, request);\n });\n};\n\n\n/**\n * Finalizes the multi-factor sign-in.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorSession} session The multi-factor session for\n * the multi-factor enrolled user trying to sign-in.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the signed in user's ID and refresh tokens.\n * @private\n */\nfireauth.MultiFactorAssertion.prototype.finalizeMfaSignIn_ =\n function(rpcHandler, session) {\n var self = this;\n return session.getRawSession().then(function(rawSession) {\n var request = {\n 'mfaPendingCredential': rawSession,\n };\n return self.finalizeSignInWithVerificationInfo(rpcHandler, request);\n });\n};\n\n\n/**\n * Defines a class for handling MultiFactorAssertions based on\n * `MultiFactorAuthCredentials`.\n * @param {!fireauth.MultiFactorAuthCredential} multiFactorAuthCredential The\n * multi-factor AuthCredential.\n * @constructor\n * @extends {fireauth.MultiFactorAssertion}\n */\nfireauth.AuthCredentialMultiFactorAssertion =\n function(multiFactorAuthCredential) {\n // This assumes the factor ID matches the credential providerId.\n // If this is ever not true, the subclass can overwrite that.\n fireauth.object.setReadonlyProperty(\n this, 'factorId', multiFactorAuthCredential.providerId);\n /**\n * @protected {!fireauth.MultiFactorAuthCredential} The underlying\n * multi-factor AuthCredential.\n */\n this.multiFactorAuthCredential = multiFactorAuthCredential;\n};\ngoog.inherits(\n fireauth.AuthCredentialMultiFactorAssertion, fireauth.MultiFactorAssertion);\n\n\n/**\n * Finalizes the 2nd factor enrollment flow with the current\n * MultiFactorAssertion.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorEnrollmentRequestIdentifier} enrollmentRequest\n * The enrollment request identifying the user.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the updated ID and refresh tokens.\n * @protected\n * @override\n */\nfireauth.AuthCredentialMultiFactorAssertion.prototype\n .finalizeEnrollmentWithVerificationInfo = function(rpcHandler,\n enrollmentRequest) {\n return this.multiFactorAuthCredential.finalizeMfaEnrollment(\n rpcHandler, enrollmentRequest);\n};\n\n\n/**\n * Finalizes the 2nd factor sign-in flow with the current MultiFactorAssertion.\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler instance.\n * @param {!fireauth.MultiFactorSignInRequestIdentifier} signInRequest\n * The sign-in request identifying the user.\n * @return {!goog.Promise<{idToken: string, refreshToken: string}>} A promise\n * that resolves with the signed in user's ID and refresh tokens.\n * @protected\n * @override\n */\nfireauth.AuthCredentialMultiFactorAssertion.prototype\n .finalizeSignInWithVerificationInfo = function(rpcHandler,\n signInRequest) {\n return this.multiFactorAuthCredential.finalizeMfaSignIn(\n rpcHandler, signInRequest);\n};\n\n\n/**\n * Defines a class for handling MultiFactorAssertions based on\n * PhoneAuthCredentials. This class extends `AuthCredentialMultiFactorAssertion`\n * but for `PhoneAuthCredentials` only.\n * @param {!fireauth.PhoneAuthCredential} phoneAuthCredential\n * @constructor\n * @extends {fireauth.AuthCredentialMultiFactorAssertion}\n */\nfireauth.PhoneMultiFactorAssertion = function(phoneAuthCredential) {\n fireauth.PhoneMultiFactorAssertion.base(\n this, 'constructor', phoneAuthCredential);\n // This class supports phone credentials only.\n if (this.multiFactorAuthCredential.providerId !=\n fireauth.PhoneAuthProvider['PROVIDER_ID']) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n 'firebase.auth.PhoneMultiFactorAssertion requires a valid ' +\n 'firebase.auth.PhoneAuthCredential');\n }\n};\ngoog.inherits(\n fireauth.PhoneMultiFactorAssertion,\n fireauth.AuthCredentialMultiFactorAssertion);\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.UserEvent and fireauth.UserEventType.\n */\n\ngoog.provide('fireauth.UserEvent');\ngoog.provide('fireauth.UserEventType');\n\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\n\n\n/**\n * User custom event.\n * @param {string} type The event type.\n * @param {?Object=} properties The optional properties to set to the custom\n * event using same keys as object provided.\n * @constructor\n * @extends {goog.events.Event}\n */\nfireauth.UserEvent = function(type, properties) {\n goog.events.Event.call(this, type);\n // If optional properties provided.\n // Add each property to custom event.\n for (var key in properties) {\n this[key] = properties[key];\n }\n};\ngoog.inherits(fireauth.UserEvent, goog.events.Event);\n\n\n/**\n * Events dispatched by the user.\n * @enum {string}\n */\nfireauth.UserEventType = {\n /** Dispatched when token is changed due to Auth event. */\n TOKEN_CHANGED: 'tokenChanged',\n\n /** Dispatched when user is deleted. */\n USER_DELETED: 'userDeleted',\n\n /**\n * Dispatched when user session is invalidated. This could happen when the\n * following errors occur: user-disabled or user-token-expired.\n */\n USER_INVALIDATED: 'userInvalidated',\n\n /** Dispatched when the user is reloaded. */\n USER_RELOADED: 'userReloaded'\n};\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 `MultiFactorUser` class used to retrieve the\n * enrolled second factors on a user and to facilitate enrollment and\n * unenrollment of second factors.\n */\n\ngoog.provide('fireauth.MultiFactorUser');\n\ngoog.require('fireauth.MultiFactorAssertion');\ngoog.require('fireauth.MultiFactorInfo');\ngoog.require('fireauth.MultiFactorSession');\ngoog.require('fireauth.UserEventType');\ngoog.require('fireauth.object');\ngoog.require('goog.array');\ngoog.require('goog.events');\n\n\n/**\n * Initializes the multi-factor instance corresponding to a signed in user.\n * This provides the ability to retrieve the enrolled second factors for that\n * user, as well as the ability to enroll new second factors or unenroll\n * existing ones.\n * @param {!fireauth.AuthUser} user The user the multi-factor instance\n * represents.\n * @param {?fireauth.AuthUser.AccountInfo=} accountInfo The optional user\n * account info.\n * @constructor\n */\nfireauth.MultiFactorUser = function(user, accountInfo) {\n /**\n * @private {!fireauth.AuthUser} The user this multi-factor instance\n * represents.\n */\n this.user_ = user;\n /** @private {!Array<!fireauth.MultiFactorInfo>} The enrolled factors. */\n this.enrolledFactors_ = [];\n /**\n * @const @private {function({userServerResponse: !Object})} The handler for\n * user reload events.\n */\n this.userReloadedListener_ = goog.bind(this.handleUserReload_, this);\n goog.events.listen(\n this.user_,\n fireauth.UserEventType.USER_RELOADED,\n this.userReloadedListener_);\n var enrolledFactors = [];\n // AccountInfo is typically loaded from storage where it is stored in plain\n // object format. Otherwise, the enrolled factors will be loaded from\n // getAccountInfo response triggered by user reload event.\n if (accountInfo &&\n accountInfo['multiFactor'] &&\n accountInfo['multiFactor']['enrolledFactors']) {\n var enrolledFactorsPlainObject =\n accountInfo['multiFactor']['enrolledFactors'];\n goog.array.forEach(enrolledFactorsPlainObject, function(mfaEnrollment) {\n var info = fireauth.MultiFactorInfo.fromPlainObject(mfaEnrollment);\n if (info) {\n enrolledFactors.push(info);\n }\n });\n }\n this.updateEnrolledFactors_(enrolledFactors);\n};\n\n\n/**\n * @const @private {string} The key for the list of second factor enrollments in\n * the GetAccountInfo server response.\n */\nfireauth.MultiFactorUser.GET_ACCOUNT_INFO_MFA_INFO_ = 'mfaInfo';\n\n\n/** @return {!fireauth.AuthUser} The corresponding user. */\nfireauth.MultiFactorUser.prototype.getUser = function() {\n return this.user_;\n};\n\n\n/**\n * Extracts the enrolled factors from getAccountInfo response and returns an\n * array of corresponding multi-factor info data.\n * @param {!Object} resp The GetAccountInfo response object.\n * @return {!Array<!fireauth.MultiFactorInfo>} The enrolled factors.\n * @private\n */\nfireauth.MultiFactorUser.extractEnrolledFactors_ = function(resp) {\n // Parse MFA enrollments.\n var mfaInfo = resp[fireauth.MultiFactorUser.GET_ACCOUNT_INFO_MFA_INFO_] || [];\n var enrolledFactors = [];\n goog.array.forEach(mfaInfo, function(mfaEnrollment) {\n var info = fireauth.MultiFactorInfo.fromServerResponse(mfaEnrollment);\n if (info) {\n enrolledFactors.push(info);\n }\n });\n return enrolledFactors;\n};\n\n\n/**\n * Handles user reload event. This will parse the enrollments from the\n * response and update them on the current multi-factor instance.\n * @param {{userServerResponse: !Object}} event The user reload event.\n * @private\n */\nfireauth.MultiFactorUser.prototype.handleUserReload_ = function(event) {\n this.updateEnrolledFactors_(fireauth.MultiFactorUser.extractEnrolledFactors_(\n event.userServerResponse));\n};\n\n\n/**\n * Updates the enrolledFactors property.\n * @param {!Array<!fireauth.MultiFactorInfo>} enrolledFactors The new list of\n * `MultiFactorInfo` objects on the user.\n * @private\n */\nfireauth.MultiFactorUser.prototype.updateEnrolledFactors_ =\n function(enrolledFactors) {\n this.enrolledFactors_ = enrolledFactors;\n fireauth.object.setReadonlyProperty(\n this, 'enrolledFactors', enrolledFactors);\n};\n\n\n/**\n * Copies the list of enrolled factors on the user. This facilitates copying a\n * user to another user. The underlying user reference is not updated.\n * @param {!fireauth.MultiFactorUser} multiFactorUser The instance to copy.\n */\nfireauth.MultiFactorUser.prototype.copy = function(multiFactorUser) {\n this.updateEnrolledFactors_(multiFactorUser.enrolledFactors_);\n};\n\n\n/**\n * Provides a multi-factor session used to start a multi-factor enrollment flow.\n * @return {!goog.Promise<!fireauth.MultiFactorSession>} A promise that resolves\n * with a multi-factor session.\n */\nfireauth.MultiFactorUser.prototype.getSession = function() {\n return this.user_.getIdToken()\n .then(function(idToken) {\n return new fireauth.MultiFactorSession(idToken, null);\n });\n};\n\n\n/**\n * Enrolls a second factor as identified by the multi-factor assertion for\n * the current user.\n * @param {!fireauth.MultiFactorAssertion} assertion The multi-factor assertion.\n * @param {?string=} displayName The optional display name used to identify\n * the 2nd factor to the end user.\n * @return {!goog.Promise<void>} A promise that resolves when the second factor\n * is enrolled.\n */\nfireauth.MultiFactorUser.prototype.enroll = function(assertion, displayName) {\n var self = this;\n var rpcHandler = this.user_.getRpcHandler();\n return this.getSession().then(function(session) {\n return assertion.process(rpcHandler, session, displayName);\n }).then(function(tokenResponse) {\n // New tokens will be issued after enrollment of the new second factors.\n // They need to be updated on the user.\n self.user_.updateTokensIfPresent(tokenResponse);\n // The user needs to be reloaded to get the new multi-factor information\n // from server. USER_RELOADED event will be triggered and `enrolledFactors`\n // will be updated.\n return self.user_.reload();\n });\n};\n\n\n/**\n * Removes a second factor from the current user. The factor to be removed can\n * either be identified with the corresponding MultiFactorInfo object or with\n * the second factor's uid string.\n *\n * As part of the unenrollment process, the backend may decide to log the user\n * out. If so, this will still succeed and invalidate the user's state.\n * @param {!fireauth.MultiFactorInfo|string} target The second factor to remove.\n * @return {!goog.Promise<void>}\n */\nfireauth.MultiFactorUser.prototype.unenroll = function(target) {\n var self = this;\n var uid = typeof target === 'string' ? target : target['uid'];\n var rpcHandler = this.user_.getRpcHandler();\n return this.user_.getIdToken().then(function(idToken) {\n return rpcHandler.withdrawMfa(idToken, uid);\n }).then(function(tokenResponse) {\n // Remove the second factor from the user's list.\n var enrolledFactors = goog.array.filter(self.enrolledFactors_,\n function(info) {\n return info['uid'] != uid;\n });\n self.updateEnrolledFactors_(enrolledFactors);\n // Depending on whether the backend decided to revoke the user's session,\n // the tokenResponse may be empty. If the tokens were not updated (and they\n // are now invalid), reloading the user will discover this and invalidate\n // the user's state accordingly.\n self.user_.updateTokensIfPresent(tokenResponse);\n return self.user_.reload().thenCatch(function(error) {\n if (error['code'] != 'auth/user-token-expired') {\n throw error;\n }\n });\n });\n};\n\n\n/**\n * @return {!Object} The plain object representation of the `MultiFactorUser`.\n */\nfireauth.MultiFactorUser.prototype.toPlainObject = function() {\n return {\n 'multiFactor': {\n 'enrolledFactors': goog.array.map(this.enrolledFactors_, function(info) {\n return info.toPlainObject();\n })\n }\n };\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Utility for proactive refresh with exponential backoff\n * algorithm typically used to define a retry policy for certain async\n * operations.\n */\n\ngoog.provide('fireauth.ProactiveRefresh');\n\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.Timer');\n\n\n/**\n * The helper utility used to proactively refresh a certain operation based on\n * certain constraints with an exponential backoff retrial policy when\n * specific recoverable errors occur. Typically this is used to retry an\n * operation on network errors.\n * @param {!function():!goog.Promise} operation The promise returning operation\n * to run.\n * @param {!function(*):boolean} retryPolicy A function that takes in an error\n * and returns whether a retry policy should be implemented based on the\n * error. If not, the operation will not run again.\n * @param {!function():number} getWaitDuration A function that returns the wait\n * period before running again.\n * @param {number} lowerBound The lower bound duration to wait when an error\n * occurs. This is the first interval to wait before rerunning after an\n * error is detected.\n * @param {number} upperBound The upper bound duration to wait when an error\n * keeps occurring. This upper bound should not be exceeded.\n * @param {boolean=} opt_runInBackground Whether to run in the background, when\n * the tab is not visible. If the refresh should only run when the app is\n * visible, the operation will block until the app is visible and then run.\n * @constructor @struct @final\n */\nfireauth.ProactiveRefresh = function(\n operation,\n retryPolicy,\n getWaitDuration,\n lowerBound,\n upperBound,\n opt_runInBackground) {\n /**\n * @const @private {!function():!goog.Promise} The promise returning operation\n * to run.\n */\n this.operation_ = operation;\n /**\n * @const @private {!function(*):boolean} The function that takes in an error\n * and returns whether a retry policy should be implemented based on the\n * error caught.\n */\n this.retryPolicy_ = retryPolicy;\n /**\n * @const @private {!function():number} The function that returns the wait\n * period after a successful operation before running again.\n */\n this.getWaitDuration_ = getWaitDuration;\n /**\n * @const @private {number} The lower bound duration to wait when an error\n * first occurs.\n */\n this.lowerBound_ = lowerBound;\n /**\n * @const @private {number} The upper bound duration to wait when an error\n * keeps occurring. This upper bound should not be exceeded.\n */\n this.upperBound_ = upperBound;\n /**\n * @const @private {boolean} Whether to run in the background, when the tab is\n * not visible.\n */\n this.runInBackground_ = !!opt_runInBackground;\n /**\n * @private {?goog.Promise} The pending promise for the next operation to run.\n */\n this.pending_ = null;\n /**\n * @private {number} The first wait interval when a new error occurs.\n */\n this.nextErrorWaitInterval_ = this.lowerBound_;\n // Throw an error if the lower bound is greater than upper bound.\n if (this.upperBound_ < this.lowerBound_) {\n throw new Error('Proactive refresh lower bound greater than upper bound!');\n }\n};\n\n\n/** Starts the proactive refresh based on the current configuration. */\nfireauth.ProactiveRefresh.prototype.start = function() {\n // Set the next error wait interval to the lower bound. On each consecutive\n // error, this will double in value until it reaches the upper bound.\n this.nextErrorWaitInterval_ = this.lowerBound_;\n // Start proactive refresh with clean slate (successful status).\n this.process_(true);\n};\n\n\n/**\n * Returns the wait duration before the next run depending on the last run\n * status. If the last operation has succeeded, returns the getWaitDuration()\n * response. Otherwise, doubles the last error wait interval starting from\n * lowerBound and up to upperBound.\n * @param {boolean} hasSucceeded Whether last run succeeded.\n * @return {number} The wait time for the next run.\n * @private\n */\nfireauth.ProactiveRefresh.prototype.getNextRun_ = function(hasSucceeded) {\n if (hasSucceeded) {\n // If last operation succeeded, reset next error wait interval and return\n // the default wait duration.\n this.nextErrorWaitInterval_ = this.lowerBound_;\n // Return typical wait duration interval after a successful operation.\n return this.getWaitDuration_();\n } else {\n // Get next error wait interval.\n var currentErrorWaitInterval = this.nextErrorWaitInterval_;\n // Double interval for next consecutive error.\n this.nextErrorWaitInterval_ *= 2;\n // Make sure next wait interval does not exceed the maximum upper bound.\n if (this.nextErrorWaitInterval_ > this.upperBound_) {\n this.nextErrorWaitInterval_ = this.upperBound_;\n }\n return currentErrorWaitInterval;\n }\n};\n\n\n/**\n * Processes one refresh call and sets the timer for the next call based on\n * the last recorded result.\n * @param {boolean} hasSucceeded Whether last run succeeded.\n * @private\n */\nfireauth.ProactiveRefresh.prototype.process_ = function(hasSucceeded) {\n var self = this;\n // Stop any other pending operation.\n this.stop();\n // Wait for next scheduled run based on whether an error occurred during last\n // run.\n this.pending_ = goog.Timer.promise(this.getNextRun_(hasSucceeded))\n .then(function() {\n // Block for conditions (if app is required to be visible) to be ready.\n return self.waitUntilReady_();\n })\n .then(function() {\n // Run the operation.\n return self.operation_();\n })\n .then(function() {\n // If successful, try again on next cycle with no previous error\n // passed.\n self.process_(true);\n })\n .thenCatch(function(error) {\n // If an error occurs, only rerun when the error meets the retry\n // policy.\n if (self.retryPolicy_(error)) {\n // Should retry with error to trigger exponentional backoff.\n self.process_(false);\n }\n // Any other error is considered unrecoverable. Do not try again.\n });\n};\n\n\n/**\n * Returns a promise which resolves when the current tab is visible.\n * This resolves quickly if refresh is supposed to run in the background too.\n * @return {!goog.Promise} The promise that resolves when the tab is visible or\n * that requirement is not needed.\n * @private\n */\nfireauth.ProactiveRefresh.prototype.waitUntilReady_ = function() {\n // Wait until app is in foreground if required.\n if (this.runInBackground_) {\n // If runs in background, resolve quickly.\n return goog.Promise.resolve();\n } else {\n // Wait for the app to be visible before resolving the promise.\n return fireauth.util.onAppVisible();\n }\n};\n\n\n/** Stops the proactive refresh from running again. */\nfireauth.ProactiveRefresh.prototype.stop = function() {\n // If there is a pending promise.\n if (this.pending_) {\n // Cancel the pending promise and nullify it.\n this.pending_.cancel();\n this.pending_ = null;\n }\n};\n\n\n/** @return {boolean} Whether the proactive refresh is running or not. */\nfireauth.ProactiveRefresh.prototype.isRunning = function() {\n return !!this.pending_;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 user info pertaining to an identity provider and\n * the Firebase user object.\n */\n\ngoog.provide('fireauth.AuthUser');\ngoog.provide('fireauth.AuthUser.AccountInfo');\ngoog.provide('fireauth.AuthUserInfo');\ngoog.provide('fireauth.TokenRefreshTime');\ngoog.provide('fireauth.UserMetadata');\n\ngoog.require('fireauth.ActionCodeSettings');\ngoog.require('fireauth.AdditionalUserInfo');\ngoog.require('fireauth.AuthCredential');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthEvent');\ngoog.require('fireauth.AuthEventHandler');\ngoog.require('fireauth.AuthEventManager');\ngoog.require('fireauth.AuthProvider');\ngoog.require('fireauth.ConfirmationResult');\ngoog.require('fireauth.IdTokenResult');\ngoog.require('fireauth.MultiFactorError');\ngoog.require('fireauth.MultiFactorUser');\ngoog.require('fireauth.PhoneAuthProvider');\ngoog.require('fireauth.ProactiveRefresh');\ngoog.require('fireauth.RpcHandler');\ngoog.require('fireauth.StsTokenManager');\ngoog.require('fireauth.UserEvent');\ngoog.require('fireauth.UserEventType');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.constants.AuthEventType');\ngoog.require('fireauth.deprecation');\ngoog.require('fireauth.idp');\ngoog.require('fireauth.iframeclient.IfcHandler');\ngoog.require('fireauth.object');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.array');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.object');\n\n\n\n/**\n * Initializes an instance of a user metadata object.\n * @param {?string=} opt_createdAt The optional creation date UTC timestamp.\n * @param {?string=} opt_lastLoginAt The optional last login date UTC timestamp.\n * @constructor\n */\nfireauth.UserMetadata = function(opt_createdAt, opt_lastLoginAt) {\n /** @private {?string} The created at UTC timestamp. */\n this.createdAt_ = opt_createdAt || null;\n /** @private {?string} The last login at UTC timestamp. */\n this.lastLoginAt_ = opt_lastLoginAt || null;\n fireauth.object.setReadonlyProperties(this, {\n 'lastSignInTime': fireauth.util.utcTimestampToDateString(\n opt_lastLoginAt || null),\n 'creationTime': fireauth.util.utcTimestampToDateString(\n opt_createdAt || null),\n });\n};\n\n\n/**\n * @return {!fireauth.UserMetadata} A clone of the current user metadata object.\n */\nfireauth.UserMetadata.prototype.clone = function() {\n return new fireauth.UserMetadata(this.createdAt_, this.lastLoginAt_);\n};\n\n\n/**\n * @return {!Object} The object representation of the user metadata instance.\n */\nfireauth.UserMetadata.prototype.toPlainObject = function() {\n return {\n 'lastLoginAt': this.lastLoginAt_,\n 'createdAt': this.createdAt_\n };\n};\n\n\n/**\n * Initializes an instance of the user info for an identity provider.\n * @param {string} uid The user ID.\n * @param {!fireauth.idp.ProviderId} providerId The provider ID.\n * @param {?string=} opt_email The optional user email.\n * @param {?string=} opt_displayName The optional display name.\n * @param {?string=} opt_photoURL The optional photo URL.\n * @param {?string=} opt_phoneNumber The optional phone number.\n * @constructor\n */\nfireauth.AuthUserInfo = function(\n uid,\n providerId,\n opt_email,\n opt_displayName,\n opt_photoURL,\n opt_phoneNumber) {\n fireauth.object.setReadonlyProperties(this, {\n 'uid': uid,\n 'displayName': opt_displayName || null,\n 'photoURL': opt_photoURL || null,\n 'email': opt_email || null,\n 'phoneNumber': opt_phoneNumber || null,\n 'providerId': providerId\n });\n};\n\n\n/**\n * Defines the proactive token refresh time constraints in milliseconds.\n * @enum {number}\n */\nfireauth.TokenRefreshTime = {\n /**\n * The offset time before token natural expiration to run the refresh.\n * This is currently 5 minutes.\n */\n OFFSET_DURATION: 5 * 60 * 1000,\n /**\n * This is the first retrial wait after an error. This is currently\n * 30 seconds.\n */\n RETRIAL_MIN_WAIT: 30 * 1000,\n /**\n * This is the maximum retrial wait, currently 16 minutes.\n */\n RETRIAL_MAX_WAIT: 16 * 60 * 1000\n};\n\n\n\n/**\n * The Firebase user.\n * @param {!Object} appOptions The application options.\n * @param {!Object} stsTokenResponse The server STS token response.\n * @param {?Object=} opt_accountInfo The optional user account info.\n * @constructor\n * @extends {goog.events.EventTarget}\n * @implements {fireauth.AuthEventHandler}\n */\nfireauth.AuthUser =\n function(appOptions, stsTokenResponse, opt_accountInfo) {\n /** @private {!Array<!goog.Promise<*, *>|!goog.Promise<void>>} List of pending\n * promises. */\n this.pendingPromises_ = [];\n // User is only created via Auth so API key should always be available.\n /** @private {string} The API key. */\n this.apiKey_ = /** @type {string} */ (appOptions['apiKey']);\n // This is needed to associate a user to the corresponding Auth instance.\n /** @private {string} The App name. */\n this.appName_ = /** @type {string} */ (appOptions['appName']);\n /** @private {?string} The Auth domain. */\n this.authDomain_ = appOptions['authDomain'] || null;\n var clientFullVersion = firebase.SDK_VERSION ?\n fireauth.util.getClientVersion(\n fireauth.util.ClientImplementation.JSCORE, firebase.SDK_VERSION) :\n null;\n /** @private {!fireauth.RpcHandler} The RPC handler instance. */\n this.rpcHandler_ = new fireauth.RpcHandler(\n this.apiKey_,\n // Get the client Auth endpoint used.\n fireauth.constants.getEndpointConfig(fireauth.constants.clientEndpoint),\n clientFullVersion);\n // TODO: Consider having AuthUser take a fireauth.StsTokenManager\n // instance instead of a token response but make sure lastAccessToken_ also\n // initialized at the right time. In this case initializeFromIdTokenResponse\n // will take in a token response object and convert it to an instance of\n // fireauth.StsTokenManager to properly initialize user.\n /** @private {!fireauth.StsTokenManager} The STS token manager instance. */\n this.stsTokenManager_ = new fireauth.StsTokenManager(this.rpcHandler_);\n\n this.setLastAccessToken_(\n stsTokenResponse[fireauth.RpcHandler.AuthServerField.ID_TOKEN]);\n // STS token manager will always be populated using server response.\n this.stsTokenManager_.parseServerResponse(stsTokenResponse);\n fireauth.object.setReadonlyProperty(\n this, 'refreshToken', this.stsTokenManager_.getRefreshToken());\n this.setAccountInfo(/** @type {!fireauth.AuthUser.AccountInfo} */ (\n opt_accountInfo || {}));\n // Add call to superclass constructor.\n fireauth.AuthUser.base(this, 'constructor');\n /** @private {boolean} Whether popup and redirect is enabled on the user. */\n this.popupRedirectEnabled_ = false;\n if (this.authDomain_ &&\n fireauth.AuthEventManager.ENABLED &&\n // Make sure popup and redirects are supported in the current environment.\n fireauth.util.isPopupRedirectSupported()) {\n // Get the Auth event manager associated with this user.\n this.authEventManager_ = fireauth.AuthEventManager.getManager(\n this.authDomain_, this.apiKey_, this.appName_);\n }\n /** @private {!Array<!function(!fireauth.AuthUser):!goog.Promise>} The list of\n * state change listeners. This is needed to make sure state changes are\n * resolved before resolving user API promises. For example redirect\n * operations should make sure the associated event ID is saved before\n * redirecting.\n */\n this.stateChangeListeners_ = [];\n /**\n * @private {?fireauth.AuthError} The user invalidation error if it exists.\n */\n this.userInvalidatedError_ = null;\n /**\n * @private {!fireauth.ProactiveRefresh} The reference to the proactive token\n * refresher utility for the current user.\n */\n this.proactiveRefresh_ = this.initializeProactiveRefreshUtility_();\n /**\n * @private {!function(!Object)} The handler for user token changes used to\n * realign the proactive token refresh with external token refresh calls.\n */\n this.userTokenChangeListener_ = goog.bind(this.handleUserTokenChange_, this);\n var self = this;\n /** @private {?string} The current user's language code. */\n this.languageCode_ = null;\n /**\n * @private {function(!goog.events.Event)} The on language code changed event\n * handler.\n */\n this.onLanguageCodeChanged_ = function(event) {\n // Update the user language code.\n self.setLanguageCode(event.languageCode);\n };\n /**\n * @private {?goog.events.EventTarget} The language code change event\n * dispatcher.\n */\n this.languageCodeChangeEventDispatcher_ = null;\n\n /** @private {!Array<string>} The current Firebase frameworks. */\n this.frameworks_ = [];\n /**\n * @private {function(!goog.events.Event)} The on framework list changed event\n * handler.\n */\n this.onFrameworkChanged_ = function(event) {\n // Update the Firebase frameworks.\n self.setFramework(event.frameworks);\n };\n /**\n * @private {?goog.events.EventTarget} The framework change event dispatcher.\n */\n this.frameworkChangeEventDispatcher_ = null;\n /**\n * @const @private {!fireauth.MultiFactorUser} The multifactor user instance.\n */\n this.multiFactorUser_ = new fireauth.MultiFactorUser(\n this, /** @type {?fireauth.AuthUser.AccountInfo|undefined} */ (\n opt_accountInfo));\n fireauth.object.setReadonlyProperty(\n this, 'multiFactor', this.multiFactorUser_);\n};\ngoog.inherits(fireauth.AuthUser, goog.events.EventTarget);\n\n\n/**\n * Updates the user language code.\n * @param {?string} languageCode The current language code to use in user\n * requests.\n */\nfireauth.AuthUser.prototype.setLanguageCode = function(languageCode) {\n // Save current language.\n this.languageCode_ = languageCode;\n // Update the custom locale header.\n this.rpcHandler_.updateCustomLocaleHeader(languageCode);\n};\n\n\n/** @return {?string} The current user's language code. */\nfireauth.AuthUser.prototype.getLanguageCode = function() {\n return this.languageCode_;\n};\n\n\n/**\n * Listens to language code changes triggered by the provided dispatcher.\n * @param {?goog.events.EventTarget} dispatcher The language code changed event\n * dispatcher.\n */\nfireauth.AuthUser.prototype.setLanguageCodeChangeDispatcher =\n function(dispatcher) {\n // Remove any previous listener.\n if (this.languageCodeChangeEventDispatcher_) {\n goog.events.unlisten(\n this.languageCodeChangeEventDispatcher_,\n fireauth.constants.AuthEventType.LANGUAGE_CODE_CHANGED,\n this.onLanguageCodeChanged_);\n }\n // Update current dispatcher.\n this.languageCodeChangeEventDispatcher_ = dispatcher;\n // Using an event listener makes it easy for non-currentUsers to detect\n // language changes on the parent Auth instance. A developer could still call\n // APIs that require localization on signed out user references.\n if (dispatcher) {\n goog.events.listen(\n dispatcher,\n fireauth.constants.AuthEventType.LANGUAGE_CODE_CHANGED,\n this.onLanguageCodeChanged_);\n }\n};\n\n\n/**\n * Updates the Firebase frameworks on the current user.\n * @param {!Array<string>} framework The list of Firebase frameworks.\n */\nfireauth.AuthUser.prototype.setFramework = function(framework) {\n // Save current frameworks.\n this.frameworks_ = framework;\n // Update the client version in RPC handler with the new frameworks.\n this.rpcHandler_.updateClientVersion(firebase.SDK_VERSION ?\n fireauth.util.getClientVersion(\n fireauth.util.ClientImplementation.JSCORE, firebase.SDK_VERSION,\n this.frameworks_) :\n null);\n};\n\n\n/** @return {!Array<string>} The current Firebase frameworks. */\nfireauth.AuthUser.prototype.getFramework = function() {\n return goog.array.clone(this.frameworks_);\n};\n\n\n/**\n * Listens to framework changes triggered by the provided dispatcher.\n * @param {?goog.events.EventTarget} dispatcher The framework changed event\n * dispatcher.\n */\nfireauth.AuthUser.prototype.setFrameworkChangeDispatcher =\n function(dispatcher) {\n // Remove any previous listener.\n if (this.frameworkChangeEventDispatcher_) {\n goog.events.unlisten(\n this.frameworkChangeEventDispatcher_,\n fireauth.constants.AuthEventType.FRAMEWORK_CHANGED,\n this.onFrameworkChanged_);\n }\n // Update current dispatcher.\n this.frameworkChangeEventDispatcher_ = dispatcher;\n // Using an event listener makes it easy for non-currentUsers to detect\n // framework changes on the parent Auth instance.\n if (dispatcher) {\n goog.events.listen(\n dispatcher,\n fireauth.constants.AuthEventType.FRAMEWORK_CHANGED,\n this.onFrameworkChanged_);\n }\n};\n\n\n/**\n * Handles user token changes. Currently used to realign the proactive token\n * refresh internal timing with successful external token refreshes.\n * @param {!Object} event The token change event.\n * @private\n */\nfireauth.AuthUser.prototype.handleUserTokenChange_ = function(event) {\n // If an external service refreshes the token, reset the proactive token\n // refresh utility in case it is still running so the next run time is\n // up to date.\n // This will currently also trigger when the proactive refresh succeeds.\n // This is not ideal but should not have any downsides. It just adds a\n // redundant reset which can be optimized not to run in the future.\n if (this.proactiveRefresh_.isRunning()) {\n this.proactiveRefresh_.stop();\n this.proactiveRefresh_.start();\n }\n};\n\n\n/**\n * @return {!fireauth.Auth} The corresponding Auth instance that created the\n * current user.\n * @private\n */\nfireauth.AuthUser.prototype.getAuth_ = function() {\n try {\n // Get the Auth instance for the current app identified by the App name.\n // This could fail if, for example, the App instance was deleted.\n return firebase['app'](this.appName_)['auth']();\n } catch (e) {\n // Throw appropriate error.\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'No firebase.auth.Auth instance is available for the Firebase App ' +\n '\\'' + this.appName_ + '\\'!');\n }\n};\n\n\n/**\n * @return {string} The user's API key.\n */\nfireauth.AuthUser.prototype.getApiKey = function() {\n return this.apiKey_;\n};\n\n\n/**\n * Returns the RPC handler of the user.\n * @return {!fireauth.RpcHandler} The RPC handler.\n */\nfireauth.AuthUser.prototype.getRpcHandler = function() {\n return this.rpcHandler_;\n};\n\n\n/**\n * Used to initialize the current user's proactive token refresher utility.\n * @return {!fireauth.ProactiveRefresh} The user's proactive token refresh\n * utility.\n * @private\n */\nfireauth.AuthUser.prototype.initializeProactiveRefreshUtility_ = function() {\n var self = this;\n return new fireauth.ProactiveRefresh(\n // Force ID token refresh right before expiration.\n function() {\n // Keep in mind when this fails for any reason other than a network\n // error, it will effectively stop the proactive refresh.\n return self.getIdToken(true);\n },\n // Retry only on network errors.\n function(error) {\n if (error && error.code == 'auth/network-request-failed') {\n return true;\n }\n return false;\n },\n // Return next time to run with offset applied.\n function() {\n // Get time until expiration minus the refresh offset.\n var waitInterval =\n self.stsTokenManager_.getExpirationTime() - goog.now() -\n fireauth.TokenRefreshTime.OFFSET_DURATION;\n // Set to zero if wait interval is negative.\n return waitInterval > 0 ? waitInterval : 0;\n },\n // Retrial minimum wait.\n fireauth.TokenRefreshTime.RETRIAL_MIN_WAIT,\n // Retrial maximum wait.\n fireauth.TokenRefreshTime.RETRIAL_MAX_WAIT,\n // Do not run in background as it is common to have multiple tabs open\n // in a browser and this could increase QPS on server.\n false);\n};\n\n\n/** Starts token proactive refresh. */\nfireauth.AuthUser.prototype.startProactiveRefresh = function() {\n // Only allow if not destroyed and not already started.\n if (!this.destroyed_ && !this.proactiveRefresh_.isRunning()) {\n this.proactiveRefresh_.start();\n // Unlisten any previous token change listener.\n goog.events.unlisten(\n this,\n fireauth.UserEventType.TOKEN_CHANGED,\n this.userTokenChangeListener_);\n // Listen to token changes to reset the token refresher.\n goog.events.listen(\n this,\n fireauth.UserEventType.TOKEN_CHANGED,\n this.userTokenChangeListener_);\n }\n};\n\n\n/** Stops token proactive refresh. */\nfireauth.AuthUser.prototype.stopProactiveRefresh = function() {\n // Remove internal token change listener.\n goog.events.unlisten(\n this,\n fireauth.UserEventType.TOKEN_CHANGED,\n this.userTokenChangeListener_);\n // Stop proactive token refresh.\n this.proactiveRefresh_.stop();\n};\n\n\n/**\n * Sets latest access token for the AuthUser object.\n * @param {string} lastAccessToken\n * @private\n */\nfireauth.AuthUser.prototype.setLastAccessToken_ = function(lastAccessToken) {\n /** @private {?string} Latest access token. */\n this.lastAccessToken_ = lastAccessToken;\n fireauth.object.setReadonlyProperty(this, '_lat', lastAccessToken);\n};\n\n\n/**\n * @param {function(!fireauth.AuthUser):!goog.Promise} listener The listener\n * to state changes to add.\n */\nfireauth.AuthUser.prototype.addStateChangeListener = function(listener) {\n this.stateChangeListeners_.push(listener);\n};\n\n\n/**\n * @param {function(!fireauth.AuthUser):!goog.Promise} listener The listener\n * to state changes to remove.\n */\nfireauth.AuthUser.prototype.removeStateChangeListener = function(listener) {\n goog.array.removeAllIf(this.stateChangeListeners_, function(ele) {\n return ele == listener;\n });\n};\n\n\n/**\n * Executes all state change listener promises and when all fulfilled, resolves\n * with the current user.\n * @return {!goog.Promise} A promise that resolves when all state listeners\n * fulfilled.\n * @private\n */\nfireauth.AuthUser.prototype.notifyStateChangeListeners_ = function() {\n var promises = [];\n var self = this;\n for (var i = 0; i < this.stateChangeListeners_.length; i++) {\n // Run listener with Auth user instance and add to list of promises.\n promises.push(this.stateChangeListeners_[i](this));\n }\n return goog.Promise.allSettled(promises).then(function(results) {\n // State change errors should be recoverable even if errors occur.\n return self;\n });\n};\n\n\n/**\n * Sets the user current pending popup event ID.\n * @param {string} eventId The pending popup event ID.\n */\nfireauth.AuthUser.prototype.setPopupEventId = function(eventId) {\n // Saving a popup event in a separate property other than redirectEventId\n // would prevent a pending redirect event from being overwritten by a newly\n // called popup operation.\n this.popupEventId_ = eventId;\n};\n\n\n/**\n * @return {?string} The pending popup event ID.\n */\nfireauth.AuthUser.prototype.getPopupEventId = function() {\n return this.popupEventId_ || null;\n};\n\n\n/**\n * Sets the user current pending redirect event ID.\n * @param {string} eventId The pending redirect event ID.\n */\nfireauth.AuthUser.prototype.setRedirectEventId = function(eventId) {\n this.redirectEventId_ = eventId;\n};\n\n\n/**\n * @return {?string} The pending redirect event ID.\n */\nfireauth.AuthUser.prototype.getRedirectEventId = function() {\n return this.redirectEventId_ || null;\n};\n\n\n/**\n * Subscribes to Auth event manager to handle popup and redirect events.\n * This is an explicit operation as users could exist in temporary states. For\n * example a user change could be detected in another tab. When syncing to those\n * changes, a temporary user is retrieved from storage and then copied to\n * existing user. The temporary user should not subscribe to Auth event changes.\n */\nfireauth.AuthUser.prototype.enablePopupRedirect = function() {\n // Subscribe to Auth event manager if available.\n if (this.authEventManager_ && !this.popupRedirectEnabled_) {\n this.popupRedirectEnabled_ = true;\n this.authEventManager_.subscribe(this);\n }\n};\n\n\n/**\n * getAccountInfo users field.\n * @const {string}\n */\nfireauth.AuthUser.GET_ACCOUNT_INFO_USERS = 'users';\n\n\n/**\n * getAccountInfo response user fields.\n * @enum {string}\n */\nfireauth.AuthUser.GetAccountInfoField = {\n CREATED_AT: 'createdAt',\n DISPLAY_NAME: 'displayName',\n EMAIL: 'email',\n EMAIL_VERIFIED: 'emailVerified',\n LAST_LOGIN_AT: 'lastLoginAt',\n LOCAL_ID: 'localId',\n PASSWORD_HASH: 'passwordHash',\n PASSWORD_UPDATED_AT: 'passwordUpdatedAt',\n PHONE_NUMBER: 'phoneNumber',\n PHOTO_URL: 'photoUrl',\n PROVIDER_USER_INFO: 'providerUserInfo',\n TENANT_ID: 'tenantId'\n};\n\n\n/**\n * setAccountInfo response user fields.\n * @enum {string}\n */\nfireauth.AuthUser.SetAccountInfoField = {\n DISPLAY_NAME: 'displayName',\n EMAIL: 'email',\n PHOTO_URL: 'photoUrl',\n PROVIDER_ID: 'providerId',\n PROVIDER_USER_INFO: 'providerUserInfo'\n};\n\n\n/**\n * getAccountInfo response provider user info fields.\n * @enum {string}\n */\nfireauth.AuthUser.GetAccountInfoProviderField = {\n DISPLAY_NAME: 'displayName',\n EMAIL: 'email',\n PHOTO_URL: 'photoUrl',\n PHONE_NUMBER: 'phoneNumber',\n PROVIDER_ID: 'providerId',\n RAW_ID: 'rawId'\n};\n\n\n/**\n * verifyAssertion response fields.\n * @enum {string}\n */\nfireauth.AuthUser.VerifyAssertionField = {\n ID_TOKEN: 'idToken',\n PROVIDER_ID: 'providerId'\n};\n\n\n/** @return {!fireauth.StsTokenManager} The STS token manager instance */\nfireauth.AuthUser.prototype.getStsTokenManager = function() {\n return this.stsTokenManager_;\n};\n\n\n/**\n * Sets the user account info.\n * @param {!fireauth.AuthUser.AccountInfo} accountInfo The account information\n * from the default provider.\n */\nfireauth.AuthUser.prototype.setAccountInfo = function(accountInfo) {\n fireauth.object.setReadonlyProperties(this, {\n 'uid': accountInfo['uid'],\n 'displayName': accountInfo['displayName'] || null,\n 'photoURL': accountInfo['photoURL'] || null,\n 'email': accountInfo['email'] || null,\n 'emailVerified': accountInfo['emailVerified'] || false,\n 'phoneNumber': accountInfo['phoneNumber'] || null,\n 'isAnonymous': accountInfo['isAnonymous'] || false,\n 'tenantId': accountInfo['tenantId'] || null,\n 'metadata': new fireauth.UserMetadata(\n accountInfo['createdAt'], accountInfo['lastLoginAt']),\n 'providerData': []\n });\n // Sets the tenant ID on RPC handler. For requests with ID tokens, the source\n // of truth is the tenant ID in the ID token. If the request body has a\n // tenant ID (optional here), the backend will confirm it matches the\n // tenant ID in the ID token, otherwise throw an error. If no tenant ID is\n // passed in the request, it will be determined from the ID token.\n this.rpcHandler_.updateTenantId(this['tenantId']);\n};\n\n\n/**\n * Type specifying the parameters that can be passed to the\n * {@code fireauth.AuthUser} constructor.\n * @typedef {{\n * uid: (?string|undefined),\n * displayName: (?string|undefined),\n * photoURL: (?string|undefined),\n * email: (?string|undefined),\n * emailVerified: ?boolean,\n * phoneNumber: (?string|undefined),\n * isAnonymous: ?boolean,\n * createdAt: (?string|undefined),\n * lastLoginAt: (?string|undefined),\n * tenantId: (?string|undefined),\n * multiFactor: ({\n * enrolledFactors: (?Array<!fireauth.MultiFactorInfo>|undefined)\n * }|undefined)\n * }}\n */\nfireauth.AuthUser.AccountInfo;\n\n\n/**\n * The provider for all fireauth.AuthUser objects is 'firebase'.\n */\nfireauth.object.setReadonlyProperty(fireauth.AuthUser.prototype, 'providerId',\n fireauth.idp.ProviderId.FIREBASE);\n\n\n/**\n * Returns nothing. This can be used to consume the output of a Promise.\n * @private\n */\nfireauth.AuthUser.returnNothing_ = function() {\n // Return nothing. Intentionally left empty.\n};\n\n\n/**\n * Ensures the user is still logged in before moving to the next promise\n * resolution.\n * @return {!goog.Promise<undefined,undefined>}\n * @private\n */\nfireauth.AuthUser.prototype.checkDestroyed_ = function() {\n var self = this;\n return goog.Promise.resolve().then(function() {\n if (self.destroyed_) {\n throw new fireauth.AuthError(fireauth.authenum.Error.MODULE_DESTROYED);\n }\n });\n};\n\n\n/**\n * @return {!Array<!fireauth.idp.ProviderId>} The list of provider IDs.\n */\nfireauth.AuthUser.prototype.getProviderIds = function() {\n return goog.array.map(this['providerData'], function(userInfo) {\n return userInfo['providerId'];\n });\n};\n\n\n/**\n * Adds the provided user info to list of providers' data.\n * @param {?fireauth.AuthUserInfo} providerData Provider data to store for user.\n */\nfireauth.AuthUser.prototype.addProviderData = function(providerData) {\n if (!providerData) {\n return;\n }\n this.removeProviderData(providerData['providerId']);\n this['providerData'].push(providerData);\n};\n\n\n/**\n * @param {!fireauth.idp.ProviderId} providerId The provider ID whose\n * data should be removed.\n */\nfireauth.AuthUser.prototype.removeProviderData = function(providerId) {\n goog.array.removeAllIf(this['providerData'], function(userInfo) {\n return userInfo['providerId'] == providerId;\n });\n};\n\n\n/**\n * @param {string} propName The property name to modify.\n * @param {?string|boolean} value The new value to set.\n */\nfireauth.AuthUser.prototype.updateProperty = function(propName, value) {\n // User ID is required.\n if (propName == 'uid' && !value) {\n return;\n }\n if (this.hasOwnProperty(propName)) {\n fireauth.object.setReadonlyProperty(this, propName, value);\n }\n};\n\n\n/**\n * @param {!fireauth.AuthUser} otherUser The other user to compare to.\n * @return {boolean} True if both User objects have the same user ID.\n */\nfireauth.AuthUser.prototype.hasSameUserIdAs = function(otherUser) {\n var thisId = this['uid'];\n var thatId = otherUser['uid'];\n if (thisId === undefined || thisId === null || thisId === '' ||\n thatId === undefined || thatId === null || thatId === '') {\n return false;\n }\n return thisId == thatId;\n};\n\n\n/**\n * Copies all properties and STS token manager instance from userToCopy to\n * current user without triggering any Auth state change or token change\n * listener.\n * @param {!fireauth.AuthUser} userToCopy The updated user to overwrite current\n * user.\n */\nfireauth.AuthUser.prototype.copy = function(userToCopy) {\n var self = this;\n // Copy to self.\n if (self == userToCopy) {\n return;\n }\n fireauth.object.setReadonlyProperties(this, {\n 'uid': userToCopy['uid'],\n 'displayName': userToCopy['displayName'],\n 'photoURL': userToCopy['photoURL'],\n 'email': userToCopy['email'],\n 'emailVerified': userToCopy['emailVerified'],\n 'phoneNumber': userToCopy['phoneNumber'],\n 'isAnonymous': userToCopy['isAnonymous'],\n 'tenantId': userToCopy['tenantId'],\n 'providerData': []\n });\n // This should always be available but just in case there is a conflict with\n // a user from an older version.\n if (userToCopy['metadata']) {\n fireauth.object.setReadonlyProperty(\n this,\n 'metadata',\n /** @type{!fireauth.UserMetadata} */ (userToCopy['metadata']).clone());\n } else {\n // User to copy has no metadata. Align with that.\n fireauth.object.setReadonlyProperty(\n this, 'metadata', new fireauth.UserMetadata());\n }\n goog.array.forEach(userToCopy['providerData'], function(userInfo) {\n self.addProviderData(userInfo);\n });\n this.stsTokenManager_.copy(userToCopy.getStsTokenManager());\n fireauth.object.setReadonlyProperty(\n this, 'refreshToken', this.stsTokenManager_.getRefreshToken());\n // Copy multi-factor info to current user.\n // This should be backward compatible.\n // If the userToCopy is loaded from an older version, multiFactorUser\n // enrolled factors will be initialized empty and copied empty to current\n // multiFactorUser.\n this.multiFactorUser_.copy(userToCopy.multiFactorUser_);\n};\n\n\n/**\n * Set the Auth user redirect storage manager.\n * @param {?fireauth.storage.RedirectUserManager} redirectStorageManager The\n * utility used to store or delete the user on redirect.\n */\nfireauth.AuthUser.prototype.setRedirectStorageManager =\n function(redirectStorageManager) {\n /**\n * @private {?fireauth.storage.RedirectUserManager} The redirect user storage\n * manager.\n */\n this.redirectStorageManager_ = redirectStorageManager;\n};\n\n\n/**\n * Refreshes the current user, if signed in.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.reload = function() {\n var self = this;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(this.checkDestroyed_().then(function() {\n return self.reloadWithoutSaving_()\n .then(function() {\n return self.notifyStateChangeListeners_();\n })\n .then(fireauth.AuthUser.returnNothing_);\n }));\n};\n\n\n/**\n * Refreshes the current user, if signed in.\n * @return {!goog.Promise<string>} Promise that resolves with the idToken.\n * @private\n */\nfireauth.AuthUser.prototype.reloadWithoutSaving_ = function() {\n var self = this;\n // ID token is required to refresh the user's data.\n // If this is called after invalidation, getToken will throw the cached error.\n return this.getIdToken().then(function(idToken) {\n var isAnonymous = self['isAnonymous'];\n return self.setUserAccountInfoFromToken_(idToken)\n .then(function(user) {\n if (!isAnonymous) {\n // Preserves the not anonymous status of the stored user,\n // even if no more credentials (federated or email/password)\n // linked to the user.\n self.updateProperty('isAnonymous', false);\n }\n return idToken;\n });\n });\n};\n\n\n/**\n * This operation resolves with the Firebase ID token result which contains\n * the entire payload claims.\n * @param {boolean=} opt_forceRefresh Whether to force refresh token exchange.\n * @return {!goog.Promise<!fireauth.IdTokenResult>} A Promise that resolves with\n * the ID token result.\n */\nfireauth.AuthUser.prototype.getIdTokenResult = function(opt_forceRefresh) {\n return this.getIdToken(opt_forceRefresh).then(function(idToken) {\n return new fireauth.IdTokenResult(idToken);\n });\n};\n\n\n/**\n * This operation resolves with the Firebase ID token.\n * @param {boolean=} opt_forceRefresh Whether to force refresh token exchange.\n * @return {!goog.Promise<string>} A Promise that resolves with the ID token.\n */\nfireauth.AuthUser.prototype.getIdToken = function(opt_forceRefresh) {\n var self = this;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(this.checkDestroyed_().then(function() {\n return self.stsTokenManager_.getToken(opt_forceRefresh);\n }).then(function(response) {\n if (!response) {\n // If the user exists, the token manager should be initialized.\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n // Only if the access token is refreshed, notify Auth listeners.\n if (response['accessToken'] != self.lastAccessToken_) {\n self.setLastAccessToken_(response['accessToken']);\n // Auth state change, notify listeners.\n self.notifyAuthListeners_();\n }\n self.updateProperty('refreshToken', response['refreshToken']);\n return response['accessToken'];\n }));\n};\n\n\n/**\n * Checks if the error corresponds to a user invalidation action.\n * @param {*} error The error returned by a user operation.\n * @return {boolean} Whether the user is invalidated based on the error\n * provided.\n * @private\n */\nfireauth.AuthUser.isUserInvalidated_ = function(error) {\n return !!(error &&\n (error.code == 'auth/user-disabled' ||\n error.code == 'auth/user-token-expired'));\n};\n\n\n/**\n * Updates the current tokens using a server response, if new tokens are\n * present and are different from the current ones, and notify the Auth\n * listeners.\n * @param {!Object} response The response from the server.\n */\nfireauth.AuthUser.prototype.updateTokensIfPresent = function(response) {\n if (response[fireauth.RpcHandler.AuthServerField.ID_TOKEN] &&\n this.lastAccessToken_ != response[\n fireauth.RpcHandler.AuthServerField.ID_TOKEN]) {\n this.stsTokenManager_.parseServerResponse(response);\n this.notifyAuthListeners_();\n this.setLastAccessToken_(response[\n fireauth.RpcHandler.AuthServerField.ID_TOKEN]);\n // Update refresh token property.\n this.updateProperty(\n 'refreshToken', this.stsTokenManager_.getRefreshToken());\n }\n};\n\n\n/**\n * Called internally on Auth (access token) changes to notify listeners.\n * @private\n */\nfireauth.AuthUser.prototype.notifyAuthListeners_ = function() {\n this.dispatchEvent(\n new fireauth.UserEvent(fireauth.UserEventType.TOKEN_CHANGED));\n};\n\n\n/**\n * Called internally on user deletion to notify listeners.\n * @private\n */\nfireauth.AuthUser.prototype.notifyUserDeletedListeners_ = function() {\n this.dispatchEvent(\n new fireauth.UserEvent(fireauth.UserEventType.USER_DELETED));\n};\n\n\n/**\n * Called internally on user session invalidation to notify listeners.\n * @private\n */\nfireauth.AuthUser.prototype.notifyUserInvalidatedListeners_ = function() {\n this.dispatchEvent(\n new fireauth.UserEvent(fireauth.UserEventType.USER_INVALIDATED));\n};\n\n\n/**\n * Queries the backend using the provided ID token for all linked accounts to\n * build the Firebase user object.\n * @param {string} idToken The ID token string.\n * @return {!goog.Promise<undefined>}\n * @private\n */\nfireauth.AuthUser.prototype.setUserAccountInfoFromToken_ = function(idToken) {\n return this.rpcHandler_.getAccountInfoByIdToken(idToken)\n .then(goog.bind(this.parseAccountInfo_, this));\n};\n\n\n/**\n * Parses the response from the getAccountInfo endpoint.\n * @param {!Object} resp The backend response.\n * @private\n */\nfireauth.AuthUser.prototype.parseAccountInfo_ = function(resp) {\n var users = resp[fireauth.AuthUser.GET_ACCOUNT_INFO_USERS];\n if (!users || !users.length) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n var user = users[0];\n var accountInfo = /** @type {!fireauth.AuthUser.AccountInfo} */ ({\n 'uid': /** @type {string} */ (\n user[fireauth.AuthUser.GetAccountInfoField.LOCAL_ID]),\n 'displayName': /** @type {?string|undefined} */ (\n user[fireauth.AuthUser.GetAccountInfoField.DISPLAY_NAME]),\n 'photoURL': /** @type {?string|undefined} */ (\n user[fireauth.AuthUser.GetAccountInfoField.PHOTO_URL]),\n 'email': /** @type {?string|undefined} */ (\n user[fireauth.AuthUser.GetAccountInfoField.EMAIL]),\n 'emailVerified':\n !!user[fireauth.AuthUser.GetAccountInfoField.EMAIL_VERIFIED],\n 'phoneNumber': /** @type {?string|undefined} */ (\n user[fireauth.AuthUser.GetAccountInfoField.PHONE_NUMBER]),\n 'lastLoginAt': /** @type {?string|undefined} */ (\n user[fireauth.AuthUser.GetAccountInfoField.LAST_LOGIN_AT]),\n 'createdAt': /** @type {?string|undefined} */ (\n user[fireauth.AuthUser.GetAccountInfoField.CREATED_AT]),\n 'tenantId': /** @type {?string|undefined} */ (\n user[fireauth.AuthUser.GetAccountInfoField.TENANT_ID])\n });\n this.setAccountInfo(accountInfo);\n var linkedAccounts = this.extractLinkedAccounts_(user);\n for (var i = 0; i < linkedAccounts.length; i++) {\n this.addProviderData(linkedAccounts[i]);\n }\n // Sets the isAnonymous flag based on email, passwordHash and providerData.\n var isAnonymous = !(this['email'] &&\n user[fireauth.AuthUser.GetAccountInfoField.PASSWORD_HASH]) &&\n !(this['providerData'] && this['providerData'].length);\n this.updateProperty('isAnonymous', isAnonymous);\n // Notify external listeners of the reload.\n this.dispatchEvent(new fireauth.UserEvent(\n fireauth.UserEventType.USER_RELOADED,\n {userServerResponse: user}));\n};\n\n\n/**\n * Extracts the linked accounts from getAccountInfo response and returns an\n * array of corresponding provider data.\n * @param {!Object} resp The response object.\n * @return {!Array<!fireauth.AuthUserInfo>} The linked accounts.\n * @private\n */\nfireauth.AuthUser.prototype.extractLinkedAccounts_ = function(resp) {\n var providerInfo =\n resp[fireauth.AuthUser.GetAccountInfoField.PROVIDER_USER_INFO];\n if (!providerInfo || !providerInfo.length) {\n return [];\n }\n\n return goog.array.map(providerInfo, function(info) {\n return new fireauth.AuthUserInfo(\n info[fireauth.AuthUser.GetAccountInfoProviderField.RAW_ID],\n info[fireauth.AuthUser.GetAccountInfoProviderField.PROVIDER_ID],\n info[fireauth.AuthUser.GetAccountInfoProviderField.EMAIL],\n info[fireauth.AuthUser.GetAccountInfoProviderField.DISPLAY_NAME],\n info[fireauth.AuthUser.GetAccountInfoProviderField.PHOTO_URL],\n info[fireauth.AuthUser.GetAccountInfoProviderField.PHONE_NUMBER]);\n });\n};\n\n\n/**\n * Reauthenticates a user using a fresh credential, to be used before operations\n * such as updatePassword that require tokens from recent login attempts. It\n * also returns any additional user info data or credentials returned form the\n * backend. It has been deprecated in favor of reauthenticateWithCredential.\n * @param {!fireauth.AuthCredential} credential\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.reauthenticateAndRetrieveDataWithCredential =\n function(credential) {\n fireauth.deprecation.log(\n fireauth.deprecation.Deprecations.REAUTH_WITH_CREDENTIAL);\n return this.reauthenticateWithCredential(credential);\n};\n\n\n/**\n * Reauthenticates a user using a fresh credential, to be used before operations\n * such as updatePassword that require tokens from recent login attempts. It\n * also returns any additional user info data or credentials returned form the\n * backend.\n * @param {!fireauth.AuthCredential} credential\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.reauthenticateWithCredential =\n function(credential) {\n var self = this;\n var userCredential = null;\n // Register this pending promise but bypass user invalidation check.\n return this.registerPendingPromise_(\n // Match ID token from credential with the current user UID.\n credential.matchIdTokenWithUid(this.rpcHandler_, this['uid'])\n .then(function(response) {\n // If the credential is valid and matches the current user ID, then\n // update the tokens accordingly.\n self.updateTokensIfPresent(response);\n // Get user credential.\n userCredential = self.getUserCredential_(\n response, fireauth.constants.OperationType.REAUTHENTICATE);\n // This could potentially validate an invalidated user. This happens in\n // the case a password reset was applied. The refresh token is expired.\n // Reauthentication should revalidate the user.\n // User would remain non current if already signed out, but should be\n // enabled again.\n self.userInvalidatedError_ = null;\n return self.reload();\n }).then(function() {\n // Return user credential after reauthenticated user is reloaded.\n return userCredential;\n }),\n // Skip invalidation check as reauthentication could revalidate a user.\n true);\n};\n\n\n/**\n * Reloads the user and then checks if a provider is already linked. If so,\n * this returns a Promise that rejects. Note that state change listeners are not\n * notified on success, so that operations using this can make changes and then\n * do one final listener notification.\n * @param {string} providerId\n * @return {!goog.Promise<void>}\n * @private\n */\nfireauth.AuthUser.prototype.checkIfAlreadyLinked_ =\n function(providerId) {\n var self = this;\n // Reload first in case the user was updated elsewhere.\n return this.reloadWithoutSaving_()\n .then(function() {\n if (goog.array.contains(self.getProviderIds(), providerId)) {\n return self.notifyStateChangeListeners_()\n .then(function() {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.PROVIDER_ALREADY_LINKED);\n });\n }\n });\n};\n\n\n/**\n * Links a provider to the current user and returns any additional user info\n * data or credentials returned form the backend. It has been deprecated in\n * favor of linkWithCredential.\n * @param {!fireauth.AuthCredential} credential The credential from the Auth\n * provider.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.linkAndRetrieveDataWithCredential =\n function(credential) {\n fireauth.deprecation.log(\n fireauth.deprecation.Deprecations.LINK_WITH_CREDENTIAL);\n return this.linkWithCredential(credential);\n};\n\n\n/**\n * Links a provider to the current user and returns any additional user info\n * data or credentials returned form the backend.\n * @param {!fireauth.AuthCredential} credential The credential from the Auth\n * provider.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.linkWithCredential = function(credential) {\n var self = this;\n var userCredential = null;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(\n this.checkIfAlreadyLinked_(credential['providerId'])\n .then(function() {\n return self.getIdToken();\n })\n .then(function(idToken) {\n return credential.linkToIdToken(self.rpcHandler_, idToken);\n })\n .then(function(response) {\n // Get user credential.\n userCredential = self.getUserCredential_(\n response, fireauth.constants.OperationType.LINK);\n // Finalize linking.\n return self.finalizeLinking_(response);\n })\n .then(function(user) {\n // Return user credential after finalizing linking.\n return userCredential;\n })\n );\n};\n\n\n/**\n * Links a phone number using the App verifier instance and returns a\n * promise that resolves with the confirmation result which on confirmation\n * will resolve with the UserCredential object.\n * @param {string} phoneNumber The phone number to authenticate with.\n * @param {!firebase.auth.ApplicationVerifier} appVerifier The application\n * verifier.\n * @return {!goog.Promise<!fireauth.ConfirmationResult>}\n */\nfireauth.AuthUser.prototype.linkWithPhoneNumber =\n function(phoneNumber, appVerifier) {\n var self = this;\n return /** @type {!goog.Promise<!fireauth.ConfirmationResult>} */ (\n this.registerPendingPromise_(\n // Check if linked already. If so, throw an error.\n // This is redundant but is needed to prevent the need to send the\n // SMS (worth the cost).\n this.checkIfAlreadyLinked_(fireauth.idp.ProviderId.PHONE)\n .then(function() {\n return fireauth.ConfirmationResult.initialize(\n self.getAuth_(),\n phoneNumber,\n appVerifier,\n // This will check again if the credential is linked.\n goog.bind(self.linkWithCredential, self));\n })));\n};\n\n\n/**\n * Reauthenticates a user with a phone number using the App verifier instance\n * and returns a promise that resolves with the confirmation result which on\n * confirmation will resolve with the UserCredential object.\n * @param {string} phoneNumber The phone number to authenticate with.\n * @param {!firebase.auth.ApplicationVerifier} appVerifier The application\n * verifier.\n * @return {!goog.Promise<!fireauth.ConfirmationResult>}\n */\nfireauth.AuthUser.prototype.reauthenticateWithPhoneNumber =\n function(phoneNumber, appVerifier) {\n var self = this;\n return /** @type {!goog.Promise<!fireauth.ConfirmationResult>} */ (\n this.registerPendingPromise_(\n // Wrap this operation in a Promise since self.getAuth_() may throw an\n // error synchronously.\n goog.Promise.resolve().then(function() {\n return fireauth.ConfirmationResult.initialize(\n // Get corresponding Auth instance.\n self.getAuth_(),\n phoneNumber,\n appVerifier,\n goog.bind(self.reauthenticateWithCredential,\n self));\n }),\n // Skip invalidation check as reauthentication could revalidate a\n // user.\n true));\n};\n\n\n/**\n * Converts an ID token response (eg. verifyAssertion) to a UserCredential\n * object.\n * @param {!Object} idTokenResponse The ID token response.\n * @param {!fireauth.constants.OperationType} operationType The operation type\n * to set in the user credential.\n * @return {!fireauth.AuthEventManager.Result} The UserCredential object\n * constructed from the response.\n * @private\n */\nfireauth.AuthUser.prototype.getUserCredential_ =\n function(idTokenResponse, operationType) {\n // Get credential if available in the response.\n var credential = fireauth.AuthProvider.getCredentialFromResponse(\n idTokenResponse);\n // Get additional user info data if available in the response.\n var additionalUserInfo = fireauth.AdditionalUserInfo.fromPlainObject(\n idTokenResponse);\n // Return the readonly copy of the user credential object.\n return fireauth.object.makeReadonlyCopy({\n // Return the current user reference.\n 'user': this,\n // Return any credential passed from the backend.\n 'credential': credential,\n // Return any additional IdP data passed from the backend.\n 'additionalUserInfo': additionalUserInfo,\n // Return the operation type in the user credential object.\n 'operationType': operationType\n });\n};\n\n\n/**\n * Finalizes a linking flow, updating idToken and user's data using the\n * RPC linking response.\n * @param {!Object} response The RPC linking response.\n * @return {!goog.Promise<!fireauth.AuthUser>}\n * @private\n */\nfireauth.AuthUser.prototype.finalizeLinking_ = function(response) {\n // The response may contain a new access token,\n // so we should update them just like a new sign in.\n this.updateTokensIfPresent(response);\n // This will take care of saving the updated state.\n var self = this;\n return this.reload().then(function() {\n return self;\n });\n};\n\n\n/**\n * Updates the user's email.\n * @param {string} newEmail The new email.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.updateEmail = function(newEmail) {\n var self = this;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(this.getIdToken()\n .then(function(idToken) {\n return self.rpcHandler_.updateEmail(idToken, newEmail);\n })\n .then(function(response) {\n // Calls to SetAccountInfo may invalidate old tokens.\n self.updateTokensIfPresent(response);\n // Reloads the user to update emailVerified.\n return self.reload();\n }));\n};\n\n\n/**\n * Updates the user's phone number.\n * @param {!fireauth.PhoneAuthCredential} phoneCredential\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.updatePhoneNumber = function(phoneCredential) {\n var self = this;\n return this.registerPendingPromise_(this.getIdToken()\n .then(function(idToken) {\n // The backend always overwrites the existing phone number during a\n // link operation.\n return phoneCredential.linkToIdToken(self.rpcHandler_, idToken);\n })\n .then(function(response) {\n self.updateTokensIfPresent(response);\n return self.reload();\n }));\n};\n\n\n/**\n * Updates the user's password.\n * @param {string} newPassword The new password.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.updatePassword = function(newPassword) {\n var self = this;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(\n this.getIdToken()\n .then(function(idToken) {\n return self.rpcHandler_.updatePassword(idToken, newPassword);\n })\n .then(function(response) {\n self.updateTokensIfPresent(response);\n // Reloads the user in case email has also been updated and the user\n // was anonymous.\n return self.reload();\n }));\n};\n\n\n/**\n * Updates the user's profile data.\n * @param {!Object} profile The profile data to update.\n * @return {!goog.Promise<undefined>}\n */\nfireauth.AuthUser.prototype.updateProfile = function(profile) {\n if (profile['displayName'] === undefined &&\n profile['photoURL'] === undefined) {\n // No change, directly return.\n return this.checkDestroyed_();\n }\n var self = this;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(\n this.getIdToken().then(function(idToken) {\n // Translate the request into one that the backend accepts.\n var profileRequest = {\n 'displayName': profile['displayName'],\n 'photoUrl': profile['photoURL']\n };\n return self.rpcHandler_.updateProfile(idToken, profileRequest);\n })\n .then(function(response) {\n // Calls to SetAccountInfo may invalidate old tokens.\n self.updateTokensIfPresent(response);\n // Update properties.\n self.updateProperty('displayName',\n response[fireauth.AuthUser.SetAccountInfoField.DISPLAY_NAME] ||\n null);\n self.updateProperty('photoURL',\n response[fireauth.AuthUser.SetAccountInfoField.PHOTO_URL] || null);\n goog.array.forEach(self['providerData'], function(userInfo) {\n // Check if password provider is linked.\n if (userInfo['providerId'] === fireauth.idp.ProviderId.PASSWORD) {\n // If so, update both fields in that provider.\n fireauth.object.setReadonlyProperty(\n userInfo, 'displayName', self['displayName']);\n fireauth.object.setReadonlyProperty(\n userInfo, 'photoURL', self['photoURL']);\n }\n });\n // Notify changes and resolve.\n return self.notifyStateChangeListeners_();\n })\n .then(fireauth.AuthUser.returnNothing_));\n};\n\n\n/**\n * Unlinks a provider from an account.\n * @param {!fireauth.idp.ProviderId} providerId The ID of the provider to\n * unlink.\n * @return {!goog.Promise<!fireauth.AuthUser>}\n */\nfireauth.AuthUser.prototype.unlink = function(providerId) {\n var self = this;\n // Make sure we have updated user providers to avoid removing a linked\n // provider that hasn't been updated in current copy of user.\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(\n this.reloadWithoutSaving_()\n .then(function(idToken) {\n // Provider already unlinked.\n if (!goog.array.contains(self.getProviderIds(), providerId)) {\n return self.notifyStateChangeListeners_()\n .then(function() {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.NO_SUCH_PROVIDER);\n });\n }\n // We delete the providerId given.\n return self.rpcHandler_\n .deleteLinkedAccounts(idToken, [providerId])\n .then(function(resp) {\n // Construct the set of provider IDs returned by server.\n var remainingProviderIds = {};\n var userInfo = resp[fireauth.AuthUser.SetAccountInfoField.\n PROVIDER_USER_INFO] || [];\n goog.array.forEach(userInfo, function(obj) {\n remainingProviderIds[\n obj[fireauth.AuthUser.SetAccountInfoField.PROVIDER_ID]] =\n true;\n });\n\n // Remove all provider data objects where the provider ID no\n // longer exists in this user.\n goog.array.forEach(self.getProviderIds(), function(pId) {\n if (!remainingProviderIds[pId]) {\n // This provider no longer linked, remove it from user.\n self.removeProviderData(pId);\n }\n });\n\n // Remove the phone number if the phone provider was unlinked.\n if (!remainingProviderIds[fireauth.PhoneAuthProvider[\n 'PROVIDER_ID']]) {\n fireauth.object.setReadonlyProperty(self, 'phoneNumber', null);\n }\n\n return self.notifyStateChangeListeners_();\n });\n }));\n};\n\n\n/**\n * Deletes the user, triggering an Auth token change if successful.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.delete = function() {\n // Notice the way of declaring the method, it's to avoid a weird bug on IE8.\n var self = this;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(\n this.getIdToken()\n .then(function(idToken) {\n return self.rpcHandler_.deleteAccount(idToken);\n })\n .then(function() {\n self.notifyUserDeletedListeners_();\n }))\n .then(function() {\n // Destroying after the registered promise is handled ensures it won't\n // be canceled.\n self.destroy();\n });\n};\n\n\n/**\n * Tells the Auth event manager if this user is the owner of a detected Auth\n * event. A user can handle linkWithPopup and linkWithRedirect operations.\n * In addition, the event ID should match the user's event IDs.\n * @param {!fireauth.AuthEvent.Type} mode The Auth operation mode (popup,\n * redirect).\n * @param {?string=} opt_eventId The event ID.\n * @return {boolean} Whether the Auth event handler can handler the provided\n * event.\n * @override\n */\nfireauth.AuthUser.prototype.canHandleAuthEvent = function(mode, opt_eventId) {\n if (mode == fireauth.AuthEvent.Type.LINK_VIA_POPUP &&\n this.getPopupEventId() == opt_eventId &&\n this.pendingPopupResolvePromise_) {\n // The link via popup event's ID matches the user's popup event ID which\n // makes this user the owner of this event.\n return true;\n } else if (mode == fireauth.AuthEvent.Type.REAUTH_VIA_POPUP &&\n this.getPopupEventId() == opt_eventId &&\n this.pendingPopupResolvePromise_) {\n // The reauth via popup event's ID matches the user's popup event ID which\n // makes this user the owner of this event.\n return true;\n } else if (mode == fireauth.AuthEvent.Type.LINK_VIA_REDIRECT &&\n this.getRedirectEventId() == opt_eventId) {\n // The link via redirect event's ID matches the user's redirect event ID\n // which makes this user the owner of this event.\n return true;\n } else if (mode == fireauth.AuthEvent.Type.REAUTH_VIA_REDIRECT &&\n this.getRedirectEventId() == opt_eventId) {\n // The reauth via redirect event's ID matches the user's redirect event ID\n // which makes this user the owner of this event.\n return true;\n }\n return false;\n};\n\n\n/**\n * Completes the pending popup operation. If error is not null, rejects with the\n * error. Otherwise, it resolves with the popup redirect result.\n * @param {!fireauth.AuthEvent.Type} mode The Auth operation mode (popup,\n * redirect).\n * @param {?fireauth.AuthEventManager.Result} popupRedirectResult The result\n * to resolve with when no error supplied.\n * @param {?fireauth.AuthError} error When supplied, the promise will reject.\n * @param {?string=} opt_eventId The event ID.\n * @override\n */\nfireauth.AuthUser.prototype.resolvePendingPopupEvent =\n function(mode, popupRedirectResult, error, opt_eventId) {\n // Only handles popup events with event IDs that match a pending popup ID.\n if ((mode != fireauth.AuthEvent.Type.LINK_VIA_POPUP &&\n mode != fireauth.AuthEvent.Type.REAUTH_VIA_POPUP) ||\n opt_eventId != this.getPopupEventId()) {\n return;\n }\n if (error && this.pendingPopupRejectPromise_) {\n // Reject with error for supplied mode.\n this.pendingPopupRejectPromise_(error);\n } else if (popupRedirectResult &&\n !error &&\n this.pendingPopupResolvePromise_) {\n // Resolve with result for supplied mode.\n this.pendingPopupResolvePromise_(popupRedirectResult);\n }\n // Now that event is resolved, delete timeout promise.\n if (this.popupTimeoutPromise_) {\n this.popupTimeoutPromise_.cancel();\n this.popupTimeoutPromise_ = null;\n }\n // Delete pending promises.\n delete this.pendingPopupResolvePromise_;\n delete this.pendingPopupRejectPromise_;\n};\n\n\n/**\n * Returns the handler's appropriate popup and redirect sign in operation\n * finisher. Can handle link or reauth events that match existing event IDs.\n * @param {!fireauth.AuthEvent.Type} mode The Auth operation mode (popup,\n * redirect).\n * @param {?string=} opt_eventId The optional event ID.\n * @return {?function(string, string, ?string,\n * ?string=):!goog.Promise<!fireauth.AuthEventManager.Result>}\n * @override\n */\nfireauth.AuthUser.prototype.getAuthEventHandlerFinisher =\n function(mode, opt_eventId) {\n if (mode == fireauth.AuthEvent.Type.LINK_VIA_POPUP &&\n opt_eventId == this.getPopupEventId()) {\n // Link with popup ID matches popup event ID.\n return goog.bind(this.finishPopupAndRedirectLink, this);\n } else if (mode == fireauth.AuthEvent.Type.REAUTH_VIA_POPUP &&\n opt_eventId == this.getPopupEventId()) {\n // Reauth with popup ID matches popup event ID.\n return goog.bind(this.finishPopupAndRedirectReauth, this);\n } else if (mode == fireauth.AuthEvent.Type.LINK_VIA_REDIRECT &&\n this.getRedirectEventId() == opt_eventId) {\n // Link with redirect ID matches redirect event ID.\n return goog.bind(this.finishPopupAndRedirectLink, this);\n } else if (mode == fireauth.AuthEvent.Type.REAUTH_VIA_REDIRECT &&\n this.getRedirectEventId() == opt_eventId) {\n // Reauth with redirect ID matches redirect event ID.\n return goog.bind(this.finishPopupAndRedirectReauth, this);\n }\n return null;\n};\n\n\n/**\n * @return {string} The generated event ID used to identify a popup or redirect\n * event.\n * @private\n */\nfireauth.AuthUser.prototype.generateEventId_ = function() {\n return fireauth.util.generateEventId(this['uid'] + ':::');\n};\n\n\n/**\n * Links to Auth provider via popup.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.linkWithPopup = function(provider) {\n var self = this;\n // Additional check to return to fail when the provider is already linked.\n var additionalCheck = function() {\n return self.checkIfAlreadyLinked_(provider['providerId'])\n .then(function() {\n // Notify state listeners after the check as it will update the user\n // state.\n return self.notifyStateChangeListeners_();\n });\n };\n return this.runOperationWithPopup_(\n fireauth.AuthEvent.Type.LINK_VIA_POPUP, provider, additionalCheck, false);\n};\n\n\n/**\n * Reauthenticate to Auth provider via popup.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.reauthenticateWithPopup = function(provider) {\n // No additional check needed before running this operation.\n var additionalCheck = function() {\n return goog.Promise.resolve();\n };\n return this.runOperationWithPopup_(\n fireauth.AuthEvent.Type.REAUTH_VIA_POPUP,\n provider,\n additionalCheck,\n // Do not update token and skip session invalidation check.\n true);\n};\n\n\n/**\n * Runs a specific OAuth operation using the Auth provider via popup.\n * @param {!fireauth.AuthEvent.Type} mode The mode of operation (link or\n * reauth).\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {function():!goog.Promise} additionalCheck The additional check to\n * run before proceeding with the popup processing.\n * @param {boolean} isReauthOperation whether this is a reauth operation or not.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n * @private\n */\nfireauth.AuthUser.prototype.runOperationWithPopup_ =\n function(mode, provider, additionalCheck, isReauthOperation) {\n // Check if popup and redirect are supported in this environment.\n if (!fireauth.util.isPopupRedirectSupported()) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n }\n // Quickly throw user invalidation error if already invalidated.\n if (this.userInvalidatedError_ &&\n // Skip invalidation check as reauthentication could revalidate a user.\n !isReauthOperation) {\n return goog.Promise.reject(this.userInvalidatedError_);\n }\n var self = this;\n // Popup the window immediately to make sure the browser associates the\n // popup with the click that triggered it.\n\n // Get provider settings.\n var settings = fireauth.idp.getIdpSettings(provider['providerId']);\n // There could multiple users at the same time and multiple users could have\n // the same UID. So try to ensure event ID uniqueness.\n var eventId = this.generateEventId_();\n // If incapable of redirecting popup from opener, popup destination URL\n // directly. This could also happen in a sandboxed iframe.\n var oauthHelperWidgetUrl = null;\n if ((!fireauth.util.runsInBackground() || fireauth.util.isIframe()) &&\n this.authDomain_ &&\n provider['isOAuthProvider']) {\n oauthHelperWidgetUrl =\n fireauth.iframeclient.IfcHandler.getOAuthHelperWidgetUrl(\n this.authDomain_,\n this.apiKey_,\n this.appName_,\n mode,\n provider,\n null,\n eventId,\n firebase.SDK_VERSION || null,\n null,\n null,\n this['tenantId']);\n }\n // The popup must have a name, otherwise when successive popups are triggered\n // they will all render in the same instance and none will succeed since the\n // popup cancel of first window will close the shared popup window instance.\n var popupWin =\n fireauth.util.popup(\n oauthHelperWidgetUrl,\n fireauth.util.generateRandomString(),\n settings && settings.popupWidth,\n settings && settings.popupHeight);\n var p = additionalCheck().then(function() {\n // Auth event manager must be available for account linking or\n // reauthentication to be possible.\n self.getAuthEventManager();\n if (!isReauthOperation) {\n // Some operations like reauthenticate do not require this.\n return self.getIdToken().then(function(idToken) {});\n }\n }).then(function() {\n // Process popup request.\n return self.authEventManager_.processPopup(\n popupWin, mode, provider, eventId, !!oauthHelperWidgetUrl,\n self['tenantId']);\n }).then(function() {\n return new goog.Promise(function(resolve, reject) {\n // Expire other pending promises if still available.\n self.resolvePendingPopupEvent(\n mode,\n null,\n new fireauth.AuthError(fireauth.authenum.Error.EXPIRED_POPUP_REQUEST),\n // Existing popup event ID.\n self.getPopupEventId());\n // Save current pending promises.\n self.pendingPopupResolvePromise_ = resolve;\n self.pendingPopupRejectPromise_ = reject;\n // Overwrite popup event ID with new one.\n self.setPopupEventId(eventId);\n // Keep track of timeout promise to cancel it on promise resolution before\n // it times out.\n self.popupTimeoutPromise_ =\n self.authEventManager_.startPopupTimeout(\n self, mode, /** @type {!Window} */ (popupWin), eventId);\n });\n }).then(function(result) {\n // On resolution, close popup if still opened and pass result through.\n if (popupWin) {\n fireauth.util.closeWindow(popupWin);\n }\n if (result) {\n return fireauth.object.makeReadonlyCopy(result);\n }\n return null;\n }).thenCatch(function(error) {\n if (popupWin) {\n fireauth.util.closeWindow(popupWin);\n }\n throw error;\n });\n // Register this pending promise. This will also check for user invalidation.\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(\n p,\n // Skip invalidation check as reauthentication could revalidate a\n // user.\n isReauthOperation));\n};\n\n\n/**\n * Links to Auth provider via redirect.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.linkWithRedirect = function(provider) {\n var mode = fireauth.AuthEvent.Type.LINK_VIA_REDIRECT;\n var self = this;\n // Additional check to return to fail when the provider is already linked.\n var additionalCheck = function() {\n return self.checkIfAlreadyLinked_(provider['providerId']);\n };\n return this.runOperationWithRedirect_(mode, provider, additionalCheck, false);\n};\n\n\n/**\n * Reauthenticates to Auth provider via redirect.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.reauthenticateWithRedirect = function(provider) {\n // No additional check needed.\n var additionalCheck = function() {\n return goog.Promise.resolve();\n };\n return this.runOperationWithRedirect_(\n fireauth.AuthEvent.Type.REAUTH_VIA_REDIRECT,\n provider,\n additionalCheck,\n // Do not update token and skip session invalidation check.\n true);\n};\n\n\n\n/**\n * Runs a specific OAuth operation using the Auth provider via redirect.\n * @param {!fireauth.AuthEvent.Type} mode The mode of operation (link or\n * reauth).\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @param {function():!goog.Promise} additionalCheck The additional check to\n * run before proceeding with the redirect processing.\n * @param {boolean} isReauthOperation whether this is a reauth operation or not.\n * @return {!goog.Promise<void>}\n * @private\n */\nfireauth.AuthUser.prototype.runOperationWithRedirect_ =\n function(mode, provider, additionalCheck, isReauthOperation) {\n // Check if popup and redirect are supported in this environment.\n if (!fireauth.util.isPopupRedirectSupported()) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n }\n // Quickly throw user invalidation error if already invalidated.\n if (this.userInvalidatedError_ &&\n // Skip invalidation check as reauthentication could revalidate a user.\n !isReauthOperation) {\n return goog.Promise.reject(this.userInvalidatedError_);\n }\n var self = this;\n var errorThrown = null;\n // There could multiple users at the same time and multiple users could have\n // the same UID. So try to ensure event ID uniqueness.\n var eventId = this.generateEventId_();\n var p = additionalCheck().then(function() {\n // Auth event manager must be available for account linking or\n // reauthentication to be possible.\n self.getAuthEventManager();\n if (!isReauthOperation) {\n // Some operations like reauthenticate do not require this.\n return self.getIdToken().then(function(idToken) {});\n }\n }).then(function() {\n // Process redirect operation.\n self.setRedirectEventId(eventId);\n // Before redirecting save the event ID.\n // It is important that the user redirect event ID is updated in storage\n // before redirecting.\n return self.notifyStateChangeListeners_();\n }).then(function(user) {\n if (self.redirectStorageManager_) {\n // Save the user before redirecting in case it is not current so that it\n // can be retrieved after reloading for linking or reauthentication to\n // succeed.\n return self.redirectStorageManager_.setRedirectUser(self);\n }\n return user;\n }).then(function(user) {\n // Complete the redirect operation.\n return self.authEventManager_.processRedirect(\n mode, provider, eventId, self['tenantId']);\n }).thenCatch(function(error) {\n // Catch error if any is generated.\n errorThrown = error;\n if (self.redirectStorageManager_) {\n // If an error is detected, delete the redirected user from storage.\n return self.redirectStorageManager_.removeRedirectUser();\n }\n // No storage manager, just throw error.\n throw errorThrown;\n }).then(function() {\n // Rethrow the error.\n if (errorThrown) {\n throw errorThrown;\n }\n });\n // Register this pending promise. This will also check for user invalidation.\n return /** @type {!goog.Promise<void>} */ (this.registerPendingPromise_(\n p,\n // Skip invalidation check as reauthentication could revalidate a user.\n isReauthOperation));\n};\n\n\n/**\n * @return {!fireauth.AuthEventManager} The user's Auth event manager.\n */\nfireauth.AuthUser.prototype.getAuthEventManager = function() {\n // Either return the manager instance if available, otherwise throw an error.\n if (this.authEventManager_ && this.popupRedirectEnabled_) {\n return this.authEventManager_;\n } else if (this.authEventManager_ && !this.popupRedirectEnabled_) {\n // This should not happen as Auth will enable a user after it is created.\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\n throw new fireauth.AuthError(fireauth.authenum.Error.MISSING_AUTH_DOMAIN);\n};\n\n\n/**\n * Finishes the popup and redirect account linking operations.\n * @param {string} requestUri The callback URL with the OAuth response.\n * @param {string} sessionId The session ID used to generate the authUri.\n * @param {?string} tenantId The tenant ID.\n * @param {?string=} opt_postBody The optional POST body content.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.finishPopupAndRedirectLink =\n function(requestUri, sessionId, tenantId, opt_postBody) {\n var self = this;\n // Now that popup has responded, delete popup timeout promise.\n if (this.popupTimeoutPromise_) {\n this.popupTimeoutPromise_.cancel();\n this.popupTimeoutPromise_ = null;\n }\n var userCredential = null;\n // This routine could be run before init state, make sure it waits for that to\n // complete otherwise this would fail as user not loaded from storage yet.\n var p = this.getIdToken()\n .then(function(idToken) {\n var request = {\n 'requestUri': requestUri,\n 'postBody': opt_postBody,\n 'sessionId': sessionId,\n // To link a tenant user, the tenant ID will be passed to the\n // backend as part of the ID token.\n 'idToken': idToken\n };\n // This operation should fail if new ID token differs from old one.\n // So this can be treate as a profile update operation.\n return self.rpcHandler_.verifyAssertionForLinking(request);\n })\n .then(function(response) {\n // Get user credential.\n userCredential = self.getUserCredential_(\n response, fireauth.constants.OperationType.LINK);\n // Finalizes the linking process.\n return self.finalizeLinking_(response);\n })\n .then(function(user) {\n // Return the user credential response.\n return userCredential;\n });\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(p));\n};\n\n\n/**\n * Finishes the popup and redirect account reauthentication operations.\n * @param {string} requestUri The callback URL with the OAuth response.\n * @param {string} sessionId The session ID used to generate the authUri.\n * @param {?string} tenantId The tenant ID.\n * @param {?string=} opt_postBody The optional POST body content.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.AuthUser.prototype.finishPopupAndRedirectReauth =\n function(requestUri, sessionId, tenantId, opt_postBody) {\n var self = this;\n // Now that popup has responded, delete popup timeout promise.\n if (this.popupTimeoutPromise_) {\n this.popupTimeoutPromise_.cancel();\n this.popupTimeoutPromise_ = null;\n }\n var userCredential = null;\n // This routine could be run before init state, make sure it waits for that to\n // complete otherwise this would fail as user not loaded from storage yet.\n var p = goog.Promise.resolve()\n .then(function() {\n var request = {\n 'requestUri': requestUri,\n 'sessionId': sessionId,\n 'postBody': opt_postBody,\n // To reauthenticate a tenant user, the tenant ID will be passed to\n // the backend explicitly.\n // Even if tenant ID is null, still pass it to RPC handler explicitly\n // so that it won't be overridden by RPC handler's tenant ID.\n 'tenantId': tenantId\n };\n // Finish sign in by calling verifyAssertionForExisting and then\n // matching the returned ID token's UID with the current user's.\n return fireauth.AuthCredential.verifyTokenResponseUid(\n self.rpcHandler_.verifyAssertionForExisting(request),\n self['uid']);\n }).then(function(response) {\n // Get credential from response if available.\n // Get user credential.\n userCredential = self.getUserCredential_(\n response, fireauth.constants.OperationType.REAUTHENTICATE);\n // If the credential is valid and matches the current user ID, then\n // update the tokens accordingly.\n self.updateTokensIfPresent(response);\n // This could potentially validate an invalidated user. This happens in\n // the case a password reset was applied. The refresh token is expired.\n // Reauthentication should revalidate the user.\n // User would remain non current if already signed out, but should be\n // enabled again.\n self.userInvalidatedError_ = null;\n return self.reload();\n })\n .then(function() {\n // Return the user credential response.\n return userCredential;\n });\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(\n p,\n // Skip invalidation check as reauthentication could revalidate a\n // user.\n true));\n};\n\n\n/**\n * Sends the verification email to the email in the user's account.\n * @param {?Object=} opt_actionCodeSettings The optional action code settings\n * object.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.sendEmailVerification =\n function(opt_actionCodeSettings) {\n var self = this;\n var idToken = null;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(\n // Wrap in promise as ActionCodeSettings constructor could throw a\n // synchronous error if invalid arguments are specified.\n this.getIdToken().then(function(latestIdToken) {\n idToken = latestIdToken;\n if (typeof opt_actionCodeSettings !== 'undefined' &&\n // Ignore empty objects.\n !goog.object.isEmpty(opt_actionCodeSettings)) {\n return new fireauth.ActionCodeSettings(\n /** @type {!Object} */ (opt_actionCodeSettings)).buildRequest();\n }\n return {};\n })\n .then(function(additionalRequestData) {\n return self.rpcHandler_.sendEmailVerification(\n /** @type {string} */ (idToken), additionalRequestData);\n })\n .then(function(email) {\n if (self['email'] != email) {\n // Our local copy does not have an email. If the email changed,\n // reload the user.\n return self.reload();\n }\n })\n .then(function() {\n // Return nothing.\n }));\n};\n\n\n/**\n * Sends the verification email before updating the email on the user.\n * @param {string} newEmail The new email.\n * @param {?Object=} opt_actionCodeSettings The optional action code settings\n * object.\n * @return {!goog.Promise<void>}\n */\nfireauth.AuthUser.prototype.verifyBeforeUpdateEmail =\n function(newEmail, opt_actionCodeSettings) {\n var self = this;\n var idToken = null;\n // Register this pending promise. This will also check for user invalidation.\n return this.registerPendingPromise_(\n // Wrap in promise as ActionCodeSettings constructor could throw a\n // synchronous error if invalid arguments are specified.\n this.getIdToken().then(function(latestIdToken) {\n idToken = latestIdToken;\n if (typeof opt_actionCodeSettings !== 'undefined' &&\n // Ignore empty objects.\n !goog.object.isEmpty(opt_actionCodeSettings)) {\n return new fireauth.ActionCodeSettings(\n /** @type {!Object} */ (opt_actionCodeSettings)).buildRequest();\n }\n return {};\n })\n .then(function(additionalRequestData) {\n return self.rpcHandler_.verifyBeforeUpdateEmail(\n /** @type {string} */ (idToken), newEmail, additionalRequestData);\n })\n .then(function(email) {\n if (self['email'] != email) {\n // If the local copy of the email on user is outdated, reload the\n // user.\n return self.reload();\n }\n })\n .then(function() {\n // Return nothing.\n }));\n};\n\n\n/**\n * Destroys the user object and makes further operations invalid. Sensitive\n * fields (refreshToken) are also cleared.\n */\nfireauth.AuthUser.prototype.destroy = function() {\n // Cancel all pending promises.\n for (var i = 0; i < this.pendingPromises_.length; i++) {\n this.pendingPromises_[i].cancel(fireauth.authenum.Error.MODULE_DESTROYED);\n }\n // Stop listening to language code changes.\n this.setLanguageCodeChangeDispatcher(null);\n // Stop listening to framework changes.\n this.setFrameworkChangeDispatcher(null);\n // Empty pending promises array.\n this.pendingPromises_ = [];\n this.destroyed_ = true;\n // Stop proactive refresh if running.\n this.stopProactiveRefresh();\n fireauth.object.setReadonlyProperty(this, 'refreshToken', null);\n // Make sure the destroyed user is unsubscribed from Auth event handling.\n if (this.authEventManager_) {\n this.authEventManager_.unsubscribe(this);\n }\n};\n\n\n/**\n * Takes in a pending promise, saves it and adds a clean up callback which\n * forgets the pending promise after it is fulfilled and echoes the promise\n * back. If in the process, a user invalidation error is detected, caches the\n * error so next time a call is made on the user, the operation will fail with\n * the cached error.\n * @param {!goog.Promise<*, *>|!goog.Promise<void>} p The pending promise.\n * @param {boolean=} opt_skipInvalidationCheck Whether to skip invalidation\n * check.\n * @return {!goog.Promise<*, *>|!goog.Promise<void>}\n * @private\n */\nfireauth.AuthUser.prototype.registerPendingPromise_ =\n function(p, opt_skipInvalidationCheck) {\n var self = this;\n // Check if user invalidation occurs.\n var processedP = this.checkIfInvalidated_(p, opt_skipInvalidationCheck);\n // Save created promise in pending list.\n this.pendingPromises_.push(processedP);\n processedP.thenAlways(function() {\n // When fulfilled, remove from pending list.\n goog.array.remove(self.pendingPromises_, processedP);\n });\n // Return the promise.\n return processedP\n .thenCatch(function(error) {\n var multiFactorError = null;\n if (error && error['code'] === 'auth/multi-factor-auth-required') {\n multiFactorError = fireauth.MultiFactorError.fromPlainObject(\n error.toPlainObject(),\n self.getAuth_(),\n goog.bind(self.handleMultiFactorIdTokenResolver_, self));\n }\n throw multiFactorError || error;\n });\n};\n\n\n/**\n * Completes multi-factor sign-in. This is only relevant for re-authentication\n * flows.\n * @param {{idToken: string, refreshToken: string}} response The successful\n * sign-in response containing the new ID tokens.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>} A Promise that\n * resolves with the updated `UserCredential`.\n * @private\n */\nfireauth.AuthUser.prototype.handleMultiFactorIdTokenResolver_ =\n function(response) {\n var userCredential = null;\n var self = this;\n // Validate token response matches current user ID.\n var p = fireauth.AuthCredential.verifyTokenResponseUid(\n goog.Promise.resolve(response),\n self['uid'])\n .then(function(response) {\n // Get credential from response if available.\n userCredential = self.getUserCredential_(\n response, fireauth.constants.OperationType.REAUTHENTICATE);\n // If the credential is valid and matches the current user ID, then\n // update the tokens accordingly.\n self.updateTokensIfPresent(response);\n // This could potentially validate an invalidated user.\n self.userInvalidatedError_ = null;\n // Reload the user with the latest profile.\n return self.reload();\n })\n .then(function() {\n // Return the user credential response.\n return userCredential;\n });\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(\n p,\n // Skip invalidation check as reauthentication could revalidate a\n // user.\n true));\n};\n\n\n/**\n * Check if user invalidation occurs. If so, it caches the error so it can be\n * thrown immediately the next time an operation is run on the user.\n * @param {!goog.Promise<*, *>|!goog.Promise<void>} p The pending promise.\n * @param {boolean=} opt_skipInvalidationCheck Whether to skip invalidation\n * check.\n * @return {!goog.Promise<*, *>|!goog.Promise<void>}\n * @private\n */\nfireauth.AuthUser.prototype.checkIfInvalidated_ =\n function(p, opt_skipInvalidationCheck) {\n var self = this;\n // Already invalidated, reject with token expired error.\n // Unless invalidation check is to be skipped.\n if (this.userInvalidatedError_ && !opt_skipInvalidationCheck) {\n // Cancel pending promise.\n p.cancel();\n // Reject with cached error.\n return goog.Promise.reject(this.userInvalidatedError_);\n }\n return p.thenCatch(function(error) {\n // Session invalidated.\n if (fireauth.AuthUser.isUserInvalidated_(error)) {\n // Notify listeners of invalidated session.\n if (!self.userInvalidatedError_) {\n self.notifyUserInvalidatedListeners_();\n }\n // Cache the invalidation error.\n self.userInvalidatedError_ = /** @type {!fireauth.AuthError} */ (error);\n }\n // Rethrow the error.\n throw error;\n });\n};\n\n\n/**\n * @return {!Object} The object representation of the user instance.\n * @override\n */\nfireauth.AuthUser.prototype.toJSON = function() {\n // Return the plain object representation in case JSON.stringify is called on\n // a user instance.\n return this.toPlainObject();\n};\n\n\n/**\n * @return {!Object} The object representation of the user instance.\n */\nfireauth.AuthUser.prototype.toPlainObject = function() {\n var obj = {\n 'uid': this['uid'],\n 'displayName': this['displayName'],\n 'photoURL': this['photoURL'],\n 'email': this['email'],\n 'emailVerified': this['emailVerified'],\n 'phoneNumber': this['phoneNumber'],\n 'isAnonymous': this['isAnonymous'],\n 'tenantId': this['tenantId'],\n 'providerData': [],\n 'apiKey': this.apiKey_,\n 'appName': this.appName_,\n 'authDomain': this.authDomain_,\n 'stsTokenManager': this.stsTokenManager_.toPlainObject(),\n // Redirect event ID must be maintained in case there is a pending redirect\n // event.\n 'redirectEventId': this.getRedirectEventId()\n };\n // Extend user plain object with metadata object.\n if (this['metadata']) {\n goog.object.extend(obj, this['metadata'].toPlainObject());\n }\n goog.array.forEach(this['providerData'], function(userInfo) {\n obj['providerData'].push(fireauth.object.makeWritableCopy(userInfo));\n });\n // Extend plain object with multi-factor user data.\n goog.object.extend(obj, this.multiFactorUser_.toPlainObject());\n return obj;\n};\n\n\n/**\n * Converts a plain user object to {@code fireauth.AuthUser}.\n * @param {!Object} user The object representation of the user instance.\n * @return {?fireauth.AuthUser} The Firebase user object corresponding to\n * object.\n */\nfireauth.AuthUser.fromPlainObject = function(user) {\n if (!user['apiKey']) {\n return null;\n }\n var options = {\n 'apiKey': user['apiKey'],\n 'authDomain': user['authDomain'],\n 'appName': user['appName']\n };\n // Convert to server response format. Constructor does not take\n // stsTokenManager toPlainObject as that format is different than the return\n // server response which is always used to initialize a user instance.\n var stsTokenManagerResponse = {};\n if (user['stsTokenManager'] &&\n user['stsTokenManager']['accessToken']) {\n stsTokenManagerResponse[fireauth.RpcHandler.AuthServerField.ID_TOKEN] =\n user['stsTokenManager']['accessToken'];\n // Refresh token could be expired.\n stsTokenManagerResponse[fireauth.RpcHandler.AuthServerField.REFRESH_TOKEN] =\n user['stsTokenManager']['refreshToken'] || null;\n } else {\n // Token response is a required field.\n return null;\n }\n var firebaseUser = new fireauth.AuthUser(options,\n stsTokenManagerResponse,\n /** @type {!fireauth.AuthUser.AccountInfo} */ (user));\n if (user['providerData']) {\n goog.array.forEach(user['providerData'], function(userInfo) {\n if (userInfo) {\n firebaseUser.addProviderData(/** @type {!fireauth.AuthUserInfo} */ (\n fireauth.object.makeReadonlyCopy(userInfo)));\n }\n });\n }\n // Redirect event ID must be restored to complete any pending link with\n // redirect operation owned by this user.\n if (user['redirectEventId']) {\n firebaseUser.setRedirectEventId(user['redirectEventId']);\n }\n return firebaseUser;\n};\n\n\n\n/**\n * Factory method for initializing a Firebase user object and populating its\n * user info. This is the recommended way for initializing a user externally.\n * On sign in/up operation, the server returns a token response. The response is\n * all that is needed to initialize this user.\n * @param {!Object} appOptions The application options.\n * @param {!Object} stsTokenResponse The server STS token response.\n * @param {?fireauth.storage.RedirectUserManager=}\n * opt_redirectStorageManager The utility used to store and delete a user on\n * link with redirect.\n * @param {?Array<string>=} opt_frameworks The list of frameworks to log on the\n * user on initialization.\n * @return {!goog.Promise<!fireauth.AuthUser>}\n */\nfireauth.AuthUser.initializeFromIdTokenResponse = function(appOptions,\n stsTokenResponse, opt_redirectStorageManager, opt_frameworks) {\n // Initialize the Firebase Auth user.\n var user = new fireauth.AuthUser(\n appOptions, stsTokenResponse);\n // If redirect storage manager provided, set it.\n if (opt_redirectStorageManager) {\n user.setRedirectStorageManager(opt_redirectStorageManager);\n }\n // If frameworks provided, set it.\n if (opt_frameworks) {\n user.setFramework(opt_frameworks);\n }\n // Updates the user info and data and resolves with a user instance.\n return user.reload().then(function() {\n return user;\n });\n};\n\n\n/**\n * Returns an AuthUser copy of the provided user using the provided parameters\n * without making any network request.\n * @param {!fireauth.AuthUser} user The user to be copied.\n * @param {?Object=} opt_appOptions The application options.\n * @param {?fireauth.storage.RedirectUserManager=}\n * opt_redirectStorageManager The utility used to store and delete a user on\n * link with redirect.\n * @param {?Array<string>=} opt_frameworks The list of frameworks to log on the\n * user on initialization.\n * @return {!fireauth.AuthUser}\n */\nfireauth.AuthUser.copyUser = function(user, opt_appOptions,\n opt_redirectStorageManager, opt_frameworks) {\n var appOptions = opt_appOptions || {\n 'apiKey': user.apiKey_,\n 'authDomain': user.authDomain_,\n 'appName': user.appName_\n };\n var newUser = new fireauth.AuthUser(\n appOptions, user.getStsTokenManager().toServerResponse());\n // If redirect storage manager provided, set it.\n if (opt_redirectStorageManager) {\n newUser.setRedirectStorageManager(opt_redirectStorageManager);\n }\n // If frameworks provided, set it.\n if (opt_frameworks) {\n newUser.setFramework(opt_frameworks);\n }\n // Copy remaining properties.\n newUser.copy(user);\n return newUser;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 Utility class to retrieve and cache STS token.\n */\ngoog.provide('fireauth.StsTokenManager');\ngoog.provide('fireauth.StsTokenManager.Response');\ngoog.provide('fireauth.StsTokenManager.ResponseData');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.IdToken');\ngoog.require('fireauth.RpcHandler');\ngoog.require('fireauth.authenum.Error');\ngoog.require('goog.Promise');\ngoog.require('goog.asserts');\n\n\n\n/**\n * Creates STS token manager.\n *\n * @param {!fireauth.RpcHandler} rpcHandler Handler for RPC requests.\n * @constructor\n */\nfireauth.StsTokenManager = function(rpcHandler) {\n /**\n * @const @private {!fireauth.RpcHandler} The RPC handler used to request STS\n * tokens.\n */\n this.rpcHandler_ = rpcHandler;\n /** @private {?string} The STS refresh token. */\n this.refreshToken_ = null;\n /** @private {?fireauth.IdToken} The STS ID token. */\n this.accessToken_ = null;\n};\n\n\n/**\n * @return {!Object} The plain object representation of the STS token manager.\n */\nfireauth.StsTokenManager.prototype.toPlainObject = function() {\n return {\n 'apiKey': this.rpcHandler_.getApiKey(),\n 'refreshToken': this.refreshToken_,\n 'accessToken': this.accessToken_ && this.accessToken_.toString(),\n // To support downgrade flows, return expiration time.\n 'expirationTime': this.getExpirationTime()\n };\n};\n\n\n/**\n * @param {!fireauth.RpcHandler} rpcHandler The RPC handler for the token\n * manager.\n * @param {?Object} obj The plain object whose STS token manager instance is to\n * be returned.\n * @return {?fireauth.StsTokenManager} The STS token manager instance from the\n * plain object provided using the RPC handler provided.\n */\nfireauth.StsTokenManager.fromPlainObject = function(rpcHandler, obj) {\n var stsTokenManager = null;\n if (obj && obj['apiKey']) {\n // These should be always equals and must be enforced in internal use.\n goog.asserts.assert(obj['apiKey'] == rpcHandler.getApiKey());\n stsTokenManager = new fireauth.StsTokenManager(rpcHandler);\n stsTokenManager.setRefreshToken(obj['refreshToken']);\n stsTokenManager.setAccessToken(obj['accessToken']);\n }\n return stsTokenManager;\n};\n\n\n/**\n * @typedef {{\n * accessToken: (?string),\n * refreshToken: (?string)\n * }}\n */\nfireauth.StsTokenManager.Response;\n\n\n/**\n * @typedef {{\n * access_token: (?string|undefined),\n * refresh_token: (?string|undefined)\n * }}\n */\nfireauth.StsTokenManager.ResponseData;\n\n\n/**\n * @param {?string} refreshToken The STS refresh token.\n */\nfireauth.StsTokenManager.prototype.setRefreshToken = function(refreshToken) {\n this.refreshToken_ = refreshToken;\n};\n\n\n/**\n * @param {?string} accessToken The STS access token.\n */\nfireauth.StsTokenManager.prototype.setAccessToken = function(accessToken) {\n this.accessToken_ = fireauth.IdToken.parse(accessToken || '');\n};\n\n\n/**\n * @return {?string} The refresh token.\n */\nfireauth.StsTokenManager.prototype.getRefreshToken = function() {\n return this.refreshToken_;\n};\n\n\n/**\n * @return {number} The STS access token expiration time in milliseconds.\n */\nfireauth.StsTokenManager.prototype.getExpirationTime = function() {\n return (this.accessToken_ && this.accessToken_.getExp() * 1000) || 0;\n};\n\n\n/**\n * The number of milliseconds before the official expiration time of a token\n * to refresh that token, to provide a buffer for RPCs to complete.\n * @const {number}\n */\nfireauth.StsTokenManager.TOKEN_REFRESH_BUFFER = 30 * 1000;\n\n\n/**\n * @return {boolean} Whether the STS access token is expired or not.\n * @private\n */\nfireauth.StsTokenManager.prototype.isExpired_ = function() {\n return goog.now() >\n this.getExpirationTime() - fireauth.StsTokenManager.TOKEN_REFRESH_BUFFER;\n};\n\n\n/**\n * Parses a response from the server that contains STS tokens (e.g. from\n * VerifyAssertion or VerifyPassword) and save the access token, refresh token,\n * and expiration time.\n * @param {!Object} response The backend response.\n * @return {string} The STS access token.\n */\nfireauth.StsTokenManager.prototype.parseServerResponse = function(response) {\n var idToken = response[fireauth.RpcHandler.AuthServerField.ID_TOKEN];\n var refreshToken =\n response[fireauth.RpcHandler.AuthServerField.REFRESH_TOKEN];\n this.setAccessToken(idToken);\n this.setRefreshToken(refreshToken);\n return idToken;\n};\n\n\n/**\n * Converts STS token manager instance to server response object.\n * @return {!Object}\n */\nfireauth.StsTokenManager.prototype.toServerResponse = function() {\n var stsTokenManagerResponse = {};\n stsTokenManagerResponse[fireauth.RpcHandler.AuthServerField.ID_TOKEN] =\n this.accessToken_ && this.accessToken_.toString();\n // Refresh token could be expired.\n stsTokenManagerResponse[fireauth.RpcHandler.AuthServerField.REFRESH_TOKEN] =\n this.getRefreshToken();\n return stsTokenManagerResponse;\n};\n\n\n/**\n * Copies IdToken, refreshToken and expirationTime from tokenManagerToCopy.\n * @param {!fireauth.StsTokenManager} tokenManagerToCopy\n */\nfireauth.StsTokenManager.prototype.copy = function(tokenManagerToCopy) {\n this.accessToken_ = tokenManagerToCopy.accessToken_;\n this.refreshToken_ = tokenManagerToCopy.refreshToken_;\n};\n\n\n/**\n * Exchanges the current refresh token with an access and refresh token.\n * @return {!goog.Promise<?fireauth.StsTokenManager.Response>}\n * @private\n */\nfireauth.StsTokenManager.prototype.exchangeRefreshToken_ = function() {\n var data = {\n 'grant_type': 'refresh_token',\n 'refresh_token': this.refreshToken_\n };\n return this.requestToken_(data);\n};\n\n\n/**\n * Sends a request to STS token endpoint for an access/refresh token.\n * @param {!Object} data The request data to send to STS token endpoint.\n * @return {!goog.Promise<?fireauth.StsTokenManager.Response>}\n * @private\n */\nfireauth.StsTokenManager.prototype.requestToken_ = function(data) {\n var self = this;\n // Send RPC request to STS token endpoint.\n return this.rpcHandler_.requestStsToken(data).then(function(resp) {\n var response = /** @type {!fireauth.StsTokenManager.ResponseData} */ (resp);\n self.accessToken_ = fireauth.IdToken.parse(\n response[fireauth.RpcHandler.StsServerField.ACCESS_TOKEN]);\n self.refreshToken_ =\n response[fireauth.RpcHandler.StsServerField.REFRESH_TOKEN];\n return /** @type {!fireauth.StsTokenManager.Response} */ ({\n 'accessToken': self.accessToken_.toString(),\n 'refreshToken': self.refreshToken_\n });\n }).thenCatch(function(error) {\n // Refresh token expired or user deleted. In this case, reset refresh token\n // to prevent sending the request again to the STS server unless\n // the token is manually updated, perhaps via successful reauthentication.\n if (error['code'] == 'auth/user-token-expired') {\n self.refreshToken_ = null;\n }\n throw error;\n });\n};\n\n\n/** @return {boolean} Whether the refresh token is expired. */\nfireauth.StsTokenManager.prototype.isRefreshTokenExpired = function() {\n return !!(this.accessToken_ && !this.refreshToken_);\n};\n\n\n/**\n * Returns an STS token. If the cached one is unexpired it is directly returned.\n * Otherwise the existing ID token or refresh token is exchanged for a new one.\n * If there is no user signed in, returns null.\n *\n * @param {boolean=} opt_forceRefresh Whether to force refresh token exchange.\n * @return {!goog.Promise<?fireauth.StsTokenManager.Response>}\n */\nfireauth.StsTokenManager.prototype.getToken = function(opt_forceRefresh) {\n var self = this;\n var forceRefresh = !!opt_forceRefresh;\n // Refresh token is expired.\n if (this.isRefreshTokenExpired()) {\n return goog.Promise.reject(\n new fireauth.AuthError(fireauth.authenum.Error.TOKEN_EXPIRED));\n }\n if (!forceRefresh && this.accessToken_ && !this.isExpired_()) {\n // Cached STS access token not expired, return it.\n return /** @type {!goog.Promise} */ (goog.Promise.resolve({\n 'accessToken': self.accessToken_.toString(),\n 'refreshToken': self.refreshToken_\n }));\n } else if (this.refreshToken_) {\n // Expired but refresh token available, exchange refresh token for STS\n // token.\n return this.exchangeRefreshToken_();\n } else {\n // No token, return null token.\n return goog.Promise.resolve(\n /** @type {?fireauth.StsTokenManager.Response} */ (null));\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.storage.RedirectUserManager class which\n * provides utilities to store, retrieve and delete an Auth user during a\n * redirect operation.\n */\n\ngoog.provide('fireauth.storage.RedirectUserManager');\n\ngoog.require('fireauth.AuthUser');\ngoog.require('fireauth.authStorage');\n\n\n/**\n * Defines the Auth redirect user storage manager. It provides methods\n * to store, load and delete a user going through a link with redirect\n * operation.\n * @param {string} appId The Auth state's application ID.\n * @param {?fireauth.authStorage.Manager=} opt_manager The underlying storage\n * manager to use. If none is provided, the default global instance is used.\n * @constructor @struct @final\n */\nfireauth.storage.RedirectUserManager = function(appId, opt_manager) {\n /** @const @private{string} appId The Auth state's application ID. */\n this.appId_ = appId;\n /**\n * @const @private{!fireauth.authStorage.Manager} The underlying storage\n * manager.\n */\n this.manager_ = opt_manager || fireauth.authStorage.Manager.getInstance();\n};\n\n\n/**\n * @const @private{!fireauth.authStorage.Key} The Auth redirect user storage\n * identifier.\n */\nfireauth.storage.RedirectUserManager.REDIRECT_USER_KEY_ = {\n name: 'redirectUser',\n persistent: fireauth.authStorage.Persistence.SESSION\n};\n\n\n/**\n * Stores the user being redirected for the provided application ID.\n * @param {!fireauth.AuthUser} redirectUser The user being redirected.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.RedirectUserManager.prototype.setRedirectUser =\n function(redirectUser) {\n return this.manager_.set(\n fireauth.storage.RedirectUserManager.REDIRECT_USER_KEY_,\n redirectUser.toPlainObject(),\n this.appId_);\n};\n\n\n/**\n * Removes the stored redirected user for provided app ID.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.RedirectUserManager.prototype.removeRedirectUser =\n function() {\n return this.manager_.remove(\n fireauth.storage.RedirectUserManager.REDIRECT_USER_KEY_, this.appId_);\n};\n\n\n/**\n * @param {?string=} opt_authDomain The optional Auth domain to override if\n * provided.\n * @return {!goog.Promise<?fireauth.AuthUser>} A promise that resolves with\n * the stored redirected user for the provided app ID.\n */\nfireauth.storage.RedirectUserManager.prototype.getRedirectUser =\n function(opt_authDomain) {\n return this.manager_.get(\n fireauth.storage.RedirectUserManager.REDIRECT_USER_KEY_, this.appId_)\n .then(function(response) {\n // If potential user saved, override Auth domain if authDomain is\n // provided.\n if (response && opt_authDomain) {\n response['authDomain'] = opt_authDomain;\n }\n return fireauth.AuthUser.fromPlainObject(response || {});\n });\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 fireauth.storage.UserManager class which provides\n * utilities to retrieve, store and delete the currently logged in user and to\n * listen to external authentication changes for the same app.\n * With the ability to modify Auth state persistence. The behavior is as\n * follows:\n * Common cases:\n * <ul>\n * <li>Initially, local and session storage will be checked and the state will\n * be loaded from there without changing it unless the developer calls\n * setPersistence explicitly. The requirement is that at any time, Auth\n * state can be saved using one type only of persistence and never more than\n * one.</li>\n * <li>If the developer tries to sign in with no persistence specified, the\n * default setting will be used (local in a browser).</li>\n * <li>If the user is not signed in and persistence is set, any future sign-in\n * attempt will use that type of persistence.</li>\n * <li>If the user is signed in and the developer then switches persistence,\n * that existing signed in user will change persistence to the new one. All\n * future sign-in attempts will use that same persistence.</li>\n * <li>When signInWithRedirect is called, the current persistence type is passed\n * along with that request and on redirect back to app will pass that type\n * to determine how that state is saved (overriding the default). If the\n * persistence is explicitly specified on that page, it will change that\n * redirected Auth state persistence. This is the only time the persistence\n * is passed from one page to another.\n * So internally, on redirect, the redirect state is retrieved and then we\n * check: If the persistence was explicitly provided, we override the\n * previous type and save the Auth state using that. If no persistence was\n * explicitly provided, we use the previous persistence type that was passed\n * in the redirect response.</li>\n * </ul>\n * Behavior across tabs:\n * <ul>\n * <li>User can sign in using session storage on multiple tabs. Each tab cannot\n * see the state of the other tab.</li>\n * <li>Any attempt to sign in using local storage will be detected and\n * synchronized on all tabs. If the user was previously signed in on a\n * specific tab using session storage, that state will be cleared.</li>\n * <li>If the user was previously signed in using local storage and then signs\n * in using session storage, the user will be signed in on the current tab\n * only and signed out on all other tabs.</li>\n * <li>Similar logic is applied to the ‘none’ state. In one tab, switching to\n * ‘none’ state will delete any previously saved state in ‘local’\n * persistence in other tabs.</li>\n * </ul>\n */\n\ngoog.provide('fireauth.storage.UserManager');\n\ngoog.require('fireauth.AuthUser');\ngoog.require('fireauth.authStorage');\ngoog.require('goog.Promise');\n\n\n/**\n * Defines the Auth user storage manager. It provides methods to\n * store, load and delete an authenticated current user. It also provides\n * methods to listen to external user changes (updates, sign in, sign out, etc.)\n * @param {string} appId The Auth state's application ID.\n * @param {?fireauth.authStorage.Manager=} opt_manager The underlying storage\n * manager to use. If none is provided, the default global instance is used.\n * @constructor @struct @final\n */\nfireauth.storage.UserManager = function(appId, opt_manager) {\n /** @const @private{string} appId The Auth state's application ID. */\n this.appId_ = appId;\n /**\n * @const @private{!fireauth.authStorage.Manager} The underlying storage\n * manager.\n */\n this.manager_ = opt_manager || fireauth.authStorage.Manager.getInstance();\n /**\n * @private {?fireauth.authStorage.Key} The current Auth user storage\n * identifier.\n */\n this.currentAuthUserKey_ = null;\n /**\n * @private {!goog.Promise} Storage operation serializer promise. This will\n * initialize the current persistence used and clean up any duplicate\n * states or temporary values (persistence for pending redirect).\n * Afterwards this is used to queue storage requests to make sure\n * storage operations are always synchronized and read/write events are\n * processed on the same storage.\n */\n this.onReady_ = this.initialize_();\n // This internal listener will always run before the external ones.\n // This is needed to queue processing of this first before any getCurrentUser\n // is called from external listeners.\n this.manager_.addListener(\n fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence.LOCAL),\n this.appId_,\n goog.bind(this.switchToLocalOnExternalEvent_, this));\n};\n\n\n/**\n * Switches to local storage on external storage event. This will happen when\n * state is specified as local in an external tab while it is none or session\n * in the current one. If a user signs in in an external tab, the current window\n * should detect this, clear existing storage and switch to local storage.\n * @private\n */\nfireauth.storage.UserManager.prototype.switchToLocalOnExternalEvent_ =\n function() {\n var self = this;\n var localKey = fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence.LOCAL);\n // Wait for any pending operation to finish first.\n // Block next read/write operation until persistence is transitioned to\n // local.\n this.waitForReady_(function() {\n return goog.Promise.resolve().then(function() {\n // If current persistence is not already local.\n if (self.currentAuthUserKey_ &&\n self.currentAuthUserKey_.persistent !=\n fireauth.authStorage.Persistence.LOCAL) {\n // Check if new current user is available in local storage.\n return self.manager_.get(localKey, self.appId_);\n }\n return null;\n }).then(function(response) {\n // Sign in on an external tab.\n if (response) {\n // Remove any existing non-local user.\n return self.removeAllExcept_(\n fireauth.authStorage.Persistence.LOCAL).then(function() {\n // Set persistence to local.\n self.currentAuthUserKey_ = localKey;\n });\n }\n });\n });\n};\n\n\n/**\n * Removes all states stored in all supported persistence types excluding the\n * specified one.\n * @param {?fireauth.authStorage.Persistence} persistence The type of storage\n * persistence to switch to.\n * @return {!goog.Promise} The promise that resolves when all stored values are\n * removed for types of storage excluding specified persistence. This helps\n * ensure there is always one type of persistence at any time.\n * @private\n */\nfireauth.storage.UserManager.prototype.removeAllExcept_ =\n function(persistence) {\n var promises = [];\n // Queue all promises to remove current user in any other persistence type.\n for (var key in fireauth.authStorage.Persistence) {\n // Skip specified persistence.\n if (fireauth.authStorage.Persistence[key] !== persistence) {\n var storageKey = fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence[key]);\n promises.push(this.manager_.remove(\n /** @type {!fireauth.authStorage.Key} */ (storageKey),\n this.appId_));\n }\n }\n // Clear persistence key (only useful for initial load upon returning from a\n // a redirect sign-in operation).\n promises.push(this.manager_.remove(\n fireauth.storage.UserManager.PERSISTENCE_KEY_,\n this.appId_));\n return goog.Promise.all(promises);\n};\n\n\n/**\n * Initializes the current persistence state. This will check the 3 supported\n * types. The first one that is found will be the current persistence. All\n * others will be cleared. If none is found we check PERSISTENCE_KEY_ which\n * when specified means that the operation is returning from a\n * signInWithRedirect call. This persistence will be applied.\n * Otherwise the default local persistence is used.\n * @return {!goog.Promise} A promise that resolves when the current persistence\n * is resolved.\n * @private\n */\nfireauth.storage.UserManager.prototype.initialize_ = function() {\n var self = this;\n // Local key.\n var localKey = fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence.LOCAL);\n // Session key.\n var sessionKey = fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence.SESSION);\n // In memory key. This is unlikely to contain anything on load.\n var inMemoryKey = fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence.NONE);\n // Migrate any old currentUser from localStorage to indexedDB.\n // This keeps any user signed in without the need for reauthentication and\n // minimizes risks of dangling Auth states.\n return this.manager_.migrateFromLocalStorage(\n localKey, this.appId_).then(function() {\n // Check if state is stored in session storage.\n return self.manager_.get(sessionKey, self.appId_);\n }).then(function(response) {\n if (response) {\n // Session storage is being used.\n return sessionKey;\n } else {\n // Session storage is empty. Check in memory storage.\n return self.manager_.get(inMemoryKey, self.appId_)\n .then(function(response) {\n if (response) {\n // In memory storage being used.\n return inMemoryKey;\n } else {\n // Check local storage.\n return self.manager_.get(localKey, self.appId_)\n .then(function(response) {\n if (response) {\n // Local storage being used.\n return localKey;\n } else {\n // Nothing found in any supported storage.\n // Check current user persistence in storage.\n return self.manager_.get(\n fireauth.storage.UserManager.PERSISTENCE_KEY_,\n self.appId_).then(function(persistence) {\n if (persistence) {\n // Sign in with redirect operation, apply this\n // persistence to any current user.\n return fireauth.storage.UserManager\n .getAuthUserKey_(persistence);\n } else {\n // No persistence found, use the default.\n return localKey;\n }\n });\n }\n });\n }\n });\n }\n }).then(function(currentKey) {\n // Set current key according to the persistence detected.\n self.currentAuthUserKey_ = currentKey;\n // Make sure only one state available. Clean up everything else.\n return self.removeAllExcept_(currentKey.persistent);\n }).thenCatch(function(error) {\n // If an error occurs in the process and no current key detected, set to\n // persistence value to default.\n if (!self.currentAuthUserKey_) {\n self.currentAuthUserKey_ = localKey;\n }\n });\n};\n\n\n/**\n * @const @private {string} The Auth current user storage identifier name.\n */\nfireauth.storage.UserManager.AUTH_USER_KEY_NAME_ = 'authUser';\n\n\n/**\n * @const @private{!fireauth.authStorage.Key} The Auth user storage persistence\n * identifier. This is needed to remember the previous persistence state for\n * sign-in with redirect.\n */\nfireauth.storage.UserManager.PERSISTENCE_KEY_ = {\n name: 'persistence',\n persistent: fireauth.authStorage.Persistence.SESSION\n};\n\n\n/**\n * Returns the Auth user key corresponding to the persistence type provided.\n * @param {!fireauth.authStorage.Persistence} persistence The key for the\n * specified type of persistence.\n * @return {!fireauth.authStorage.Key} The corresponding Auth user storage\n * identifier.\n * @private\n */\nfireauth.storage.UserManager.getAuthUserKey_ = function(persistence) {\n return {\n name: fireauth.storage.UserManager.AUTH_USER_KEY_NAME_,\n persistent: persistence\n };\n};\n\n\n/**\n * Sets the persistence to the specified type.\n * If an existing user already is in storage, it copies that value to the new\n * storage and clears all the others.\n * @param {!fireauth.authStorage.Persistence} persistence The type of storage\n * persistence to switch to.\n * @return {!goog.Promise} A promise that resolves when persistence change is\n * applied.\n */\nfireauth.storage.UserManager.prototype.setPersistence = function(persistence) {\n var currentUser = null;\n var self = this;\n // Validate the persistence type provided. This will throw a synchronous error\n // if invalid.\n fireauth.authStorage.validatePersistenceArgument(persistence);\n // Wait for turn in queue.\n return this.waitForReady_(function() {\n // If persistence hasn't changed, do nothing.\n if (persistence != self.currentAuthUserKey_.persistent) {\n // Persistence changed. Copy from current storage to new one.\n return self.manager_.get(\n /** @type {!fireauth.authStorage.Key} */ (self.currentAuthUserKey_),\n self.appId_).then(function(result) {\n // Save current user.\n currentUser = result;\n // Clear from current storage.\n return self.removeAllExcept_(persistence);\n }).then(function() {\n // Update persistence key to the new one.\n self.currentAuthUserKey_ =\n fireauth.storage.UserManager.getAuthUserKey_(persistence);\n // Copy current storage type to the new one.\n if (currentUser) {\n return self.manager_.set(\n /** @type {!fireauth.authStorage.Key} */ (\n self.currentAuthUserKey_),\n currentUser,\n self.appId_);\n }\n });\n }\n // No change in persistence type.\n return goog.Promise.resolve();\n });\n};\n\n\n/**\n * Saves the current persistence type so it can be retrieved after a page\n * redirect. This is relevant for signInWithRedirect.\n * @return {!goog.Promise} Promise that resolve when current persistence is\n * saved.\n */\nfireauth.storage.UserManager.prototype.savePersistenceForRedirect = function() {\n var self = this;\n return this.waitForReady_(function() {\n // Save persistence to survive redirect.\n return self.manager_.set(\n fireauth.storage.UserManager.PERSISTENCE_KEY_,\n self.currentAuthUserKey_.persistent,\n self.appId_);\n });\n};\n\n\n/**\n * Stores the current Auth user for the provided application ID.\n * @param {!fireauth.AuthUser} currentUser The app current Auth user to save.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.UserManager.prototype.setCurrentUser = function(currentUser) {\n var self = this;\n // Wait for any pending persistence change to be resolved.\n return this.waitForReady_(function() {\n return self.manager_.set(\n /** @type {!fireauth.authStorage.Key} */ (self.currentAuthUserKey_),\n currentUser.toPlainObject(),\n self.appId_);\n });\n};\n\n\n/**\n * Removes the stored current user for provided app ID.\n * @return {!goog.Promise<void>} A promise that resolves on success.\n */\nfireauth.storage.UserManager.prototype.removeCurrentUser = function() {\n var self = this;\n // Wait for any pending persistence change to be resolved.\n return this.waitForReady_(function() {\n return self.manager_.remove(\n /** @type {!fireauth.authStorage.Key} */ (self.currentAuthUserKey_),\n self.appId_);\n });\n};\n\n\n/**\n * @param {?string=} opt_authDomain The optional Auth domain to override if\n * provided.\n * @return {!goog.Promise<?fireauth.AuthUser>} A promise that resolves with\n * the stored current user for the provided app ID.\n */\nfireauth.storage.UserManager.prototype.getCurrentUser =\n function(opt_authDomain) {\n var self = this;\n // Wait for any pending persistence change to be resolved.\n return this.waitForReady_(function() {\n return self.manager_.get(\n /** @type {!fireauth.authStorage.Key} */ (self.currentAuthUserKey_),\n self.appId_).then(function(response) {\n // If potential user saved, override Auth domain if authDomain is\n // provided.\n // This is useful in cases where on one page the developer initializes\n // the Auth instance without authDomain and signs in user using\n // headless methods. On another page, Auth is initialized with\n // authDomain for the purpose of linking with a popup. The loaded user\n // (stored without the authDomain) must have this field updated with\n // the current authDomain.\n if (response && opt_authDomain) {\n response['authDomain'] = opt_authDomain;\n }\n return fireauth.AuthUser.fromPlainObject(response || {});\n });\n });\n};\n\n\n/**\n * Serializes storage access operations especially since persistence\n * could be updated from one type to the other while read/write operations\n * occur.\n * @param {function():!goog.Promise<T>} cb The promise return callback to chain\n * when pending operations are resolved.\n * @return {!goog.Promise<T>} The resulting promise that resolves when provided\n * promise finally resolves.\n * @template T\n * @private\n */\nfireauth.storage.UserManager.prototype.waitForReady_ = function(cb) {\n // Wait for any pending persistence change to be resolved before running\n // storage related operation. Chain to onReady so next call will wait for\n // this operation to resolve.\n // While an error is unlikely, run callback even if it happens, otherwise\n // no storage related event will be allowed to complete after an error.\n this.onReady_ = this.onReady_.then(cb, cb);\n return this.onReady_;\n};\n\n\n/**\n * Adds a listener to Auth current user change event for app ID provided.\n * @param {!function()} listener The listener to run on current user change\n * event.\n */\nfireauth.storage.UserManager.prototype.addCurrentUserChangeListener =\n function(listener) {\n // When this is triggered, getCurrentUser is called, that will have to wait\n // for switchToLocalOnExternalEvent_ to resolve which is ahead of it in the\n // queue.\n this.manager_.addListener(\n fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence.LOCAL),\n this.appId_,\n listener);\n};\n\n\n/**\n * Removes a listener to Auth current user change event for app ID provided.\n * @param {!function()} listener The listener to remove from current user change\n * event changes.\n */\nfireauth.storage.UserManager.prototype.removeCurrentUserChangeListener =\n function(listener) {\n this.manager_.removeListener(\n fireauth.storage.UserManager.getAuthUserKey_(\n fireauth.authStorage.Persistence.LOCAL),\n this.appId_,\n listener);\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 The headless Auth class used for authenticating Firebase users.\n */\n\ngoog.provide('fireauth.Auth');\n\ngoog.require('fireauth.ActionCodeInfo');\ngoog.require('fireauth.ActionCodeSettings');\ngoog.require('fireauth.AdditionalUserInfo');\ngoog.require('fireauth.AuthCredential');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthEvent');\ngoog.require('fireauth.AuthEventHandler');\ngoog.require('fireauth.AuthEventManager');\ngoog.require('fireauth.AuthProvider');\ngoog.require('fireauth.AuthSettings');\ngoog.require('fireauth.AuthUser');\ngoog.require('fireauth.ConfirmationResult');\ngoog.require('fireauth.EmailAuthProvider');\ngoog.require('fireauth.MultiFactorError');\ngoog.require('fireauth.RpcHandler');\ngoog.require('fireauth.UserEventType');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.deprecation');\ngoog.require('fireauth.idp');\ngoog.require('fireauth.iframeclient.IfcHandler');\ngoog.require('fireauth.object');\ngoog.require('fireauth.storage.RedirectUserManager');\ngoog.require('fireauth.storage.UserManager');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.array');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.object');\n\n\n\n/**\n * Creates the Firebase Auth corresponding for the App provided.\n *\n * @param {!firebase.app.App} app The corresponding Firebase App.\n * @constructor\n * @implements {fireauth.AuthEventHandler}\n * @implements {firebase.Service}\n * @extends {goog.events.EventTarget}\n */\nfireauth.Auth = function(app) {\n /** @private {boolean} Whether this instance is deleted. */\n this.deleted_ = false;\n /** The Auth instance's settings object. */\n fireauth.object.setReadonlyProperty(\n this, 'settings', new fireauth.AuthSettings());\n /** Auth's corresponding App. */\n fireauth.object.setReadonlyProperty(this, 'app', app);\n // Initialize RPC handler.\n // API key is required for web client RPC calls.\n if (this.app_().options && this.app_().options['apiKey']) {\n var clientFullVersion = firebase.SDK_VERSION ?\n fireauth.util.getClientVersion(\n fireauth.util.ClientImplementation.JSCORE, firebase.SDK_VERSION) :\n null;\n this.rpcHandler_ = new fireauth.RpcHandler(\n this.app_().options && this.app_().options['apiKey'],\n // Get the client Auth endpoint used.\n fireauth.constants.getEndpointConfig(fireauth.constants.clientEndpoint),\n clientFullVersion);\n } else {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_API_KEY);\n }\n /** @private {!Array<!goog.Promise<*, *>|!goog.Promise<void>>} List of\n * pending promises. */\n this.pendingPromises_ = [];\n /** @private {!Array<!function(?string)>} Auth token listeners. */\n this.authListeners_ = [];\n /** @private {!Array<!function(?string)>} User change listeners. */\n this.userChangeListeners_ = [];\n /**\n * @private {!firebase.Subscribe} The subscribe function to the Auth ID token\n * change observer. This will trigger on ID token changes, including\n * token refresh on the same user.\n */\n this.onIdTokenChanged_ = firebase.INTERNAL.createSubscribe(\n goog.bind(this.initIdTokenChangeObserver_, this));\n /**\n * @private {?string|undefined} The UID of the user that last triggered the\n * user state change listener.\n */\n this.userStateChangeUid_ = undefined;\n /**\n * @private {!firebase.Subscribe} The subscribe function to the user state\n * change observer.\n */\n this.onUserStateChanged_ = firebase.INTERNAL.createSubscribe(\n goog.bind(this.initUserStateObserver_, this));\n // Set currentUser to null.\n this.setCurrentUser_(null);\n /**\n * @private {!fireauth.storage.UserManager} The Auth user storage\n * manager instance.\n */\n this.userStorageManager_ =\n new fireauth.storage.UserManager(this.getStorageKey());\n /**\n * @private {!fireauth.storage.RedirectUserManager} The redirect user\n * storagemanager instance.\n */\n this.redirectUserStorageManager_ =\n new fireauth.storage.RedirectUserManager(this.getStorageKey());\n /**\n * @private {!goog.Promise<undefined>} Promise that resolves when initial\n * state is loaded from storage.\n */\n this.authStateLoaded_ = this.registerPendingPromise_(this.initAuthState_());\n /**\n * @private {!goog.Promise<undefined>} Promise that resolves when state and\n * redirect result is ready, after which sign in and sign out operations\n * are safe to execute.\n */\n this.redirectStateIsReady_ = this.registerPendingPromise_(\n this.initAuthRedirectState_());\n /** @private {boolean} Whether initial state has already been resolved. */\n this.isStateResolved_ = false;\n /**\n * @private {!function()} The syncAuthChanges function with context set to\n * auth instance.\n */\n this.getSyncAuthUserChanges_ = goog.bind(this.syncAuthUserChanges_, this);\n /** @private {!function(!fireauth.AuthUser):!goog.Promise} The handler for\n * user state changes. */\n this.userStateChangeListener_ =\n goog.bind(this.handleUserStateChange_, this);\n /** @private {!function(!Object)} The handler for user token changes. */\n this.userTokenChangeListener_ =\n goog.bind(this.handleUserTokenChange_, this);\n /** @private {!function(!Object)} The handler for user deletion. */\n this.userDeleteListener_ = goog.bind(this.handleUserDelete_, this);\n /** @private {!function(!Object)} The handler for user invalidation. */\n this.userInvalidatedListener_ = goog.bind(this.handleUserInvalidated_, this);\n /**\n * @private {?fireauth.AuthEventManager} The Auth event manager instance.\n */\n this.authEventManager_ = null;\n // TODO: find better way to enable or disable auth event manager.\n if (fireauth.AuthEventManager.ENABLED) {\n // Initialize Auth event manager to handle popup and redirect operations.\n this.initAuthEventManager_();\n }\n\n // Export INTERNAL namespace.\n this.INTERNAL = {};\n this.INTERNAL['delete'] = goog.bind(this.delete, this);\n this.INTERNAL['logFramework'] = goog.bind(this.logFramework, this);\n /**\n * @private {number} The number of Firebase services subscribed to Auth\n * changes.\n */\n this.firebaseServices_ = 0;\n // Add call to superclass constructor.\n fireauth.Auth.base(this, 'constructor');\n // Initialize readable/writable Auth properties.\n this.initializeReadableWritableProps_();\n /**\n * @private {!Array<string>} List of Firebase frameworks/libraries used. This\n * is currently only used to log FirebaseUI.\n */\n this.frameworks_ = [];\n};\ngoog.inherits(fireauth.Auth, goog.events.EventTarget);\n\n\n/**\n * Language code change custom event.\n * @param {?string} languageCode The new language code.\n * @constructor\n * @extends {goog.events.Event}\n */\nfireauth.Auth.LanguageCodeChangeEvent = function(languageCode) {\n goog.events.Event.call(\n this, fireauth.constants.AuthEventType.LANGUAGE_CODE_CHANGED);\n this.languageCode = languageCode;\n};\ngoog.inherits(fireauth.Auth.LanguageCodeChangeEvent, goog.events.Event);\n\n\n/**\n * Framework change custom event.\n * @param {!Array<string>} frameworks The new frameworks array.\n * @constructor\n * @extends {goog.events.Event}\n */\nfireauth.Auth.FrameworkChangeEvent = function(frameworks) {\n goog.events.Event.call(\n this, fireauth.constants.AuthEventType.FRAMEWORK_CHANGED);\n this.frameworks = frameworks;\n};\ngoog.inherits(fireauth.Auth.FrameworkChangeEvent, goog.events.Event);\n\n\n/**\n * Changes the Auth state persistence to the specified one.\n * @param {!fireauth.authStorage.Persistence} persistence The Auth state\n * persistence mechanism.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.setPersistence = function(persistence) {\n // TODO: fix auth.delete() behavior and how this affects persistence\n // change after deletion.\n // Throw an error if already destroyed.\n // Set current persistence.\n var p = this.userStorageManager_.setPersistence(persistence);\n return /** @type {!goog.Promise<void>} */ (this.registerPendingPromise_(p));\n};\n\n\n/**\n * Get rid of Closure warning - the property is adding in the constructor.\n * @type {!firebase.app.App}\n */\nfireauth.Auth.prototype.app;\n\n\n/**\n * Sets the language code.\n * @param {?string} languageCode\n */\nfireauth.Auth.prototype.setLanguageCode = function(languageCode) {\n // Don't do anything if no change detected.\n if (this.languageCode_ !== languageCode && !this.deleted_) {\n this.languageCode_ = languageCode;\n // Update custom Firebase locale field.\n this.rpcHandler_.updateCustomLocaleHeader(this.languageCode_);\n // Notify external language code change listeners.\n this.notifyLanguageCodeListeners_();\n }\n};\n\n\n/**\n * Returns the current auth instance's language code if available.\n * @return {?string}\n */\nfireauth.Auth.prototype.getLanguageCode = function() {\n return this.languageCode_;\n};\n\n\n/**\n * Sets the current language to the default device/browser preference.\n */\nfireauth.Auth.prototype.useDeviceLanguage = function() {\n this.setLanguageCode(fireauth.util.getUserLanguage());\n};\n\n\n/**\n * @param {string} frameworkId The framework identifier.\n */\nfireauth.Auth.prototype.logFramework = function(frameworkId) {\n // Theoretically multiple frameworks could be used\n // (angularfire and FirebaseUI). Once a framework is used, it is not going\n // to be unused, so no point adding a method to remove the framework ID.\n this.frameworks_.push(frameworkId);\n // Update the client version in RPC handler with the new frameworks.\n this.rpcHandler_.updateClientVersion(firebase.SDK_VERSION ?\n fireauth.util.getClientVersion(\n fireauth.util.ClientImplementation.JSCORE, firebase.SDK_VERSION,\n this.frameworks_) :\n null);\n this.dispatchEvent(new fireauth.Auth.FrameworkChangeEvent(\n this.frameworks_));\n};\n\n\n/** @return {!Array<string>} The current Firebase frameworks. */\nfireauth.Auth.prototype.getFramework = function() {\n return goog.array.clone(this.frameworks_);\n};\n\n\n/**\n * Updates the framework list on the provided user and configures the user to\n * listen to the Auth instance for any framework ID changes.\n * @param {!fireauth.AuthUser} user The user to whose framework list needs to be\n * updated.\n * @private\n */\nfireauth.Auth.prototype.setUserFramework_ = function(user) {\n // Sets the framework ID on the user.\n user.setFramework(this.frameworks_);\n // Sets current Auth instance as framework list change dispatcher on the user.\n user.setFrameworkChangeDispatcher(this);\n};\n\n\n/**\n * Sets the tenant ID.\n * @param {?string} tenantId The tenant ID of the tenant project if available.\n */\nfireauth.Auth.prototype.setTenantId = function(tenantId) {\n // Don't do anything if no change detected.\n if (this.tenantId_ !== tenantId && !this.deleted_) {\n this.tenantId_ = tenantId;\n this.rpcHandler_.updateTenantId(this.tenantId_);\n }\n};\n\n\n/**\n * Returns the current Auth instance's tenant ID.\n * @return {?string}\n */\nfireauth.Auth.prototype.getTenantId = function() {\n return this.tenantId_;\n};\n\n\n/**\n * Initializes readable/writable properties on Auth.\n * @suppress {invalidCasts}\n * @private\n */\nfireauth.Auth.prototype.initializeReadableWritableProps_ = function() {\n Object.defineProperty(/** @type {!Object} */ (this), 'lc', {\n /**\n * @this {!Object}\n * @return {?string} The current language code.\n */\n get: function() {\n return this.getLanguageCode();\n },\n /**\n * @this {!Object}\n * @param {string} value The new language code.\n */\n set: function(value) {\n this.setLanguageCode(value);\n },\n enumerable: false\n });\n // Initialize to null.\n /** @private {?string} The current Auth instance's language code. */\n this.languageCode_ = null;\n\n // Initialize tenant ID.\n Object.defineProperty(/** @type {!Object} */ (this), 'ti', {\n /**\n * @this {!Object}\n * @return {?string} The current tenant ID.\n */\n get: function() {\n return this.getTenantId();\n },\n /**\n * @this {!Object}\n * @param {?string} value The new tenant ID.\n */\n set: function(value) {\n this.setTenantId(value);\n },\n enumerable: false\n });\n // Initialize to null.\n /** @private {?string} The current Auth instance's tenant ID. */\n this.tenantId_ = null;\n};\n\n\n/**\n * Notifies all external listeners of the language code change.\n * @private\n */\nfireauth.Auth.prototype.notifyLanguageCodeListeners_ = function() {\n // Notify external listeners on the language code change.\n this.dispatchEvent(new fireauth.Auth.LanguageCodeChangeEvent(\n this.getLanguageCode()));\n};\n\n\n\n\n\n/**\n * @return {!Object} The object representation of the Auth instance.\n * @override\n */\nfireauth.Auth.prototype.toJSON = function() {\n // Return the plain object representation in case JSON.stringify is called on\n // an Auth instance.\n return {\n 'apiKey': this.app_().options['apiKey'],\n 'authDomain': this.app_().options['authDomain'],\n 'appName': this.app_().name,\n 'currentUser': this.currentUser_() && this.currentUser_().toPlainObject()\n };\n};\n\n\n/**\n * Returns the Auth event manager promise.\n * @return {!goog.Promise<!fireauth.AuthEventManager>}\n * @private\n */\nfireauth.Auth.prototype.getAuthEventManager_ = function() {\n // Either return cached Auth event manager promise provider if available or a\n // promise that rejects with missing Auth domain error.\n return this.eventManagerProviderPromise_ ||\n goog.Promise.reject(\n new fireauth.AuthError(fireauth.authenum.Error.MISSING_AUTH_DOMAIN));\n};\n\n\n/**\n * Initializes the Auth event manager when state is ready.\n * @private\n */\nfireauth.Auth.prototype.initAuthEventManager_ = function() {\n // Initialize Auth event manager on initState.\n var self = this;\n var authDomain = this.app_().options['authDomain'];\n var apiKey = this.app_().options['apiKey'];\n // Make sure environment also supports popup and redirect.\n if (authDomain && fireauth.util.isPopupRedirectSupported()) {\n // Auth domain is required for Auth event manager to resolve.\n // Auth state has to be loaded first. One reason is to process link events.\n this.eventManagerProviderPromise_ = this.authStateLoaded_.then(function() {\n if (self.deleted_) {\n return;\n }\n // By this time currentUser should be ready if available and will be able\n // to resolve linkWithRedirect if detected.\n self.authEventManager_ = fireauth.AuthEventManager.getManager(\n authDomain, apiKey, self.app_().name);\n // Subscribe Auth instance.\n self.authEventManager_.subscribe(self);\n // Subscribe current user by enabling popup and redirect on that user.\n if (self.currentUser_()) {\n self.currentUser_().enablePopupRedirect();\n }\n // If a redirect user is present, subscribe to popup and redirect events.\n // In case current user was not available and the developer called link\n // with redirect on a signed out user, this will work and the linked\n // logged out user will be returned in getRedirectResult.\n // current user and redirect user are the same (was already logged in),\n // currentUser will have priority as it is subscribed before redirect\n // user. This change will also allow further popup and redirect events on\n // the redirect user going forward.\n if (self.redirectUser_) {\n self.redirectUser_.enablePopupRedirect();\n // Set the user language for the redirect user.\n self.setUserLanguage_(\n /** @type {!fireauth.AuthUser} */ (self.redirectUser_));\n // Set the user Firebase frameworks for the redirect user.\n self.setUserFramework_(\n /** @type {!fireauth.AuthUser} */ (self.redirectUser_));\n // Reference to redirect user no longer needed.\n self.redirectUser_ = null;\n }\n return self.authEventManager_;\n });\n }\n};\n\n\n/**\n * @param {!fireauth.AuthEvent.Type} mode The Auth type mode.\n * @param {?string=} opt_eventId The event ID.\n * @return {boolean} Whether the auth event handler can handler the provided\n * event.\n * @override\n */\nfireauth.Auth.prototype.canHandleAuthEvent = function(mode, opt_eventId) {\n // Only sign in events are handled.\n switch (mode) {\n // Accept all general sign in with redirect and unknowns.\n // Migrating redirect events to use session storage will prevent this event\n // from leaking to other tabs.\n case fireauth.AuthEvent.Type.UNKNOWN:\n case fireauth.AuthEvent.Type.SIGN_IN_VIA_REDIRECT:\n return true;\n case fireauth.AuthEvent.Type. SIGN_IN_VIA_POPUP:\n // Pending sign in with popup event must match the stored popup event ID.\n return this.popupEventId_ == opt_eventId &&\n !!this.pendingPopupResolvePromise_;\n default:\n return false;\n }\n};\n\n\n/**\n * Completes the pending popup operation. If error is not null, rejects with the\n * error. Otherwise, it resolves with the popup redirect result.\n * @param {!fireauth.AuthEvent.Type} mode The Auth type mode.\n * @param {?fireauth.AuthEventManager.Result} popupRedirectResult The result\n * to resolve with when no error supplied.\n * @param {?fireauth.AuthError} error When supplied, the promise will reject.\n * @param {?string=} opt_eventId The event ID.\n * @override\n */\nfireauth.Auth.prototype.resolvePendingPopupEvent =\n function(mode, popupRedirectResult, error, opt_eventId) {\n // Only handles popup events of type sign in and which match popup event ID.\n if (mode != fireauth.AuthEvent.Type.SIGN_IN_VIA_POPUP ||\n this.popupEventId_ != opt_eventId) {\n return;\n }\n if (error && this.pendingPopupRejectPromise_) {\n // Reject with error for supplied mode.\n this.pendingPopupRejectPromise_(error);\n } else if (popupRedirectResult &&\n !error &&\n this.pendingPopupResolvePromise_) {\n // Resolve with result for supplied mode.\n this.pendingPopupResolvePromise_(popupRedirectResult);\n }\n // Now that event is resolved, delete popup timeout promise.\n if (this.popupTimeoutPromise_) {\n this.popupTimeoutPromise_.cancel();\n this.popupTimeoutPromise_ = null;\n }\n // Delete pending promises.\n delete this.pendingPopupResolvePromise_;\n delete this.pendingPopupRejectPromise_;\n};\n\n\n/**\n * Returns the handler's appropriate popup and redirect sign in operation\n * finisher.\n * @param {!fireauth.AuthEvent.Type} mode The Auth type mode.\n * @param {?string=} opt_eventId The optional event ID.\n * @return {?function(string, string, ?string,\n * ?string=):!goog.Promise<!fireauth.AuthEventManager.Result>}\n * @override\n */\nfireauth.Auth.prototype.getAuthEventHandlerFinisher =\n function(mode, opt_eventId) {\n // Sign in events will be completed by finishPopupAndRedirectSignIn.\n if (mode == fireauth.AuthEvent.Type.SIGN_IN_VIA_REDIRECT) {\n return goog.bind(this.finishPopupAndRedirectSignIn, this);\n } else if (mode == fireauth.AuthEvent.Type.SIGN_IN_VIA_POPUP &&\n this.popupEventId_ == opt_eventId &&\n this.pendingPopupResolvePromise_) {\n return goog.bind(this.finishPopupAndRedirectSignIn, this);\n }\n return null;\n};\n\n\n/**\n * Finishes the popup and redirect sign in operations.\n * @param {string} requestUri The callback url with the oauth response.\n * @param {string} sessionId The session id used to generate the authUri.\n * @param {?string} tenantId The tenant ID.\n * @param {?string=} opt_postBody The optional POST body content.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.finishPopupAndRedirectSignIn =\n function(requestUri, sessionId, tenantId, opt_postBody) {\n var self = this;\n // Verify assertion request.\n var request = {\n 'requestUri': requestUri,\n 'postBody': opt_postBody,\n 'sessionId': sessionId,\n // Even if tenant ID is null, still pass it to RPC handler explicitly so\n // that it won't be overridden by RPC handler's tenant ID.\n 'tenantId': tenantId\n };\n // Now that popup has responded, delete popup timeout promise.\n if (this.popupTimeoutPromise_) {\n this.popupTimeoutPromise_.cancel();\n this.popupTimeoutPromise_ = null;\n }\n // When state is ready, run verify assertion request.\n // This will only run either after initial and redirect state is ready for\n // popups or after initial state is ready for redirect resolution.\n return self.authStateLoaded_.then(function() {\n return self.signInWithIdTokenProvider_(\n self.rpcHandler_.verifyAssertion(request));\n });\n};\n\n\n/**\n * @return {string} The generated event ID used to identify a popup event.\n * @private\n */\nfireauth.Auth.prototype.generateEventId_ = function() {\n return fireauth.util.generateEventId();\n};\n\n\n/**\n * Signs in to Auth provider via popup.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.signInWithPopup = function(provider) {\n // Check if popup and redirect are supported in this environment.\n if (!fireauth.util.isPopupRedirectSupported()) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n }\n var mode = fireauth.AuthEvent.Type.SIGN_IN_VIA_POPUP;\n var self = this;\n // Popup the window immediately to make sure the browser associates the\n // popup with the click that triggered it.\n\n // Get provider settings.\n var settings = fireauth.idp.getIdpSettings(provider['providerId']);\n // There could multiple sign in with popup events in different windows.\n // We need to match the correct popup to the correct pending promise.\n var eventId = this.generateEventId_();\n // If incapable of redirecting popup from opener, popup destination URL\n // directly. This could also happen in a sandboxed iframe.\n var oauthHelperWidgetUrl = null;\n if ((!fireauth.util.runsInBackground() || fireauth.util.isIframe()) &&\n this.app_().options['authDomain'] &&\n provider['isOAuthProvider']) {\n oauthHelperWidgetUrl =\n fireauth.iframeclient.IfcHandler.getOAuthHelperWidgetUrl(\n this.app_().options['authDomain'],\n this.app_().options['apiKey'],\n this.app_().name,\n mode,\n provider,\n null,\n eventId,\n firebase.SDK_VERSION || null,\n null,\n null,\n this.getTenantId());\n }\n // The popup must have a name, otherwise when successive popups are triggered\n // they will all render in the same instance and none will succeed since the\n // popup cancel of first window will close the shared popup window instance.\n var popupWin =\n fireauth.util.popup(\n oauthHelperWidgetUrl,\n fireauth.util.generateRandomString(),\n settings && settings.popupWidth,\n settings && settings.popupHeight);\n // Auth event manager must be available for popup sign in to be possible.\n var p = this.getAuthEventManager_().then(function(manager) {\n // Process popup request tagging it with newly created event ID.\n return manager.processPopup(\n popupWin, mode, provider, eventId, !!oauthHelperWidgetUrl,\n self.getTenantId());\n }).then(function() {\n return new goog.Promise(function(resolve, reject) {\n // Expire other pending promises if still available..\n self.resolvePendingPopupEvent(\n mode,\n null,\n new fireauth.AuthError(fireauth.authenum.Error.EXPIRED_POPUP_REQUEST),\n // Existing pending popup event ID.\n self.popupEventId_);\n // Save current pending promises.\n self.pendingPopupResolvePromise_ = resolve;\n self.pendingPopupRejectPromise_ = reject;\n // Overwrite popup event ID with new one corresponding to popup.\n self.popupEventId_ = eventId;\n // Keep track of timeout promise to cancel it on promise resolution before\n // it times out.\n self.popupTimeoutPromise_ =\n self.authEventManager_.startPopupTimeout(\n self, mode, /** @type {!Window} */ (popupWin), eventId);\n });\n }).then(function(result) {\n // On resolution, close popup if still opened and pass result through.\n if (popupWin) {\n fireauth.util.closeWindow(popupWin);\n }\n if (result) {\n return fireauth.object.makeReadonlyCopy(result);\n }\n return null;\n }).thenCatch(function(error) {\n if (popupWin) {\n fireauth.util.closeWindow(popupWin);\n }\n throw error;\n });\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(p));\n};\n\n\n/**\n * Signs in to Auth provider via redirect.\n * @param {!fireauth.AuthProvider} provider The Auth provider to sign in with.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.signInWithRedirect = function(provider) {\n // Check if popup and redirect are supported in this environment.\n if (!fireauth.util.isPopupRedirectSupported()) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n }\n var self = this;\n var mode = fireauth.AuthEvent.Type.SIGN_IN_VIA_REDIRECT;\n // Auth event manager must be available for sign in via redirect to be\n // possible.\n var p = this.getAuthEventManager_().then(function(manager) {\n // Remember current persistence to apply it on the next page.\n // This is the only time the state is passed to the next page (when user is\n // not already logged in).\n // This is not needed for link and reauthenticate as the user is already\n // stored with specified persistence.\n return self.userStorageManager_.savePersistenceForRedirect();\n }).then(function() {\n // Process redirect operation.\n return self.authEventManager_.processRedirect(\n mode, provider, undefined, self.getTenantId());\n });\n return /** @type {!goog.Promise<void>} */ (this.registerPendingPromise_(p));\n};\n\n\n/**\n * Returns the redirect result. If coming back from a successful redirect sign\n * in, will resolve to the signed in user. If coming back from an unsuccessful\n * redirect sign, will reject with the proper error. If no redirect operation\n * called, resolves with null.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n * @private\n */\nfireauth.Auth.prototype.getRedirectResultWithoutClearing_ = function() {\n // Check if popup and redirect are supported in this environment.\n if (!fireauth.util.isPopupRedirectSupported()) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED));\n }\n var self = this;\n // Auth event manager must be available for get redirect result to be\n // possible.\n var p = this.getAuthEventManager_().then(function(manager) {\n // Return redirect result when resolved.\n return self.authEventManager_.getRedirectResult();\n }).then(function(result) {\n if (result) {\n return fireauth.object.makeReadonlyCopy(result);\n }\n return null;\n });\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(p));\n};\n\n\n/**\n * In addition to returning the redirect result as in\n * `getRedirectResultWithoutClearing_`, this will also clear the cached\n * redirect result for security reasons.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.getRedirectResult = function() {\n return this.getRedirectResultWithoutClearing_()\n .then((result) => {\n if (this.authEventManager_) {\n this.authEventManager_.clearRedirectResult();\n }\n return result;\n })\n .thenCatch((error) => {\n if (this.authEventManager_) {\n this.authEventManager_.clearRedirectResult();\n }\n throw error;\n });\n};\n\n\n/**\n * Asynchronously sets the provided user as currentUser on the current Auth\n * instance.\n * @param {?fireauth.AuthUser} user The user to be copied to Auth instance.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.updateCurrentUser = function(user) {\n if (!user) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.NULL_USER));\n }\n if (this.tenantId_ != user['tenantId']) {\n return goog.Promise.reject(new fireauth.AuthError(\n fireauth.authenum.Error.TENANT_ID_MISMATCH));\n }\n var self = this;\n var options = {};\n options['apiKey'] = this.app_().options['apiKey'];\n options['authDomain'] = this.app_().options['authDomain'];\n options['appName'] = this.app_().name;\n var newUser = fireauth.AuthUser.copyUser(user, options,\n self.redirectUserStorageManager_, self.getFramework());\n return this.registerPendingPromise_(\n this.redirectStateIsReady_.then(function() {\n if (self.app_().options['apiKey'] != user.getApiKey()) {\n // Throws auth/invalid-user-token if user doesn't belong to app.\n // Throws auth/user-token-expired if token expires.\n return newUser.reload();\n }\n }).then(function() {\n if (self.currentUser_() && user['uid'] == self.currentUser_()['uid']) {\n // Same user signed in. Update user data and notify Auth listeners.\n // No need to resubscribe to user events.\n // TODO: Check if the user to copy is older than current user and skip\n // the copy logic in that case.\n self.currentUser_().copy(user);\n return self.handleUserStateChange_(user);\n }\n self.setCurrentUser_(newUser);\n // Enable popup and redirect events.\n newUser.enablePopupRedirect();\n // Save user changes.\n return self.handleUserStateChange_(newUser);\n }).then(function(user) {\n self.notifyAuthListeners_();\n }));\n};\n\n\n/**\n * Completes the headless sign in with the server response containing the STS\n * access and refresh tokens, and sets the Auth user as current user while\n * setting all listeners to it and saving it to storage.\n * @param {!Object<string, string>} idTokenResponse The ID token response from\n * the server.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.signInWithIdTokenResponse =\n function(idTokenResponse) {\n var self = this;\n var options = {};\n options['apiKey'] = self.app_().options['apiKey'];\n options['authDomain'] = self.app_().options['authDomain'];\n options['appName'] = self.app_().name;\n // Wait for state to be ready.\n // This is used internally and is also used for redirect sign in so there is\n // no need for waiting for redirect result to resolve since redirect result\n // depends on it.\n return this.authStateLoaded_.then(function() {\n // Initialize an Auth user using the provided ID token response.\n return fireauth.AuthUser.initializeFromIdTokenResponse(\n options,\n idTokenResponse,\n /** @type {!fireauth.storage.RedirectUserManager} */ (\n self.redirectUserStorageManager_),\n // Pass frameworks so they are logged in getAccountInfo while populating\n // the user info.\n self.getFramework());\n }).then(function(user) {\n // Check if the same user is already signed in.\n if (self.currentUser_() &&\n user['uid'] == self.currentUser_()['uid']) {\n // Same user signed in. Update user data and notify Auth listeners.\n // No need to resubscribe to user events.\n self.currentUser_().copy(user);\n return self.handleUserStateChange_(user);\n }\n // New user.\n // Set current user and attach all listeners to it.\n self.setCurrentUser_(user);\n // Enable popup and redirect events.\n user.enablePopupRedirect();\n // Save user changes.\n return self.handleUserStateChange_(user);\n }).then(function() {\n // Notify external Auth listeners only when state is ready.\n self.notifyAuthListeners_();\n });\n};\n\n\n/**\n * Updates the current auth user and attaches event listeners to changes on it.\n * Also removes all event listeners from previously signed in user.\n * @param {?fireauth.AuthUser} user The current user instance.\n * @private\n */\nfireauth.Auth.prototype.setCurrentUser_ = function(user) {\n // Must be called first before updating currentUser reference.\n this.attachEventListeners_(user);\n // Update currentUser property.\n fireauth.object.setReadonlyProperty(this, 'currentUser', user);\n if (user) {\n // If a user is available, set the language code on it and set current Auth\n // instance as language code change dispatcher.\n this.setUserLanguage_(user);\n // Set the current frameworks used on the user and set current Auth instance\n // as the framework change dispatcher.\n this.setUserFramework_(user);\n }\n};\n\n\n/**\n * Signs out the current user while deleting the Auth user from storage and\n * removing all listeners from it.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.signOut = function() {\n var self = this;\n // Wait for final state to be ready first, otherwise a signed out user could\n // come back to life.\n var p = this.redirectStateIsReady_.then(function() {\n // Clear any cached redirect result on sign out, even if user is already\n // signed out. For example, sign in could fail due to account conflict\n // error, the error in redirect result should still be cleared. There is\n // also the use case where you keep a reference to a signed out user and\n // call signedOutUser.linkWithRedirect(provider). Even though the user is\n // signed out, getRedirectResult() will resolve with the modified signed\n // out user. This could also throw an error\n // (provider already linked, etc).\n if (self.authEventManager_) {\n self.authEventManager_.clearRedirectResult();\n }\n // Ignore if already signed out.\n if (!self.currentUser_()) {\n return goog.Promise.resolve();\n }\n // Detach all event listeners.\n // Set current user to null.\n self.setCurrentUser_(null);\n // Remove current user from storage\n return /** @type {!fireauth.storage.UserManager} */ (\n self.userStorageManager_).removeCurrentUser()\n .then(function() {\n // Notify external Auth listeners of this Auth change event.\n self.notifyAuthListeners_();\n });\n });\n return /** @type {!goog.Promise<void>} */ (this.registerPendingPromise_(p));\n};\n\n\n/**\n * @return {!goog.Promise} A promise that resolved when any stored redirect user\n * is loaded and removed from session storage and then stored locally.\n * @private\n */\nfireauth.Auth.prototype.initRedirectUser_ = function() {\n var self = this;\n var authDomain = this.app_().options['authDomain'];\n // Get any saved redirect user and delete from session storage.\n // Override user's authDomain with app's authDomain if there is a mismatch.\n var p = /** @type {!fireauth.storage.RedirectUserManager} */ (\n this.redirectUserStorageManager_).getRedirectUser(authDomain)\n .then(function(user) {\n // Save redirect user.\n self.redirectUser_ = user;\n if (user) {\n // Set redirect storage manager on user.\n user.setRedirectStorageManager(\n /** @type {!fireauth.storage.RedirectUserManager} */ (\n self.redirectUserStorageManager_));\n }\n // Delete redirect user.\n return /** @type {!fireauth.storage.RedirectUserManager} */ (\n self.redirectUserStorageManager_).removeRedirectUser();\n });\n return /** @type {!goog.Promise<undefined>} */ (\n this.registerPendingPromise_(p));\n};\n\n\n/**\n * Loads the initial Auth state for current application from web storage and\n * initializes Auth user accordingly to reflect that state. This routine does\n * not wait for any pending redirect result to be resolved.\n * @return {!goog.Promise<undefined>} Promise that resolves when state is ready,\n * loaded from storage.\n * @private\n */\nfireauth.Auth.prototype.initAuthState_ = function() {\n // Load current user from storage.\n var self = this;\n var authDomain = this.app_().options['authDomain'];\n // Get any saved redirected user first.\n var p = this.initRedirectUser_().then(function() {\n // Override user's authDomain with app's authDomain if there is a mismatch.\n return /** @type {!fireauth.storage.UserManager} */ (\n self.userStorageManager_).getCurrentUser(authDomain);\n }).then(function(user) {\n // Logged in user.\n if (user) {\n // Set redirect storage manager on user.\n user.setRedirectStorageManager(\n /** @type {!fireauth.storage.RedirectUserManager} */ (\n self.redirectUserStorageManager_));\n // If the current user is undergoing a redirect operation, do not reload\n // as that could could potentially delete the user if the token is\n // expired. Instead any token problems will be detected via the\n // verifyAssertion flow or the remaining flow. This is critical for\n // reauthenticateWithRedirect as this flow is potentially used to recover\n // from a token expiration error.\n if (self.redirectUser_ &&\n self.redirectUser_.getRedirectEventId() ==\n user.getRedirectEventId()) {\n return user;\n }\n // Confirm user valid first before setting listeners.\n return user.reload().then(function() {\n // Force user saving after reload as state change listeners not\n // subscribed yet below via setCurrentUser_. Changes may have happened\n // externally such as email actions or changes on another device.\n return self.userStorageManager_.setCurrentUser(user).then(function() {\n return user;\n });\n }).thenCatch(function(error) {\n if (error['code'] == 'auth/network-request-failed') {\n // Do not delete the user from storage if connection is lost or app is\n // offline.\n return user;\n }\n // Invalid user, could be deleted, remove from storage and resolve with\n // null.\n return /** @type {!fireauth.storage.UserManager} */(\n self.userStorageManager_).removeCurrentUser();\n });\n }\n // No logged in user, resolve with null;\n return null;\n }).then(function(user) {\n // Even though state not ready yet pending any redirect result.\n // Current user needs to be available for link with redirect to complete.\n // This will also set listener on the user changes in case state changes\n // occur they would get updated in storage too.\n self.setCurrentUser_(user || null);\n });\n // In case the app is deleted before it is initialized with state from\n // storage.\n return /** @type {!goog.Promise<undefined>} */ (\n this.registerPendingPromise_(p));\n};\n\n\n/**\n * After initial Auth state is loaded, waits for any pending redirect result,\n * resolves it and then adds the external Auth state change listeners and\n * triggers first state of all observers.\n * @return {!goog.Promise<undefined>} Promise that resolves when state is ready\n * taking into account any pending redirect result.\n * @private\n */\nfireauth.Auth.prototype.initAuthRedirectState_ = function() {\n var self = this;\n // Wait first for state to be loaded from storage.\n return this.authStateLoaded_.then(function() {\n // Resolve any pending redirect result.\n return self.getRedirectResultWithoutClearing_();\n }).thenCatch(function(error) {\n // Ignore any error in the process. Redirect could be not supported.\n return;\n }).then(function() {\n // Make sure instance was not deleted before proceeding.\n if (self.deleted_) {\n return;\n }\n // Between init Auth state and get redirect result resolution there\n // could have been a sign in attempt in another window.\n // Force sync and then add listener to run sync on change below.\n return self.getSyncAuthUserChanges_();\n }).thenCatch(function(error) {\n // Ignore any error in the process.\n return;\n }).then(function() {\n // Now that final state is ready, make sure instance was not deleted before\n // proceeding.\n if (self.deleted_) {\n return;\n }\n // Initial state has been resolved.\n self.isStateResolved_ = true;\n // Add user state change listener so changes are synchronized with\n // other windows and tabs.\n /** @type {!fireauth.storage.UserManager} */ (self.userStorageManager_\n ).addCurrentUserChangeListener(self.getSyncAuthUserChanges_);\n });\n};\n\n\n/**\n * Synchronizes current Auth to stored auth state, used when external state\n * changes occur.\n * @return {!goog.Promise<void>}\n * @private\n */\nfireauth.Auth.prototype.syncAuthUserChanges_ = function() {\n // Get Auth user state from storage and compare to current state.\n // Safe to run when no external change is detected.\n var self = this;\n var authDomain = this.app_().options['authDomain'];\n // Override user's authDomain with app's authDomain if there is a mismatch.\n return /** @type {!fireauth.storage.UserManager} */ (\n this.userStorageManager_).getCurrentUser(authDomain)\n .then(function(user) {\n // In case this was deleted.\n if (self.deleted_) {\n return;\n }\n // Since the authDomain could be modified here, saving to storage here\n // could trigger an infinite loop of changes between this tab and\n // another tab using different Auth domain but since sync Auth user\n // changes does not save changes to storage, except for getToken below\n // if the token needs refreshing but will stop triggering the first time\n // the token is refreshed on one of the first tab that refreshes it.\n // The latter should not happen anyway since getToken should be valid\n // at all times since anything that triggers the storage change should\n // have communicated with the backend and that requires a valid token.\n // In addition, authDomain difference is an edge case to begin with.\n\n // If the same user is to be synchronized.\n if (self.currentUser_() &&\n user &&\n self.currentUser_().hasSameUserIdAs(user)) {\n // Data update, simply copy data changes.\n self.currentUser_().copy(user);\n // If tokens changed from previous user tokens, this will trigger\n // notifyAuthListeners_.\n return self.currentUser_().getIdToken();\n } else if (!self.currentUser_() && !user) {\n // No change, do nothing (was signed out and remained signed out).\n return;\n } else {\n // Update current Auth state. Either a new login or logout.\n self.setCurrentUser_(user);\n // If a new user is signed in, enabled popup and redirect on that\n // user.\n if (user) {\n user.enablePopupRedirect();\n // Set redirect storage manager on user.\n user.setRedirectStorageManager(\n /** @type {!fireauth.storage.RedirectUserManager} */ (\n self.redirectUserStorageManager_));\n }\n if (self.authEventManager_) {\n self.authEventManager_.subscribe(self);\n }\n // Notify external Auth changes of Auth change event.\n self.notifyAuthListeners_();\n }\n });\n};\n\n\n/**\n * Updates the language code on the provided user and configures the user to\n * listen to the Auth instance for any language code changes.\n * @param {!fireauth.AuthUser} user The user to whose language needs to be set.\n * @private\n */\nfireauth.Auth.prototype.setUserLanguage_ = function(user) {\n // Sets the current language code on the user.\n user.setLanguageCode(this.getLanguageCode());\n // Sets current Auth instance as language code change dispatcher on the user.\n user.setLanguageCodeChangeDispatcher(this);\n};\n\n\n/**\n * Handles user state changes.\n * @param {!fireauth.AuthUser} user The user which triggered the state changes.\n * @return {!goog.Promise} The promise that resolves when state changes are\n * handled.\n * @private\n */\nfireauth.Auth.prototype.handleUserStateChange_ = function(user) {\n // Save Auth user state changes.\n return /** @type {!fireauth.storage.UserManager} */ (\n this.userStorageManager_).setCurrentUser(user);\n};\n\n\n/**\n * Handles user token changes.\n * @param {!Object} event The token change event.\n * @private\n */\nfireauth.Auth.prototype.handleUserTokenChange_ = function(event) {\n // This is only called when user is ready and Auth state has been resolved.\n // Notify external Auth change listeners.\n this.notifyAuthListeners_();\n // Save user token changes.\n this.handleUserStateChange_(/** @type {!fireauth.AuthUser} */ (\n this.currentUser_()));\n};\n\n\n/**\n * Handles user deletion events.\n * @param {!Object} event The user delete event.\n * @private\n */\nfireauth.Auth.prototype.handleUserDelete_ = function(event) {\n // A deleted user will be treated like a sign out event.\n this.signOut();\n};\n\n\n/**\n * Handles user invalidation events.\n * @param {!Object} event The user invalidation event.\n * @private\n */\nfireauth.Auth.prototype.handleUserInvalidated_ = function(event) {\n // An invalidated user will be treated like a sign out event.\n this.signOut();\n};\n\n\n/**\n * Detaches all previous listeners on current user and reattach new listeners to\n * provided user if not null.\n * @param {?fireauth.AuthUser} user The user to attach event listeners to.\n * @private\n */\nfireauth.Auth.prototype.attachEventListeners_ = function(user) {\n // Remove existing event listeners from previous current user if available.\n if (this.currentUser_()) {\n this.currentUser_().removeStateChangeListener(\n this.userStateChangeListener_);\n goog.events.unlisten(\n this.currentUser_(),\n fireauth.UserEventType.TOKEN_CHANGED,\n this.userTokenChangeListener_);\n goog.events.unlisten(\n this.currentUser_(),\n fireauth.UserEventType.USER_DELETED,\n this.userDeleteListener_);\n goog.events.unlisten(\n this.currentUser_(),\n fireauth.UserEventType.USER_INVALIDATED,\n this.userInvalidatedListener_);\n // Stop proactive token refresh on the current user.\n this.currentUser_().stopProactiveRefresh();\n }\n // If a new user is provided, attach event listeners to state, token, user\n // invalidation and delete events.\n if (user) {\n user.addStateChangeListener(this.userStateChangeListener_);\n goog.events.listen(\n user,\n fireauth.UserEventType.TOKEN_CHANGED,\n this.userTokenChangeListener_);\n goog.events.listen(\n user,\n fireauth.UserEventType.USER_DELETED,\n this.userDeleteListener_);\n goog.events.listen(\n user,\n fireauth.UserEventType.USER_INVALIDATED,\n this.userInvalidatedListener_);\n // Start proactive token refresh on new user if there is at least one\n // Firebase service subscribed to Auth changes.\n if (this.firebaseServices_ > 0) {\n user.startProactiveRefresh();\n }\n }\n};\n\n\n/**\n * Signs in with ID token promise provider.\n * @param {!goog.Promise<!Object>} idTokenPromise\n * The rpc handler method that returns a promise which resolves with an ID\n * token.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n * @private\n */\nfireauth.Auth.prototype.signInWithIdTokenProvider_ = function(idTokenPromise) {\n var self = this;\n var credential = null;\n var additionalUserInfo = null;\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(\n idTokenPromise\n .then(function(idTokenResponse) {\n // Get credential if available in the response.\n credential = fireauth.AuthProvider.getCredentialFromResponse(\n idTokenResponse);\n // Get additional IdP data if available in the response.\n additionalUserInfo = fireauth.AdditionalUserInfo.fromPlainObject(\n idTokenResponse);\n // When custom token is exchanged for idToken, continue sign in with\n // ID token and return firebase Auth user.\n return self.signInWithIdTokenResponse(idTokenResponse);\n }, function(error) {\n // Catch the MFA_REQUIRED error rejected in ID token promise and\n // repackage it into a multi-factor error with additional IdP data\n // if available.\n var multiFactorError = null;\n if (error && error['code'] === 'auth/multi-factor-auth-required') {\n multiFactorError = fireauth.MultiFactorError.fromPlainObject(\n error.toPlainObject(),\n self,\n goog.bind(self.handleMultiFactorIdTokenResolver_, self));\n }\n throw multiFactorError || error;\n })\n .then(function() {\n // Resolve promise with a readonly user credential object.\n return fireauth.object.makeReadonlyCopy({\n // Return the current user reference.\n 'user': self.currentUser_(),\n // Return any credential passed from the backend.\n 'credential': credential,\n // Return any additional IdP data passed from the backend.\n 'additionalUserInfo': additionalUserInfo,\n // Sign in operation type.\n 'operationType': fireauth.constants.OperationType.SIGN_IN\n });\n })));\n};\n\n\n/**\n * Completes multi-factor sign-in with ID token response and additional IdP data\n * if available.\n * @param {{idToken: string, refreshToken: string}} response The successful\n * sign-in response containing the new ID tokens.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>} A Promise that\n * resolves with the updated `UserCredential`.\n * @private\n */\nfireauth.Auth.prototype.handleMultiFactorIdTokenResolver_ =\n function(response) {\n var self = this;\n // Wait for state to be ready and then finish sign-in.\n return this.redirectStateIsReady_.then(function() {\n return self.signInWithIdTokenProvider_(goog.Promise.resolve(response));\n });\n};\n\n\n/**\n * Initializes the Auth state change observer returned by the\n * firebase.INTERNAL.createSubscribe helper.\n * @param {!firebase.Observer} observer The Auth state change observer.\n * @private\n */\nfireauth.Auth.prototype.initIdTokenChangeObserver_ = function(observer) {\n var self = this;\n // Adds a listener that will transmit the event everytime it's called.\n this.addAuthTokenListener(function(accessToken) {\n observer.next(self.currentUser_());\n });\n};\n\n\n/**\n * Initializes the user state change observer returned by the\n * firebase.INTERNAL.createSubscribe helper.\n * @param {!firebase.Observer} observer The user state change observer.\n * @private\n */\nfireauth.Auth.prototype.initUserStateObserver_ = function(observer) {\n var self = this;\n // Adds a listener that will transmit the event everytime it's called.\n this.addUserChangeListener_(function(accessToken) {\n observer.next(self.currentUser_());\n });\n};\n\n\n/**\n * Adds an observer for Auth state changes, we need to wrap the call as\n * the args checking code needs a method defined on the prototype this way,\n * not within the constructor, and we also have to implement the behavior\n * that will trigger an observer right away if state is ready.\n * @param {!firebase.Observer|function(?fireauth.AuthUser)}\n * nextOrObserver An observer object or a function triggered on change.\n * @param {function(!fireauth.AuthError)=} opt_error Optional A function\n * triggered on Auth error.\n * @param {function()=} opt_completed Optional A function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\nfireauth.Auth.prototype.onIdTokenChanged = function(\n nextOrObserver, opt_error, opt_completed) {\n var self = this;\n // State already determined. Trigger immediately, otherwise initState will\n // take care of notifying all pending listeners on initialization.\n // In this case we do not trigger synchronously and trigger via a resolved\n // promise as required by specs.\n if (this.isStateResolved_) {\n // The observer cannot be called synchronously. We're using the\n // native Promise implementation as otherwise it creates weird behavior\n // where the order of promises resolution would not be as expected.\n // It is due to the fact fireauth and firebase.app use their own\n // and different promises library and this leads to calls resolutions order\n // being different from the promises registration order.\n Promise.resolve().then(function() {\n if (goog.isFunction(nextOrObserver)) {\n nextOrObserver(self.currentUser_());\n } else if (goog.isFunction(nextOrObserver['next'])) {\n nextOrObserver['next'](self.currentUser_());\n }\n });\n }\n return this.onIdTokenChanged_(\n /** @type {!firebase.Observer|function(*)|undefined} */ (nextOrObserver),\n /** @type {function(!Error)|undefined} */ (opt_error),\n opt_completed);\n};\n\n\n/**\n * Adds an observer for user state changes, we need to wrap the call as\n * the args checking code needs a method defined on the prototype this way,\n * not within the constructor, and we also have to implement the behavior\n * that will trigger an observer right away if state is ready.\n * @param {!firebase.Observer|function(?fireauth.AuthUser)}\n * nextOrObserver An observer object or a function triggered on change.\n * @param {function(!fireauth.AuthError)=} opt_error Optional A function\n * triggered on Auth error.\n * @param {function()=} opt_completed Optional A function triggered when the\n * observer is removed.\n * @return {!function()} The unsubscribe function for the observer.\n */\nfireauth.Auth.prototype.onAuthStateChanged = function(\n nextOrObserver, opt_error, opt_completed) {\n var self = this;\n // State already determined. Trigger immediately, otherwise initState will\n // take care of notifying all pending listeners on initialization.\n // In this case we do not trigger synchronously and trigger via a resolved\n // promise as required by specs.\n if (this.isStateResolved_) {\n // The observer cannot be called synchronously. We're using the\n // native Promise implementation as otherwise it creates weird behavior\n // where the order of promises resolution would not be as expected.\n // It is due to the fact fireauth and firebase.app use their own\n // and different promises library and this leads to calls resolutions order\n // being different from the promises registration order.\n Promise.resolve().then(function() {\n // This ensures that the first time notifyAuthListeners_ is triggered,\n // it has the correct UID before triggering the user state change\n // listeners.\n self.userStateChangeUid_ = self.getUid();\n if (goog.isFunction(nextOrObserver)) {\n nextOrObserver(self.currentUser_());\n } else if (goog.isFunction(nextOrObserver['next'])) {\n nextOrObserver['next'](self.currentUser_());\n }\n });\n }\n return this.onUserStateChanged_(\n /** @type {!firebase.Observer|function(*)|undefined} */ (nextOrObserver),\n /** @type {function(!Error)|undefined} */ (opt_error),\n opt_completed);\n};\n\n\n/**\n * Returns an STS token. If the cached one is unexpired it is directly returned.\n * Otherwise the existing ID token or refresh token is exchanged for a new one.\n * If there is no user signed in, returns null.\n *\n * This method is called getIdTokenInternal as the symbol getIdToken is not\n * obfuscated, which could lead to developers incorrectly calling\n * firebase.auth().getIdToken().\n *\n * @param {boolean=} opt_forceRefresh Whether to force refresh token exchange.\n * @return {!goog.Promise<?Object>}\n */\nfireauth.Auth.prototype.getIdTokenInternal = function(opt_forceRefresh) {\n var self = this;\n // Wait for state to be ready.\n var p = this.redirectStateIsReady_.then(function() {\n // Call user's underlying getIdToken method.\n if (self.currentUser_()) {\n return self.currentUser_().getIdToken(opt_forceRefresh)\n .then(function(stsAccessToken) {\n // This is used internally by other services which expect the access\n // token to be returned in an object.\n return {\n 'accessToken': stsAccessToken\n };\n });\n }\n // No logged in user, return null token.\n return null;\n });\n return /** @type {!goog.Promise<?Object>} */ (\n this.registerPendingPromise_(p));\n};\n\n\n/**\n * Signs in a user asynchronously using a custom token and returns any\n * additional user info data or credentials returned form the backend.\n * @param {string} token The custom token to sign in with.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.signInWithCustomToken = function(token) {\n var self = this;\n // Wait for the redirect state to be determined before proceeding. If critical\n // errors like web storage unsupported are detected, fail before RPC, instead\n // of after.\n return this.redirectStateIsReady_.then(function() {\n return self.signInWithIdTokenProvider_(\n self.getRpcHandler().verifyCustomToken(token));\n }).then(function(result) {\n var user = result['user'];\n // Manually sets the isAnonymous flag to false as the GetAccountInfo\n // response will look like an anonymous user (no credentials visible).\n user.updateProperty('isAnonymous', false);\n // Save isAnonymous flag changes to current user in storage.\n self.handleUserStateChange_(user);\n return result;\n });\n};\n\n\n/**\n * Sign in using an email and password and returns any additional user info\n * data or credentials returned form the backend.\n * @param {string} email The email to sign in with.\n * @param {string} password The password to sign in with.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.signInWithEmailAndPassword =\n function(email, password) {\n var self = this;\n // Wait for the redirect state to be determined before proceeding. If critical\n // errors like web storage unsupported are detected, fail before RPC, instead\n // of after.\n return this.redirectStateIsReady_.then(function() {\n return self.signInWithIdTokenProvider_(\n self.getRpcHandler().verifyPassword(email, password));\n });\n};\n\n\n/**\n * Creates a new email and password account and returns any additional user\n * info data or credentials returned form the backend.\n * @param {string} email The email to sign up with.\n * @param {string} password The password to sign up with.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.createUserWithEmailAndPassword =\n function(email, password) {\n var self = this;\n // Wait for the redirect state to be determined before proceeding. If critical\n // errors like web storage unsupported are detected, fail before RPC, instead\n // of after.\n return this.redirectStateIsReady_.then(function() {\n return self.signInWithIdTokenProvider_(\n self.getRpcHandler().createAccount(email, password));\n });\n};\n\n\n/**\n * Logs into Firebase with the given 3rd party credentials and returns any\n * additional user info data or credentials returned form the backend.\n * @param {!fireauth.AuthCredential} credential The Auth credential.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.signInWithCredential = function(credential) {\n // Credential could be extended in the future, so leave it to credential to\n // decide how to retrieve ID token.\n var self = this;\n // Wait for the redirect state to be determined before proceeding. If critical\n // errors like web storage unsupported are detected, fail before RPC, instead\n // of after.\n return this.redirectStateIsReady_.then(function() {\n // Return the full response object and not just the user.\n return self.signInWithIdTokenProvider_(\n credential.getIdTokenProvider(self.getRpcHandler()));\n });\n};\n\n\n/**\n * Logs into Firebase with the given 3rd party credentials and returns any\n * additional user info data or credentials returned form the backend. It has\n * been deprecated in favor of signInWithCredential.\n * @param {!fireauth.AuthCredential} credential The Auth credential.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.signInAndRetrieveDataWithCredential =\n function(credential) {\n fireauth.deprecation.log(\n fireauth.deprecation.Deprecations.SIGN_IN_WITH_CREDENTIAL);\n return this.signInWithCredential(credential);\n};\n\n\n/**\n * Signs in a user anonymously and returns any additional user info data or\n * credentials returned form the backend.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.signInAnonymously = function() {\n var self = this;\n // Wait for the redirect state to be determined before proceeding. If critical\n // errors like web storage unsupported are detected, fail before RPC, instead\n // of after.\n return this.redirectStateIsReady_.then(function() {\n var user = self.currentUser_();\n // If an anonymous user is already signed in, no need to sign him again.\n if (user && user['isAnonymous']) {\n var additionalUserInfo = fireauth.object.makeReadonlyCopy({\n 'providerId': null,\n 'isNewUser': false\n });\n return fireauth.object.makeReadonlyCopy({\n // Return the signed in user reference.\n 'user': user,\n // Do not return credential for anonymous user.\n 'credential': null,\n // Return any additional IdP data.\n 'additionalUserInfo': additionalUserInfo,\n // Sign in operation type.\n 'operationType': fireauth.constants.OperationType.SIGN_IN\n });\n } else {\n // No anonymous user currently signed in.\n return self.signInWithIdTokenProvider_(\n self.getRpcHandler().signInAnonymously())\n .then(function(result) {\n var user = result['user'];\n // Manually sets the isAnonymous flag to true as\n // initializeFromIdTokenResponse uses the default value of false and\n // even though getAccountInfo sets that to true, it will be reverted\n // to false in reloadWithoutSaving.\n // TODO: consider optimizing this and cleaning these manual\n // overwrites.\n user.updateProperty('isAnonymous', true);\n // Save isAnonymous flag changes to current user in storage.\n self.handleUserStateChange_(user);\n return result;\n });\n }\n });\n};\n\n\n/**\n * @return {string} The key used for storing Auth state.\n */\nfireauth.Auth.prototype.getStorageKey = function() {\n return fireauth.util.createStorageKey(\n this.app_().options['apiKey'],\n this.app_().name);\n};\n\n\n/**\n * @return {!firebase.app.App} The Firebase App this auth object is connected\n * to.\n * @private\n */\nfireauth.Auth.prototype.app_ = function() {\n return this['app'];\n};\n\n\n/**\n * @return {!fireauth.RpcHandler} The RPC handler.\n */\nfireauth.Auth.prototype.getRpcHandler = function() {\n return this.rpcHandler_;\n};\n\n\n/**\n * @return {?fireauth.AuthUser} The currently logged in user.\n * @private\n */\nfireauth.Auth.prototype.currentUser_ = function() {\n return this['currentUser'];\n};\n\n\n/** @return {?string} The current user UID if available, null if not. */\nfireauth.Auth.prototype.getUid = function() {\n return (this.currentUser_() && this.currentUser_()['uid']) || null;\n};\n\n\n/**\n * @return {?string} The last cached access token.\n * @private\n */\nfireauth.Auth.prototype.getLastAccessToken_ = function() {\n return (this.currentUser_() && this.currentUser_()['_lat']) || null;\n};\n\n\n\n/**\n * Called internally on Auth state change to notify listeners.\n * @private\n */\nfireauth.Auth.prototype.notifyAuthListeners_ = function() {\n // Only run when state is resolved. After state is resolved, the Auth listener\n // will always trigger.\n if (this.isStateResolved_) {\n for (var i = 0; i < this.authListeners_.length; i++) {\n if (this.authListeners_[i]) {\n this.authListeners_[i](this.getLastAccessToken_());\n }\n }\n // Trigger user change only if UID changed.\n if (this.userStateChangeUid_ !== this.getUid() &&\n this.userChangeListeners_.length) {\n // Update user state change UID.\n this.userStateChangeUid_ = this.getUid();\n // Trigger all subscribed user state change listeners.\n for (var i = 0; i < this.userChangeListeners_.length; i++) {\n if (this.userChangeListeners_[i]) {\n this.userChangeListeners_[i](this.getLastAccessToken_());\n }\n }\n }\n }\n};\n\n\n/**\n * Attaches a listener function to Auth state change.\n * This is used only by internal Firebase services.\n * @param {!function(?string)} listener The auth state change listener.\n */\nfireauth.Auth.prototype.addAuthTokenListenerInternal = function(listener) {\n this.addAuthTokenListener(listener);\n // This is not exact science but should be good enough to detect Firebase\n // services subscribing to Auth token changes.\n // This is needed to start proactive token refresh on a user.\n this.firebaseServices_++;\n if (this.firebaseServices_ > 0 && this.currentUser_()) {\n // Start proactive token refresh on the current user.\n this.currentUser_().startProactiveRefresh();\n }\n};\n\n\n/**\n * Detaches the provided listener from Auth state change event.\n * This is used only by internal Firebase services.\n * @param {!function(?string)} listener The Auth state change listener.\n */\nfireauth.Auth.prototype.removeAuthTokenListenerInternal = function(listener) {\n // This is unlikely to be called by Firebase services. Services are unlikely\n // to remove Auth token listeners.\n // Make sure listener is still subscribed before decrementing.\n var self = this;\n goog.array.forEach(this.authListeners_, function(ele) {\n // This covers the case where the same listener is subscribed more than\n // once.\n if (ele == listener) {\n self.firebaseServices_--;\n }\n });\n if (this.firebaseServices_ < 0) {\n this.firebaseServices_ = 0;\n }\n if (this.firebaseServices_ == 0 && this.currentUser_()) {\n // Stop proactive token refresh on the current user.\n this.currentUser_().stopProactiveRefresh();\n }\n this.removeAuthTokenListener(listener);\n};\n\n\n/**\n * Attaches a listener function to Auth state change.\n * @param {!function(?string)} listener The Auth state change listener.\n */\nfireauth.Auth.prototype.addAuthTokenListener = function(listener) {\n var self = this;\n // Save listener.\n this.authListeners_.push(listener);\n // Make sure redirect state is ready and then trigger listener.\n this.registerPendingPromise_(this.redirectStateIsReady_.then(function() {\n // Do nothing if deleted.\n if (self.deleted_) {\n return;\n }\n // Make sure listener is still subscribed.\n if (goog.array.contains(self.authListeners_, listener)) {\n // Trigger the first call for this now that redirect state is resolved.\n listener(self.getLastAccessToken_());\n }\n }));\n};\n\n\n/**\n * Detaches the provided listener from Auth state change event.\n * @param {!function(?string)} listener The Auth state change listener.\n */\nfireauth.Auth.prototype.removeAuthTokenListener = function(listener) {\n // Remove from Auth listeners.\n goog.array.removeAllIf(this.authListeners_, function(ele) {\n return ele == listener;\n });\n};\n\n\n/**\n * Attaches a listener function to user state change.\n * @param {!function(?string)} listener The user state change listener.\n * @private\n */\nfireauth.Auth.prototype.addUserChangeListener_ = function(listener) {\n var self = this;\n // Save listener.\n this.userChangeListeners_.push(listener);\n // Make sure redirect state is ready and then trigger listener.\n this.registerPendingPromise_(this.redirectStateIsReady_.then(function() {\n // Do nothing if deleted.\n if (self.deleted_) {\n return;\n }\n // Make sure listener is still subscribed.\n if (goog.array.contains(self.userChangeListeners_, listener)) {\n // Confirm UID change before triggering.\n if (self.userStateChangeUid_ !== self.getUid()) {\n self.userStateChangeUid_ = self.getUid();\n // Trigger the first call for this now that redirect state is resolved.\n listener(self.getLastAccessToken_());\n }\n }\n }));\n};\n\n\n/**\n * Deletes the Auth instance, handling cancellation of all pending async Auth\n * operations.\n * @return {!Promise<void>}\n */\nfireauth.Auth.prototype.delete = function() {\n this.deleted_ = true;\n // Cancel all pending promises.\n for (var i = 0; i < this.pendingPromises_.length; i++) {\n this.pendingPromises_[i].cancel(fireauth.authenum.Error.MODULE_DESTROYED);\n }\n\n // Empty pending promises array.\n this.pendingPromises_ = [];\n // Remove current user change listener.\n if (this.userStorageManager_) {\n this.userStorageManager_.removeCurrentUserChangeListener(\n this.getSyncAuthUserChanges_);\n }\n // Unsubscribe from Auth event handling.\n if (this.authEventManager_) {\n this.authEventManager_.unsubscribe(this);\n this.authEventManager_.clearRedirectResult();\n }\n return Promise.resolve();\n};\n\n\n/** @return {boolean} Whether Auth instance has pending promises. */\nfireauth.Auth.prototype.hasPendingPromises = function() {\n return this.pendingPromises_.length != 0;\n};\n\n\n/**\n * Takes in a pending promise, saves it and adds a clean up callback which\n * forgets the pending promise after it is fulfilled and echoes the promise\n * back.\n * @param {!goog.Promise<*, *>|!goog.Promise<void>} p The pending promise.\n * @return {!goog.Promise<*, *>|!goog.Promise<void>}\n * @private\n */\nfireauth.Auth.prototype.registerPendingPromise_ = function(p) {\n var self = this;\n // Save created promise in pending list.\n this.pendingPromises_.push(p);\n p.thenAlways(function() {\n // When fulfilled, remove from pending list.\n goog.array.remove(self.pendingPromises_, p);\n });\n // Return the promise.\n return p;\n};\n\n\n/**\n * Gets the list of possible sign in methods for the given email address.\n * @param {string} email The email address.\n * @return {!goog.Promise<!Array<string>>}\n */\nfireauth.Auth.prototype.fetchSignInMethodsForEmail = function(email) {\n return /** @type {!goog.Promise<!Array<string>>} */ (\n this.registerPendingPromise_(\n this.getRpcHandler().fetchSignInMethodsForIdentifier(email)));\n};\n\n\n/**\n * @param {string} emailLink The email link.\n * @return {boolean} Whether the link is a sign in with email link.\n */\nfireauth.Auth.prototype.isSignInWithEmailLink = function(emailLink) {\n return !!fireauth.EmailAuthProvider\n .getActionCodeUrlFromSignInEmailLink(emailLink);\n};\n\n\n/**\n * Sends the sign-in with email link for the email account provided.\n * @param {string} email The email account to sign in with.\n * @param {!Object} actionCodeSettings The action code settings object.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.sendSignInLinkToEmail = function(\n email, actionCodeSettings) {\n var self = this;\n return this.registerPendingPromise_(\n // Wrap in promise as ActionCodeSettings constructor could throw a\n // synchronous error if invalid arguments are specified.\n goog.Promise.resolve()\n .then(function() {\n var actionCodeSettingsBuilder =\n new fireauth.ActionCodeSettings(actionCodeSettings);\n if (!actionCodeSettingsBuilder.canHandleCodeInApp()) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n fireauth.ActionCodeSettings.RawField.HANDLE_CODE_IN_APP +\n ' must be true when sending sign in link to email');\n }\n return actionCodeSettingsBuilder.buildRequest();\n }).then(function(additionalRequestData) {\n return self.getRpcHandler().sendSignInLinkToEmail(\n email, additionalRequestData);\n }).then(function(email) {\n // Do not return the email.\n }));\n};\n\n\n/**\n * Verifies an email action code for password reset and returns a promise\n * that resolves with the associated email if verified.\n * @param {string} code The email action code to verify for password reset.\n * @return {!goog.Promise<string>}\n */\nfireauth.Auth.prototype.verifyPasswordResetCode = function(code) {\n return this.checkActionCode(code).then(function(info) {\n return info['data']['email'];\n });\n};\n\n\n/**\n * Requests resetPassword endpoint for password reset, verifies the action code\n * and updates the new password, returns an empty promise.\n * @param {string} code The email action code to confirm for password reset.\n * @param {string} newPassword The new password.\n * @return {!goog.Promise<undefined, !fireauth.AuthError>}\n */\nfireauth.Auth.prototype.confirmPasswordReset = function(code, newPassword) {\n return this.registerPendingPromise_(\n this.getRpcHandler().confirmPasswordReset(code, newPassword)\n .then(function(email) {\n // Do not return the email.\n }));\n};\n\n\n/**\n * Verifies an email action code and returns an empty promise if verified.\n * @param {string} code The email action code to verify for password reset.\n * @return {!goog.Promise<!Object>}\n */\nfireauth.Auth.prototype.checkActionCode = function(code) {\n return this.registerPendingPromise_(\n this.getRpcHandler().checkActionCode(code)\n .then(function(response) {\n return new fireauth.ActionCodeInfo(response);\n }));\n};\n\n\n/**\n * Applies an out-of-band email action code, such as an email verification code.\n * @param {string} code The email action code.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.applyActionCode = function(code) {\n return this.registerPendingPromise_(\n this.getRpcHandler().applyActionCode(code)\n .then(function(email) {\n // Returns nothing.\n }));\n};\n\n\n/**\n * Sends the password reset email for the email account provided.\n * @param {string} email The email account with the password to be reset.\n * @param {?Object=} opt_actionCodeSettings The optional action code settings\n * object.\n * @return {!goog.Promise<void>}\n */\nfireauth.Auth.prototype.sendPasswordResetEmail =\n function(email, opt_actionCodeSettings) {\n var self = this;\n return this.registerPendingPromise_(\n // Wrap in promise as ActionCodeSettings constructor could throw a\n // synchronous error if invalid arguments are specified.\n goog.Promise.resolve().then(function() {\n if (typeof opt_actionCodeSettings !== 'undefined' &&\n // Ignore empty objects.\n !goog.object.isEmpty(opt_actionCodeSettings)) {\n return new fireauth.ActionCodeSettings(\n /** @type {!Object} */ (opt_actionCodeSettings)).buildRequest();\n }\n return {};\n })\n .then(function(additionalRequestData) {\n return self.getRpcHandler().sendPasswordResetEmail(\n email, additionalRequestData);\n }).then(function(email) {\n // Do not return the email.\n }));\n};\n\n\n/**\n * Signs in with a phone number using the app verifier instance and returns a\n * promise that resolves with the confirmation result which on confirmation\n * will resolve with the UserCredential object.\n * @param {string} phoneNumber The phone number to authenticate with.\n * @param {!firebase.auth.ApplicationVerifier} appVerifier The application\n * verifier.\n * @return {!goog.Promise<!fireauth.ConfirmationResult>}\n */\nfireauth.Auth.prototype.signInWithPhoneNumber =\n function(phoneNumber, appVerifier) {\n return /** @type {!goog.Promise<!fireauth.ConfirmationResult>} */ (\n this.registerPendingPromise_(fireauth.ConfirmationResult.initialize(\n this,\n phoneNumber,\n appVerifier,\n // This will wait for redirectStateIsReady to resolve first.\n goog.bind(this.signInWithCredential, this))));\n};\n\n\n/**\n * Signs in a Firebase User with the provided email and the passwordless\n * sign-in email link.\n * @param {string} email The email account to sign in with.\n * @param {?string=} opt_link The optional link which contains the OTP needed\n * to complete the sign in with email link. If not specified, the current\n * URL is used instead.\n * @return {!goog.Promise<!fireauth.AuthEventManager.Result>}\n */\nfireauth.Auth.prototype.signInWithEmailLink = function(email, opt_link) {\n return this.registerPendingPromise_(goog.Promise.resolve().then(() => {\n const link = opt_link || fireauth.util.getCurrentUrl();\n const credential = fireauth.EmailAuthProvider.credentialWithLink(\n email, link);\n // Check if the tenant ID in the email link matches the tenant ID on Auth\n // instance.\n const actionCodeUrl =\n fireauth.EmailAuthProvider.getActionCodeUrlFromSignInEmailLink(link);\n if (!actionCodeUrl) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR, 'Invalid email link!');\n }\n if (actionCodeUrl['tenantId'] !== this.getTenantId()) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.TENANT_ID_MISMATCH);\n }\n return this.signInWithCredential(credential);\n }));\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 grecaptcha interface.\n */\n\ngoog.provide('fireauth.grecaptcha');\n\n\n/**\n * The reCAPTCHA interface for initializing and managing visible v2\n * reCAPTCHAs as well as invisible ones.\n * @interface\n */\nfireauth.grecaptcha = function() {};\n\n\n/**\n * Creates a new instance of the recaptcha client.\n *\n * @param {!Element|string} elementOrId Element or element ID for the\n * placeholder to render the reCAPTCHA client.\n * @param {!Object} params Parameters for the recaptcha client.\n * @return {number} The client ID.\n */\nfireauth.grecaptcha.prototype.render = function(elementOrId, params) {};\n\n\n/**\n * Resets a client with the given ID. If an ID is not provided, resets the\n * default client.\n *\n * @param {number=} id The ID of the recaptcha client.\n * @param {?Object=} params Parameters for the recaptcha client.\n */\nfireauth.grecaptcha.prototype.reset = function(id, params) {};\n\n\n/**\n * Gets the response for the client with the given ID. If an ID is not\n * provided, gets the response for the default client.\n *\n * @param {number=} id The ID of the recaptcha client.\n * @return {?string}\n */\nfireauth.grecaptcha.prototype.getResponse = function(id) {};\n\n\n/**\n * Programmatically triggers the invisible reCAPTCHA.\n *\n * @param {number=} opt_id The ID of the recaptcha client. Defaults to the\n * first widget created if unspecified.\n */\nfireauth.grecaptcha.prototype.execute = function(opt_id) {};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 mock grecaptcha utilities used for development\n * testing.\n */\ngoog.provide('fireauth.GRecaptchaMockFactory');\ngoog.provide('fireauth.RecaptchaMock');\n\ngoog.require('fireauth.grecaptcha');\ngoog.require('fireauth.util');\ngoog.require('goog.dom');\ngoog.require('goog.events');\ngoog.require('goog.events.EventType');\n\n\n/**\n * The mock grecaptcha factory.\n * @constructor\n * @implements {fireauth.grecaptcha}\n */\nfireauth.GRecaptchaMockFactory = function() {\n /**\n * @const @private {!Object<string, !fireauth.RecaptchaMock>} The hash map\n * that stores the widget ID to mock reCAPTCHA instances.\n */\n this.map_ = {};\n /**\n * @private {number} The current widget ID counter, incremented each time\n * a new mock reCAPTCHA is created.\n */\n this.counter_ = fireauth.GRecaptchaMockFactory.START_INSTANCE_ID;\n};\n\n\n/**\n * @const {number} The start ID of the first created mock reCAPTCHA.\n */\nfireauth.GRecaptchaMockFactory.START_INSTANCE_ID = 1000000000000;\n\n\n/** @const {number} The reCAPTCHA expiration time in milliseconds. */\nfireauth.GRecaptchaMockFactory.EXPIRATION_TIME_MS = 60000;\n\n\n/** @const {number} The reCAPTCHA auto solving time in milliseconds. */\nfireauth.GRecaptchaMockFactory.SOLVE_TIME_MS = 500;\n\n\n/**\n * @private {?fireauth.GRecaptchaMockFactory} The singleton instance\n * for grecaptcha mock object.\n */\nfireauth.GRecaptchaMockFactory.instance_ = null;\n\n\n/**\n * @return {!fireauth.GRecaptchaMockFactory} The singleton grecaptcha mock\n * instance.\n */\nfireauth.GRecaptchaMockFactory.getInstance = function() {\n // Check if there is an existing instance. Otherwise, create one and cache it.\n if (!fireauth.GRecaptchaMockFactory.instance_) {\n fireauth.GRecaptchaMockFactory.instance_ =\n new fireauth.GRecaptchaMockFactory();\n }\n return fireauth.GRecaptchaMockFactory.instance_;\n};\n\n\n/**\n * Creates a new instance of the mock reCAPTCHA widget.\n *\n * @param {(!Element|string)} elementOrId Element or element ID for the\n * placeholder to render the reCAPTCHA client.\n * @param {!Object} params Parameters for the reCAPTCHA client.\n * @return {number} The client ID.\n * @override\n */\nfireauth.GRecaptchaMockFactory.prototype.render =\n function(elementOrId, params) {\n this.map_[this.counter_.toString()] =\n new fireauth.RecaptchaMock(elementOrId, params);\n return this.counter_++;\n};\n\n\n/**\n * Resets a reCAPTCHA with the given ID. If an ID is not provided, resets the\n * first instance.\n *\n * @param {number=} opt_id The id of the reCAPTCHA client. Defaults to the first\n * widget created if unspecified.\n * @override\n */\nfireauth.GRecaptchaMockFactory.prototype.reset = function(opt_id) {\n var mock = this.getMock_(opt_id);\n var id = this.getId_(opt_id);\n if (mock && id) {\n mock.delete();\n delete this.map_[/** @type {string} */ (id)];\n }\n};\n\n\n/**\n * Gets the response for the client with the given ID. If an ID is not\n * provided, gets the response for the default client.\n *\n * @param {number=} opt_id The ID of the reCAPTCHA widget. Defaults to the first\n * widget created if unspecified.\n * @return {?string}\n * @override\n */\nfireauth.GRecaptchaMockFactory.prototype.getResponse = function(opt_id) {\n var mock = this.getMock_(opt_id);\n return mock ? mock.getResponse() : null;\n};\n\n\n/**\n * Programmatically triggers the invisible reCAPTCHA.\n *\n * @param {number=} opt_id The ID of the recaptcha client. Defaults to the first\n * widget created if unspecified.\n * @override\n */\nfireauth.GRecaptchaMockFactory.prototype.execute = function(opt_id) {\n var mock = this.getMock_(opt_id);\n if (mock) {\n mock.execute();\n }\n};\n\n\n/**\n * @param {number=} opt_id The optional ID to lookup.\n * @return {?fireauth.RecaptchaMock} The corresponding reCAPTCHA mock if found.\n * @private\n */\nfireauth.GRecaptchaMockFactory.prototype.getMock_ = function(opt_id) {\n var id = this.getId_(opt_id);\n return id ? this.map_[id] || null : null;\n};\n\n\n/**\n * @param {number=} opt_id The optional ID to lookup.\n * @return {?string} The corresponding reCAPTCHA mock ID if found.\n * @private\n */\nfireauth.GRecaptchaMockFactory.prototype.getId_ = function(opt_id) {\n var id = typeof opt_id === 'undefined' ?\n fireauth.GRecaptchaMockFactory.START_INSTANCE_ID : opt_id;\n return id ? id.toString() : null;\n};\n\n\n/**\n * Mock single reCAPTCHA instance.\n * @param {(!Element|string)} elementOrId Element or element ID for the\n * placeholder to render the reCAPTCHA client.\n * @param {!Object} params Parameters for the reCAPTCHA client.\n * @constructor\n */\nfireauth.RecaptchaMock = function(elementOrId, params) {\n /** @private {boolean} Whether the instance was deleted. */\n this.deleted_ = false;\n /** @const @private {!Object} The reCAPTCHA parameters. */\n this.params_ = params;\n /** @private {?string} The simulated response token if available. */\n this.responseToken_ = null;\n /**\n * @private {?number} The timer ID for response callback/expiration callback\n * to trigger.\n */\n this.timerId_ = null;\n /** @const @private {boolean} Whether the reCAPTCHA is visible or not. */\n this.isVisible_ = this.params_['size'] !== 'invisible';\n /**\n * @const @private {?Element} The container or button trigger of the\n * reCAPTCHA.\n */\n this.element_ = goog.dom.getElement(elementOrId);\n var self = this;\n /** @private {function(?)} The on click handler for invisible reCAPTCHAs. */\n this.onClickHandler_ = function(event) {\n self.execute();\n };\n if (this.isVisible_) {\n // For a visible reCAPTCHA, simulate reCAPTCHA continuously solved\n // and then expired.\n this.execute();\n } else {\n // Trigger on button click on when execute is directly called.\n goog.events.listen(\n this.element_,\n goog.events.EventType.CLICK,\n this.onClickHandler_);\n }\n};\n\n\n/** @return {?string} The current reCAPTCHA response. */\nfireauth.RecaptchaMock.prototype.getResponse = function() {\n this.checkIfDeleted_();\n return this.responseToken_;\n};\n\n\n/** Starts the reCAPTCHA mock solving/expiration cycle. */\nfireauth.RecaptchaMock.prototype.execute = function() {\n this.checkIfDeleted_();\n var self = this;\n if (this.timerId_) {\n return;\n }\n // Wait for expected delay before auto-solving.\n this.timerId_ = setTimeout(function() {\n // Generate random string as reCAPTCHA response token.\n self.responseToken_ = fireauth.util.generateRandomAlphaNumericString(50);\n // Trigger developer's callbacks.\n var callback = self.params_['callback'];\n var expirationCallback = self.params_['expired-callback'];\n if (callback) {\n try {\n callback(self.responseToken_);\n } catch (e) {}\n }\n // Wait for token to expire before triggering expiration callback and\n // resetting token response.\n self.timerId_ = setTimeout(function() {\n self.timerId_ = null;\n self.responseToken_ = null;\n if (expirationCallback) {\n try {\n expirationCallback();\n } catch (e) {}\n }\n if (self.isVisible_) {\n self.execute();\n }\n }, fireauth.GRecaptchaMockFactory.EXPIRATION_TIME_MS);\n }, fireauth.GRecaptchaMockFactory.SOLVE_TIME_MS);\n};\n\n\n/** Deletes the current mock instance. */\nfireauth.RecaptchaMock.prototype.delete = function() {\n this.checkIfDeleted_();\n this.deleted_ = true;\n clearTimeout(this.timerId_);\n this.timerId_ = null;\n goog.events.unlisten(\n this.element_,\n goog.events.EventType.CLICK,\n this.onClickHandler_);\n};\n\n\n/**\n * Checks whether the instance was deleted.\n * @private\n */\nfireauth.RecaptchaMock.prototype.checkIfDeleted_ = function() {\n // This error should never be thrown externally.\n // GRecaptchaMockFactory will ensure that a deleted instance is removed.\n if (this.deleted_) {\n throw new Error('reCAPTCHA mock was already deleted!');\n }\n};\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 MultiFactorGenerators used to generate\n * MultiFactorAssertions. This currently covers only PhoneMultiFactorGenerator.\n */\n\ngoog.provide('fireauth.PhoneMultiFactorGenerator');\n\ngoog.require('fireauth.PhoneMultiFactorAssertion');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.object');\n\n\n/**\n * Defines the multi-factor generator for PhoneMultiFactorAssertions.\n * This class acts only as a namespace and defines some static methods and\n * properties.\n * @constructor @struct @final\n */\nfireauth.PhoneMultiFactorGenerator = function() {};\nfireauth.object.setReadonlyProperty(fireauth.PhoneMultiFactorGenerator,\n 'FACTOR_ID', fireauth.constants.SecondFactorType.PHONE);\n\n\n/**\n * Initializes a `PhoneMultiFactorAssertion` given a `PhoneAuthCredential`.\n * @param {!fireauth.PhoneAuthCredential} phoneAuthCredential\n * @return {!fireauth.PhoneMultiFactorAssertion} The `MultiFactorAssertion`\n * corresponding to the provided `PhoneAuthCredential`.\n */\nfireauth.PhoneMultiFactorGenerator.assertion = function(phoneAuthCredential) {\n return new fireauth.PhoneMultiFactorAssertion(phoneAuthCredential);\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 RecaptchaLoader implementation used to mock loading\n * of grecaptcha dependencies.\n */\n\ngoog.provide('fireauth.RecaptchaMockLoader');\n\ngoog.require('fireauth.GRecaptchaMockFactory');\ngoog.require('fireauth.RecaptchaLoader');\ngoog.require('goog.Promise');\n\n\n/**\n * Defines a mock reCAPTCHA loader by implementing the fireauth.RecaptchaLoader\n * interface.\n * @constructor\n * @implements {fireauth.RecaptchaLoader}\n */\nfireauth.RecaptchaMockLoader = function() {};\n\n\n/**\n * Loads the grecaptcha mock library if it is not loaded and returns a promise\n * that resolves on success. If the right conditions are available, will reload\n * the dependencies for a specified language code.\n * @param {?string} hl The reCAPTCHA language code.\n * @return {!goog.Promise<!fireauth.grecaptcha>} A promise that resolves when\n * grecaptcha is loaded.\n * @override\n */\nfireauth.RecaptchaMockLoader.prototype.loadRecaptchaDeps =\n function(hl) {\n return goog.Promise.resolve(\n \t/** @type {!fireauth.grecaptcha} */ (fireauth.GRecaptchaMockFactory.getInstance()));\n};\n\n\n/**\n * Decrements the reCAPTCHA instance counter.\n * @override\n */\nfireauth.RecaptchaMockLoader.prototype.clearSingleRecaptcha =\n function() {};\n\n\n/**\n * @private {?fireauth.RecaptchaMockLoader} The singleton instance\n * for the mock reCAPTCHA dependency loader.\n */\nfireauth.RecaptchaMockLoader.instance_ = null;\n\n\n/**\n * @return {!fireauth.RecaptchaMockLoader} The singleton mock reCAPTCHA\n * dependency loader instance.\n */\nfireauth.RecaptchaMockLoader.getInstance = function() {\n // Check if there is an existing instance. Otherwise create one and cache it.\n if (!fireauth.RecaptchaMockLoader.instance_) {\n fireauth.RecaptchaMockLoader.instance_ =\n new fireauth.RecaptchaMockLoader();\n }\n return fireauth.RecaptchaMockLoader.instance_;\n};\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 RecaptchaLoader implementation used to load all\n * the grecaptcha dependencies.\n */\n\ngoog.provide('fireauth.RecaptchaRealLoader');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.RecaptchaLoader');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.html.TrustedResourceUrl');\ngoog.require('goog.net.jsloader');\ngoog.require('goog.string.Const');\n\n\n/**\n * Utility to help load reCAPTCHA dependencies for specified languages.\n * @constructor\n * @implements {fireauth.RecaptchaLoader}\n */\nfireauth.RecaptchaRealLoader = function() {\n /**\n * @private {number} The reCAPTCHA instance counter. This is used to track the\n * number of reCAPTCHAs rendered on the page. This is needed to allow\n * localization of the reCAPTCHA. Localization is applied by loading the\n * grecaptcha SDK with the hl field provided. However, this will break\n * existing reCAPTCHAs. So we should only support i18n when there are no\n * other widgets rendered on this screen. If the developer is already\n * using reCAPTCHA in another context, we will disable localization so we\n * don't accidentally break existing reCAPTCHA widgets.\n */\n this.counter_ = goog.global['grecaptcha'] ? Infinity : 0;\n /** @private {?string} The current reCAPTCHA language code. */\n this.hl_ = null;\n /** @const @private {string} The reCAPTCHA callback name. */\n this.cbName_ = '__rcb' + Math.floor(Math.random() * 1000000).toString();\n};\n\n\n/** @private @const {!goog.string.Const} The reCAPTCHA javascript source URL. */\nfireauth.RecaptchaRealLoader.RECAPTCHA_SRC_ = goog.string.Const.from(\n 'https://www.google.com/recaptcha/api.js?onload=%{onload}&render=explicit' +\n '&hl=%{hl}');\n\n\n/**\n * The default timeout delay (units in milliseconds) for requests loading\n * the external reCAPTCHA dependencies.\n * @const {!fireauth.util.Delay}\n * @private\n */\nfireauth.RecaptchaRealLoader.DEFAULT_DEPENDENCY_TIMEOUT_ =\n new fireauth.util.Delay(30000, 60000);\n\n\n/**\n * Loads the grecaptcha client library if it is not loaded and returns a promise\n * that resolves on success. If the right conditions are available, will reload\n * the dependencies for a specified language code.\n * @param {?string} hl The reCAPTCHA language code.\n * @return {!goog.Promise<!fireauth.grecaptcha>} A promise that resolves when\n * grecaptcha is loaded.\n * @override\n */\nfireauth.RecaptchaRealLoader.prototype.loadRecaptchaDeps =\n function(hl) {\n var self = this;\n return new goog.Promise(function(resolve, reject) {\n var timer = setTimeout(\n function() {\n reject(new fireauth.AuthError(\n fireauth.authenum.Error.NETWORK_REQUEST_FAILED));\n },\n fireauth.RecaptchaRealLoader.DEFAULT_DEPENDENCY_TIMEOUT_\n .get()\n );\n // Load grecaptcha SDK if not already loaded or language changed since last\n // load and no other rendered reCAPTCHA is visible,\n if (!goog.global['grecaptcha'] || (hl !== self.hl_ && !self.counter_)) {\n // reCAPTCHA saves the onload function and applies it on subsequent\n // reloads. This means that the callback name has to remain the same.\n goog.global[self.cbName_] = function() {\n if (!goog.global['grecaptcha']) {\n clearTimeout(timer);\n // This should not happen.\n reject(new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR));\n } else {\n // Update the current language code.\n self.hl_ = hl;\n var render = goog.global['grecaptcha']['render'];\n // Wrap grecaptcha.render to keep track of rendered grecaptcha. This\n // helps detect if the developer rendered a non\n // firebase.auth.RecaptchaVerifier reCAPTCHA.\n goog.global['grecaptcha']['render'] =\n function(container, parameters) {\n var widgetId = render(container, parameters);\n // Increment only after render succeeds, in case an error is thrown\n // during rendering.\n self.counter_++;\n return widgetId;\n };\n clearTimeout(timer);\n resolve(goog.global['grecaptcha']);\n }\n delete goog.global[self.cbName_];\n };\n // Construct reCAPTCHA URL and on load, run the temporary function.\n var url = goog.html.TrustedResourceUrl.format(\n fireauth.RecaptchaRealLoader.RECAPTCHA_SRC_,\n {'onload': self.cbName_, 'hl': hl || ''});\n // TODO: eventually, replace all dependencies on goog.net.jsloader.\n goog.Promise.resolve(goog.net.jsloader.safeLoad(url))\n .thenCatch(function(error) {\n clearTimeout(timer);\n // In case library fails to load, typically due to a network error,\n // reset cached loader to null to force a refresh on a retrial.\n reject(new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'Unable to load external reCAPTCHA dependencies!'));\n });\n } else {\n clearTimeout(timer);\n resolve(goog.global['grecaptcha']);\n }\n });\n};\n\n\n/**\n * Decrements the reCAPTCHA instance counter.\n * @override\n */\nfireauth.RecaptchaRealLoader.prototype.clearSingleRecaptcha =\n function() {\n this.counter_--;\n};\n\n\n/**\n * @private {?fireauth.RecaptchaRealLoader} The singleton instance\n * for reCAPTCHA dependency loader.\n */\nfireauth.RecaptchaRealLoader.instance_ = null;\n\n\n/**\n * @return {!fireauth.RecaptchaRealLoader} The singleton reCAPTCHA\n * dependency loader instance.\n */\nfireauth.RecaptchaRealLoader.getInstance = function() {\n // Check if there is an existing instance. Otherwise create one and cache it.\n if (!fireauth.RecaptchaRealLoader.instance_) {\n fireauth.RecaptchaRealLoader.instance_ =\n new fireauth.RecaptchaRealLoader();\n }\n return fireauth.RecaptchaRealLoader.instance_;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 reCAPTCHA app verifier and its base class. The\n * former is currently used for web phone authentication whereas the latter is\n * used for the mobile app verification web fallback.\n */\ngoog.provide('fireauth.BaseRecaptchaVerifier');\ngoog.provide('fireauth.RecaptchaVerifier');\n\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.RecaptchaMockLoader');\ngoog.require('fireauth.RecaptchaRealLoader');\ngoog.require('fireauth.RpcHandler');\ngoog.require('fireauth.authenum.Error');\ngoog.require('fireauth.constants');\ngoog.require('fireauth.object');\ngoog.require('fireauth.util');\ngoog.require('goog.Promise');\ngoog.require('goog.array');\ngoog.require('goog.dom');\n\n\n/**\n * Creates the firebase base reCAPTCHA app verifier independent of Firebase\n * App or Auth instances.\n *\n * @param {string} apiKey The API key used to initialize the RPC handler for\n * querying the Auth backend.\n * @param {!Element|string} container The reCAPTCHA container parameter. This\n * has different meaning depending on whether the reCAPTCHA is hidden or\n * visible.\n * @param {?Object=} opt_parameters The optional reCAPTCHA parameters.\n * @param {?(function():?string)=} opt_getLanguageCode The language code getter\n * function.\n * @param {?string=} opt_clientVersion The optional client version to append to\n * RPC header.\n * @param {?Object=} opt_rpcHandlerConfig The optional RPC handler\n * configuration, typically passed when different Auth endpoints are to be\n * used.\n * @param {boolean=} opt_isTestingMode Whether the reCAPTCHA is to be rendered\n * in testing mode.\n * @constructor\n */\nfireauth.BaseRecaptchaVerifier = function(apiKey, container, opt_parameters,\n opt_getLanguageCode, opt_clientVersion, opt_rpcHandlerConfig,\n opt_isTestingMode) {\n // Set the type readonly property needed for full implementation of the\n // firebase.auth.ApplicationVerifier interface.\n fireauth.object.setReadonlyProperty(this, 'type', 'recaptcha');\n /**\n * @private {?goog.Promise<void>} The cached reCAPTCHA ready response. This is\n * null until the first time it is triggered or when an error occurs in\n * getting ready.\n */\n this.cachedReadyPromise_ = null;\n /** @private {?number} The reCAPTCHA widget ID. Null when not rendered. */\n this.widgetId_ = null;\n /** @private {boolean} Whether the instance is already destroyed. */\n this.destroyed_ = false;\n /** @private {!Element|string} The reCAPTCHA container. */\n this.container_ = container;\n /**\n * @private {?fireauth.grecaptcha} The reCAPTCHA client library namespace.\n */\n this.grecaptcha_ = null;\n /**\n * @const @private {!fireauth.RecaptchaLoader} The grecaptcha loader.\n */\n this.recaptchaLoader_ = !!opt_isTestingMode ?\n fireauth.RecaptchaMockLoader.getInstance() :\n fireauth.RecaptchaRealLoader.getInstance();\n // If no parameters passed, use default settings.\n // Currently, visible recaptcha is the default setting as invisible reCAPTCHA\n // is not yet supported by the backend.\n /** @private {!Object} The reCAPTCHA parameters. */\n this.parameters_ = opt_parameters || {\n 'theme': 'light',\n 'type': 'image'\n };\n /** @private {!Array<!goog.Promise<*>|!goog.Promise<void>>} List of\n * pending promises. */\n this.pendingPromises_ = [];\n if (this.parameters_[fireauth.BaseRecaptchaVerifier.ParamName.SITEKEY]) {\n // sitekey should not be provided.\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n 'sitekey should not be provided for reCAPTCHA as one is ' +\n 'automatically provisioned for the current project.');\n }\n /** @private {boolean} Whether the reCAPTCHA is invisible or not. */\n this.isInvisible_ =\n this.parameters_[fireauth.BaseRecaptchaVerifier.ParamName.SIZE] ===\n 'invisible';\n // Check if DOM is supported.\n if (!fireauth.util.isDOMSupported()) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED,\n 'RecaptchaVerifier is only supported in a browser HTTP/HTTPS ' +\n 'environment with DOM support.');\n }\n // reCAPTCHA container must be valid and if visible, not empty.\n // An invisible reCAPTCHA will not render in its container. That container\n // will execute the reCAPTCHA when it is clicked.\n if (!goog.dom.getElement(container) ||\n (!this.isInvisible_ && goog.dom.getElement(container).hasChildNodes())) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n 'reCAPTCHA container is either not found or already contains inner ' +\n 'elements!');\n }\n /**\n * @private {!fireauth.RpcHandler} The RPC handler for querying the auth\n * backend.\n */\n this.rpcHandler_ = new fireauth.RpcHandler(\n apiKey,\n opt_rpcHandlerConfig || null,\n opt_clientVersion || null);\n /**\n * @private {function():?string} Current language code getter.\n */\n this.getLanguageCode_ = opt_getLanguageCode || function() {return null;};\n var self = this;\n /**\n * @private {!Array<function(?string)>} The token change listeners.\n */\n this.tokenListeners_ = [];\n // Wrap token callback.\n var existingCallback =\n this.parameters_[fireauth.BaseRecaptchaVerifier.ParamName.CALLBACK];\n this.parameters_[fireauth.BaseRecaptchaVerifier.ParamName.CALLBACK] =\n function(response) {\n // Dispatch internal event for the token response.\n self.dispatchEvent_(response);\n if (typeof existingCallback === 'function') {\n existingCallback(response);\n } else if (typeof existingCallback === 'string') {\n // Check if the provided callback is a global function name.\n var cb = fireauth.util.getObjectRef(existingCallback, goog.global);\n if (typeof cb === 'function') {\n // If so, trigger it.\n cb(response);\n }\n }\n };\n // Wrap expired token callback.\n var existingExpiredCallback = this.parameters_[\n fireauth.BaseRecaptchaVerifier.ParamName.EXPIRED_CALLBACK];\n this.parameters_[fireauth.BaseRecaptchaVerifier.ParamName.EXPIRED_CALLBACK] =\n function() {\n // Dispatch internal event for the token expiration.\n self.dispatchEvent_(null);\n if (typeof existingExpiredCallback === 'function') {\n existingExpiredCallback();\n } else if (typeof existingExpiredCallback === 'string') {\n // Check if the provided expired callback is a global function name.\n var cb = fireauth.util.getObjectRef(existingExpiredCallback, goog.global);\n if (typeof cb === 'function') {\n // If so, trigger it.\n cb();\n }\n }\n };\n};\n\n\n/**\n * grecaptcha parameter names.\n * @enum {string}\n */\nfireauth.BaseRecaptchaVerifier.ParamName = {\n CALLBACK: 'callback',\n EXPIRED_CALLBACK: 'expired-callback',\n SITEKEY: 'sitekey',\n SIZE: 'size'\n};\n\n\n/**\n * Dispatches the token change event to all subscribed listeners.\n * @param {?string} token The current detected token, null for none.\n * @private\n */\nfireauth.BaseRecaptchaVerifier.prototype.dispatchEvent_ = function(token) {\n for (var i = 0; i < this.tokenListeners_.length; i++) {\n try {\n this.tokenListeners_[i](token);\n } catch (e) {\n // If any handler fails, ignore and run next handler.\n }\n }\n};\n\n\n/**\n * Add a reCAPTCHA token change listener.\n * @param {function(?string)} listener The token listener to add.\n * @private\n */\nfireauth.BaseRecaptchaVerifier.prototype.addTokenChangeListener_ =\n function(listener) {\n this.tokenListeners_.push(listener);\n};\n\n\n/**\n * Remove a reCAPTCHA token change listener.\n * @param {function(?string)} listener The token listener to remove.\n * @private\n */\nfireauth.BaseRecaptchaVerifier.prototype.removeTokenChangeListener_ =\n function(listener) {\n goog.array.removeAllIf(this.tokenListeners_, function(ele) {\n return ele == listener;\n });\n};\n\n\n/**\n * Takes in a pending promise, saves it and adds a clean up callback which\n * forgets the pending promise after it is fulfilled and echoes the promise\n * back.\n * @param {!goog.Promise<*, *>|!goog.Promise<void>} p The pending promise.\n * @return {!goog.Promise<*, *>|!goog.Promise<void>}\n * @private\n */\nfireauth.BaseRecaptchaVerifier.prototype.registerPendingPromise_ = function(p) {\n var self = this;\n // Save created promise in pending list.\n this.pendingPromises_.push(p);\n p.thenAlways(function() {\n // When fulfilled, remove from pending list.\n goog.array.remove(self.pendingPromises_, p);\n });\n // Return the promise.\n return p;\n};\n\n\n/** @return {boolean} Whether verifier instance has pending promises. */\nfireauth.BaseRecaptchaVerifier.prototype.hasPendingPromises = function() {\n return this.pendingPromises_.length != 0;\n};\n\n\n/**\n * Gets the current RecaptchaVerifier in a ready state for rendering by first\n * checking that the environment supports a reCAPTCHA, loading reCAPTCHA\n * dependencies if not already available and then getting the Firebase project's\n * provisioned reCAPTCHA configuration.\n * @return {!goog.Promise<void>} The promise that resolves when recaptcha\n * is ready for rendering.\n * @private\n */\nfireauth.BaseRecaptchaVerifier.prototype.isReady_ = function() {\n var self = this;\n // If previously called, return the cached response.\n if (this.cachedReadyPromise_) {\n return this.cachedReadyPromise_;\n }\n this.cachedReadyPromise_ = this.registerPendingPromise_(goog.Promise.resolve()\n .then(function() {\n // Verify environment first.\n // Fail quickly from a worker environment or non-HTTP/HTTPS environment.\n if (fireauth.util.isHttpOrHttps() && !fireauth.util.isWorker()) {\n // Wait for DOM to be ready as this feature depends on that.\n return fireauth.util.onDomReady();\n } else {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.OPERATION_NOT_SUPPORTED,\n 'RecaptchaVerifier is only supported in a browser HTTP/HTTPS ' +\n 'environment.');\n }\n })\n .then(function() {\n // Load external reCAPTCHA dependencies if not already there, taking\n // into account the current language code.\n return self.recaptchaLoader_.loadRecaptchaDeps(self.getLanguageCode_());\n })\n .then(function(grecaptcha) {\n self.grecaptcha_ = grecaptcha;\n // Load Firebase project's reCAPTCHA configuration.\n return self.rpcHandler_.getRecaptchaParam();\n })\n .then(function(result) {\n // Update the reCAPTCHA parameters.\n self.parameters_[fireauth.BaseRecaptchaVerifier.ParamName.SITEKEY] =\n result[fireauth.RpcHandler.AuthServerField.RECAPTCHA_SITE_KEY];\n }).thenCatch(function(error) {\n // Anytime an error occurs, reset the cached ready promise to rerun on\n // retrial.\n self.cachedReadyPromise_ = null;\n // Rethrow the error.\n throw error;\n }));\n // Return the cached/pending ready promise.\n return this.cachedReadyPromise_;\n};\n\n/**\n * Renders the reCAPTCHA and returns the allocated widget ID.\n * @return {!goog.Promise<number>} The promise that resolves with the reCAPTCHA\n * widget ID when it is rendered.\n */\nfireauth.BaseRecaptchaVerifier.prototype.render = function() {\n this.checkIfDestroyed_();\n var self = this;\n // Get reCAPTCHA ready.\n return this.registerPendingPromise_(this.isReady_().then(function() {\n if (self.widgetId_ === null) {\n // For a visible reCAPTCHA, embed in a wrapper DIV container to allow\n // re-rendering in the same developer provided container.\n var container = self.container_;\n if (!self.isInvisible_) {\n // Get outer container (the developer provided container).\n var outerContainer = goog.dom.getElement(container);\n // Create wrapper temp DIV container.\n container = goog.dom.createDom(goog.dom.TagName.DIV);\n // Add temp DIV to outer container.\n outerContainer.appendChild(container);\n }\n // If not initialized, initialize reCAPTCHA and return its widget ID.\n self.widgetId_ = self.grecaptcha_.render(container, self.parameters_);\n }\n return self.widgetId_;\n }));\n};\n\n\n/**\n * Gets the reCAPTCHA ready and waits for the reCAPTCHA token to be available\n * before resolving the promise returned.\n * @return {!goog.Promise<string>} The promise that resolves with the reCAPTCHA\n * token when reCAPTCHA challenge is solved.\n */\nfireauth.BaseRecaptchaVerifier.prototype.verify = function() {\n // Fail if reCAPTCHA is already destroyed.\n this.checkIfDestroyed_();\n var self = this;\n // Render reCAPTCHA.\n return this.registerPendingPromise_(this.render().then(function(widgetId) {\n return new goog.Promise(function(resolve, reject) {\n // Get current reCAPTCHA token.\n var recaptchaToken = self.grecaptcha_.getResponse(widgetId);\n if (recaptchaToken) {\n // Unexpired token already available. Resolve pending promise with that\n // token.\n resolve(recaptchaToken);\n } else {\n // No token available. Listen to token change.\n var cb = function(token) {\n if (!token) {\n // Ignore token expirations.\n return;\n }\n // Remove temporary token change listener.\n self.removeTokenChangeListener_(cb);\n // Resolve with new token.\n resolve(token);\n };\n // Add temporary token change listener.\n self.addTokenChangeListener_(cb);\n if (self.isInvisible_) {\n // Execute invisible reCAPTCHA to force a challenge.\n // This should do nothing if already triggered either by developer or\n // by a button click.\n self.grecaptcha_.execute(/** @type {number} */ (self.widgetId_));\n }\n }\n });\n }));\n};\n\n\n/**\n * Resets the reCAPTCHA widget.\n */\nfireauth.BaseRecaptchaVerifier.prototype.reset = function() {\n this.checkIfDestroyed_();\n if (this.widgetId_ !== null) {\n this.grecaptcha_.reset(this.widgetId_);\n }\n};\n\n\n/**\n * Throws an error if the reCAPTCHA verifier is already cleared.\n * @private\n */\nfireauth.BaseRecaptchaVerifier.prototype.checkIfDestroyed_ = function() {\n if (this.destroyed_) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.INTERNAL_ERROR,\n 'RecaptchaVerifier instance has been destroyed.');\n }\n};\n\n\n/**\n * Removes the reCAPTCHA from the DOM.\n */\nfireauth.BaseRecaptchaVerifier.prototype.clear = function() {\n this.checkIfDestroyed_();\n this.destroyed_ = true;\n // Decrement reCAPTCHA instance counter.\n this.recaptchaLoader_.clearSingleRecaptcha();\n // Cancel all pending promises.\n for (var i = 0; i < this.pendingPromises_.length; i++) {\n this.pendingPromises_[i].cancel(\n 'RecaptchaVerifier instance has been destroyed.');\n }\n if (!this.isInvisible_) {\n goog.dom.removeChildren(goog.dom.getElement(this.container_));\n }\n};\n\n\n/**\n * Creates the Firebase reCAPTCHA app verifier, publicly available, for the\n * Firebase app provided, used for web phone authentication.\n * This is a subclass of fireauth.BaseRecaptchaVerifier.\n *\n * @param {!Element|string} container The reCAPTCHA container parameter. This\n * has different meaning depending on whether the reCAPTCHA is hidden or\n * visible.\n * @param {?Object=} opt_parameters The optional reCAPTCHA parameters.\n * @param {?firebase.app.App=} opt_app The corresponding Firebase app.\n * @constructor\n * @extends {fireauth.BaseRecaptchaVerifier}\n */\nfireauth.RecaptchaVerifier = function(container, opt_parameters, opt_app) {\n var isTestingMode = false;\n var apiKey;\n try {\n /** @private {!firebase.app.App} The corresponding Firebase app instance. */\n this.app_ = opt_app || firebase.app();\n } catch (error) {\n throw new fireauth.AuthError(\n fireauth.authenum.Error.ARGUMENT_ERROR,\n 'No firebase.app.App instance is currently initialized.');\n }\n // API key is required for web client RPC calls.\n if (this.app_.options && this.app_.options['apiKey']) {\n apiKey = this.app_.options['apiKey'];\n } else {\n throw new fireauth.AuthError(fireauth.authenum.Error.INVALID_API_KEY);\n }\n var self = this;\n // Construct the language code getter based on the underlying Auth instance.\n var getLanguageCode = function() {\n var languageCode;\n // Get the latest language setting.\n // reCAPTCHA does not support updating the language of an already\n // rendered reCAPTCHA. Reloading the SDK with the new hl will break\n // the existing rendered localized reCAPTCHA. We will need to\n // document that a new fireauth.BaseRecaptchaVerifier instance needs\n // to be instantiated after the language is updated. Otherwise, the\n // old language code will remain active on the existing instance.\n try {\n languageCode = self.app_['auth']().getLanguageCode();\n } catch (e) {\n languageCode = null;\n }\n return languageCode;\n };\n // Get the framework version from Auth instance.\n var frameworkVersion = null;\n try {\n frameworkVersion = this.app_['auth']().getFramework();\n } catch (e) {\n // Do nothing.\n }\n try {\n isTestingMode =\n this.app_['auth']()['settings']['appVerificationDisabledForTesting'];\n } catch (e) {\n // Do nothing.\n }\n // Get the client version based on the Firebase JS version.\n var clientFullVersion = firebase.SDK_VERSION ?\n fireauth.util.getClientVersion(\n fireauth.util.ClientImplementation.JSCORE, firebase.SDK_VERSION,\n frameworkVersion) :\n null;\n // Call the superclass constructor with the computed API key, reCAPTCHA\n // container, optional parameters, language code getter, Firebase JS client\n // version and the current client configuration endpoints.\n fireauth.RecaptchaVerifier.base(this, 'constructor', apiKey,\n container, opt_parameters, getLanguageCode, clientFullVersion,\n fireauth.constants.getEndpointConfig(fireauth.constants.clientEndpoint),\n isTestingMode);\n};\ngoog.inherits(fireauth.RecaptchaVerifier, fireauth.BaseRecaptchaVerifier);\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 function argument validation for third-party calls\n * that cannot be validated with Closure compiler.\n */\n\ngoog.provide('fireauth.args');\ngoog.provide('fireauth.args.Argument');\n\ngoog.require('fireauth.Auth');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthUser');\ngoog.require('fireauth.MultiFactorSession');\ngoog.require('fireauth.authenum.Error');\n\n\n/**\n * Represents an argument to a function. Fields:\n * <ul>\n * <li> name: A label for the argument. For example, the names of the arguments\n * to a signIn() function might be \"email\" and \"password\".\n * <li> typeLabel: A label for the expected type of the argument, starting with\n * an article, for example, \"an object\" or \"a valid credential\".\n * <li> optional: Whether or not this argument is optional. Optional arguments\n * cannot come after non-optional arguments in the input to validate().\n * <li> validator: A function that takes the passed value of this argument\n * and returns whether the value is valid or not.\n * </ul>\n * @typedef {{\n * name: string,\n * typeLabel: string,\n * optional: boolean,\n * validator: function (*) : boolean,\n * }}\n */\nfireauth.args.Argument;\n\n\n/**\n * Validates the arguments to a method call and throws an error if invalid. This\n * can be used to validate external calls where the Closure compiler cannot\n * detect errors.\n *\n * Example usage:\n * function greet(recipient, opt_useFormalLanguage) {\n * fireauth.args.validate('greet', [\n * fireauth.args.string('recipient'),\n * fireauth.args.bool('opt_useFormalLanguage', true)\n * ], arguments);\n * if (opt_useFormalLanguage) {\n * console.log('Good day, ' + recipient + '.');\n * } else {\n * console.log('Wassup, ' + recipient + '?');\n * }\n * }\n * greet('Mr. Manager', true); // Prints 'Good day, Mr. Manager.'\n * greet('Billy Bob'); // Prints 'Wassup, Billy Bob?'\n * greet(133); // Throws 'greet failed: First argument \"recipient\" must be a\n * // valid string.'\n * greet(); // Throws 'greet failed: Expected 1-2 arguments but got 0.'\n * greet('Mr. Manager', true, 'ohno'); // Throws 'greet failed: Expected 1-2\n * // arguments but got 3.'\n *\n * This can also be used to validate setters by passing an additional true\n * argument to fireauth.args.validate. This modifies the error message to be\n * relevant for that setter.\n *\n * @param {string} apiName The name of the method being called, to display in\n * the error message for debugging purposes.\n * @param {!Array<!fireauth.args.Argument>} expected The expected arguments.\n * @param {!IArrayLike} actual The arguments object of the function whose\n * parameters we want to validate.\n * @param {boolean=} opt_isSetter Whether the function is a setter which takes\n * a single argument.\n */\nfireauth.args.validate = function(apiName, expected, actual, opt_isSetter) {\n // Convert the arguments object into a real array.\n var actualAsArray = Array.prototype.slice.call(actual);\n var errorMessage = fireauth.args.validateAndGetMessage_(\n expected, actualAsArray, opt_isSetter);\n if (errorMessage) {\n throw new fireauth.AuthError(fireauth.authenum.Error.ARGUMENT_ERROR,\n apiName + ' failed: ' + errorMessage);\n }\n};\n\n\n/**\n * @param {!Array<!fireauth.args.Argument>} expected\n * @param {!Array<*>} actual\n * @param {boolean=} opt_isSetter Whether the function is a setter which takes\n * a single argument.\n * @return {?string} The error message if there is an error, or otherwise\n * null.\n * @private\n */\nfireauth.args.validateAndGetMessage_ =\n function(expected, actual, opt_isSetter) {\n var minNumArgs = fireauth.args.calcNumRequiredArgs_(expected);\n var maxNumArgs = expected.length;\n if (actual.length < minNumArgs || maxNumArgs < actual.length) {\n return fireauth.args.makeLengthError_(minNumArgs, maxNumArgs,\n actual.length);\n }\n\n for (var i = 0; i < actual.length; i++) {\n // Argument is optional and undefined is explicitly passed.\n var optionalUndefined = expected[i].optional && actual[i] === undefined;\n // Check if invalid argument and the argument is not optional with undefined\n // passed.\n if (!expected[i].validator(actual[i]) && !optionalUndefined) {\n return fireauth.args.makeErrorAtPosition_(i, expected[i], opt_isSetter);\n }\n }\n\n return null;\n};\n\n\n/**\n * @param {!Array<!fireauth.args.Argument>} expected\n * @return {number} The number of required arguments.\n * @private\n */\nfireauth.args.calcNumRequiredArgs_ = function(expected) {\n var numRequiredArgs = 0;\n var isOptionalSection = false;\n for (var i = 0; i < expected.length; i++) {\n if (expected[i].optional) {\n isOptionalSection = true;\n } else {\n if (isOptionalSection) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'Argument validator encountered a required argument after an ' +\n 'optional argument.');\n }\n numRequiredArgs++;\n }\n }\n return numRequiredArgs;\n};\n\n\n/**\n * @param {number} min The minimum number of arguments to the function,\n * inclusive.\n * @param {number} max The maximum number of arguments to the function,\n * inclusive.\n * @param {number} actual The actual number of arguments received.\n * @return {string} The error message.\n * @private\n */\nfireauth.args.makeLengthError_ = function(min, max, actual) {\n var numExpectedString;\n if (min == max) {\n if (min == 1) {\n numExpectedString = '1 argument';\n } else {\n numExpectedString = min + ' arguments';\n }\n } else {\n numExpectedString = min + '-' + max + ' arguments';\n }\n return 'Expected ' + numExpectedString + ' but got ' + actual + '.';\n};\n\n\n/**\n * @param {number} position The position at which there was an error.\n * @param {!fireauth.args.Argument} expectedType The expected type of the\n * argument, which was violated.\n * @param {boolean=} opt_isSetter Whether the function is a setter which takes\n * a single argument.\n * @return {string} The error message.\n * @private\n */\nfireauth.args.makeErrorAtPosition_ =\n function(position, expectedType, opt_isSetter) {\n var ordinal = fireauth.args.makeOrdinal_(position);\n var argName = expectedType.name ?\n fireauth.args.quoteString_(expectedType.name) + ' ' : '';\n // Add support to setters for readable/writable properties which take a\n // required single argument.\n var errorPrefix = !!opt_isSetter ? '' : ordinal + ' argument ';\n return errorPrefix + argName + 'must be ' +\n expectedType.typeLabel + '.';\n};\n\n\n/** @private {!Array<string>} The first few ordinal numbers. */\nfireauth.args.ORDINAL_NUMBERS_ = ['First', 'Second', 'Third', 'Fourth',\n 'Fifth', 'Sixth', 'Seventh', 'Eighth', 'Ninth'];\n\n\n/**\n * @param {number} cardinal An integer.\n * @return {string} The integer converted to an ordinal number, starting at\n * \"First\". That is, makeOrdinal_(0) returns \"First\" and makeOrdinal_(1)\n * returns \"Second\", etc.\n * @private\n */\nfireauth.args.makeOrdinal_ = function(cardinal) {\n // We only support the first few ordinal numbers. We could provide a more\n // robust solution, but it is unlikely that a function would need more than\n // nine arguments.\n if (cardinal < 0 || cardinal >= fireauth.args.ORDINAL_NUMBERS_.length) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR,\n 'Argument validator received an unsupported number of arguments.');\n }\n return fireauth.args.ORDINAL_NUMBERS_[cardinal];\n};\n\n\n/**\n * Specifies a string argument.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.string = function(opt_name, opt_optional) {\n return {\n name: opt_name || '',\n typeLabel: 'a valid string',\n optional: !!opt_optional,\n validator: x => typeof x === 'string'\n };\n};\n\n\n/**\n * Specifies a boolean argument.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.bool = function(opt_name, opt_optional) {\n return {\n name: opt_name || '',\n typeLabel: 'a boolean',\n optional: !!opt_optional,\n validator: x => typeof x === 'boolean'\n };\n};\n\n\n/**\n * Specifies a number argument.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.number = function(opt_name, opt_optional) {\n return {\n name: opt_name || '',\n typeLabel: 'a valid number',\n optional: !!opt_optional,\n validator: x => typeof x === 'number'\n };\n};\n\n\n/**\n * Specifies an object argument.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.object = function(opt_name, opt_optional) {\n return {\n name: opt_name || '',\n typeLabel: 'a valid object',\n optional: !!opt_optional,\n validator: goog.isObject\n };\n};\n\n\n/**\n * Specifies a function argument.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.func = function(opt_name, opt_optional) {\n return {\n name: opt_name || '',\n typeLabel: 'a function',\n optional: !!opt_optional,\n validator: goog.isFunction\n };\n};\n\n\n/**\n * Specifies a null argument.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.null = function(opt_name, opt_optional) {\n return {\n name: opt_name || '',\n typeLabel: 'null',\n optional: !!opt_optional,\n validator: x => x === null\n };\n};\n\n\n/**\n * Specifies an HTML element argument.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.element = function(opt_name, opt_optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: opt_name || '',\n typeLabel: 'an HTML element',\n optional: !!opt_optional,\n validator: /** @type {function(!Element) : boolean} */ (\n function(element) {\n return !!(element && element instanceof Element);\n })\n });\n};\n\n\n/**\n * Specifies an instance of Firebase Auth.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.firebaseAuth = function(opt_optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: 'auth',\n typeLabel: 'an instance of Firebase Auth',\n optional: !!opt_optional,\n validator: /** @type {function(!fireauth.Auth) : boolean} */ (\n function(auth) {\n return !!(auth && auth instanceof fireauth.Auth);\n })\n });\n};\n\n\n/**\n * Specifies an instance of Firebase User.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.firebaseUser = function(opt_optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: 'user',\n typeLabel: 'an instance of Firebase User',\n optional: !!opt_optional,\n validator: /** @type {function(!fireauth.AuthUser) : boolean} */ (\n function(user) {\n return !!(user && user instanceof fireauth.AuthUser);\n })\n });\n};\n\n\n/**\n * Specifies an instance of Firebase App.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.firebaseApp = function(opt_optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: 'app',\n typeLabel: 'an instance of Firebase App',\n optional: !!opt_optional,\n validator: /** @type {function(!firebase.app.App) : boolean} */ (\n function(app) {\n return !!(app && app instanceof firebase.app.App);\n })\n });\n};\n\n\n/**\n * Specifies an argument that implements the fireauth.AuthCredential interface.\n * @param {?fireauth.idp.ProviderId=} opt_requiredProviderId The required type\n * of provider.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.authCredential =\n function(opt_requiredProviderId, opt_name, opt_optional) {\n var name = opt_name ||\n (opt_requiredProviderId ?\n opt_requiredProviderId + 'Credential' :\n 'credential');\n var typeLabel = opt_requiredProviderId ?\n 'a valid ' + opt_requiredProviderId + ' credential' :\n 'a valid credential';\n return /** @type {!fireauth.args.Argument} */ ({\n name: name,\n typeLabel: typeLabel,\n optional: !!opt_optional,\n validator: /** @type {function(!fireauth.AuthCredential) : boolean} */ (\n function(credential) {\n if (!credential) {\n return false;\n }\n // If opt_requiredProviderId is set, make sure it matches the\n // credential's providerId.\n var matchesRequiredProvider = !opt_requiredProviderId ||\n (credential['providerId'] === opt_requiredProviderId);\n return !!(credential.getIdTokenProvider && matchesRequiredProvider);\n })\n });\n};\n\n\n/**\n * Specifies an argument that implements the fireauth.MultiFactorAssertion\n * interface.\n * @param {?string=} requiredFactorId The required type of second factor.\n * @param {?string=} optionalName The name of the argument.\n * @param {?boolean=} optionalArg Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.multiFactorAssertion =\n function(requiredFactorId, optionalName, optionalArg) {\n var name = optionalName ||\n (requiredFactorId ?\n requiredFactorId + 'MultiFactorAssertion' : 'multiFactorAssertion');\n var typeLabel = requiredFactorId ?\n 'a valid ' + requiredFactorId + ' multiFactorAssertion' :\n 'a valid multiFactorAssertion';\n return /** @type {!fireauth.args.Argument} */ ({\n name: name,\n typeLabel: typeLabel,\n optional: !!optionalArg,\n validator:\n /** @type {function(!fireauth.MultiFactorAssertion) : boolean} */ (\n function(assertion) {\n if (!assertion) {\n return false;\n }\n // If requiredFactorId is set, make sure it matches the\n // assertion's factorId.\n var matchesRequiredFactor = !requiredFactorId ||\n (assertion['factorId'] === requiredFactorId);\n return !!(assertion.process && matchesRequiredFactor);\n })\n });\n};\n\n\n/**\n * Specifies an argument that implements the fireauth.AuthProvider interface.\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.authProvider = function(opt_name, opt_optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: opt_name || 'authProvider',\n typeLabel: 'a valid Auth provider',\n optional: !!opt_optional,\n validator: /** @type {function(!fireauth.AuthProvider) : boolean} */ (\n function(provider) {\n return !!(provider &&\n provider['providerId'] &&\n provider.hasOwnProperty &&\n provider.hasOwnProperty('isOAuthProvider'));\n })\n });\n};\n\n\n/**\n * Specifies a phone info options argument.\n * @param {?string=} name The name of the argument.\n * @param {?boolean=} optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.phoneInfoOptions = function(name, optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: name || 'phoneInfoOptions',\n typeLabel: 'valid phone info options',\n optional: !!optional,\n validator: /** @type {function(!Object) : boolean} */ (\n function(phoneInfoOptions) {\n if (!phoneInfoOptions) {\n return false;\n }\n // For multi-factor enrollment, phone number and MFA session should\n // be provided.\n if (phoneInfoOptions['session'] &&\n phoneInfoOptions['phoneNumber']) {\n return fireauth.args.validateMultiFactorSession_(\n phoneInfoOptions['session'],\n fireauth.MultiFactorSession.Type.ENROLL) &&\n typeof phoneInfoOptions['phoneNumber'] === 'string';\n // For multi-factor sign-in, phone multi-factor hint and MFA session\n // are provided.\n } else if (phoneInfoOptions['session'] &&\n phoneInfoOptions['multiFactorHint']) {\n return fireauth.args.validateMultiFactorSession_(\n phoneInfoOptions['session'],\n fireauth.MultiFactorSession.Type.SIGN_IN) &&\n fireauth.args.validateMultiFactorInfo_(\n phoneInfoOptions['multiFactorHint']);\n // For multi-factor sign-in, phone multi-factor UID and MFA session\n // are provided.\n } else if (phoneInfoOptions['session'] &&\n phoneInfoOptions['multiFactorUid']) {\n return fireauth.args.validateMultiFactorSession_(\n phoneInfoOptions['session'],\n fireauth.MultiFactorSession.Type.SIGN_IN) &&\n typeof phoneInfoOptions['multiFactorUid'] === 'string';\n // For single-factor sign-in, only phone number needs to be provided.\n } else if (phoneInfoOptions['phoneNumber']) {\n return typeof phoneInfoOptions['phoneNumber'] === 'string';\n }\n return false;\n })\n });\n};\n\n\n/**\n * @param {*} session The multi-factor session object.\n * @param {!fireauth.MultiFactorSession.Type} type The session type.\n * @return {boolean} Whether the seesion is a valid multi-factor session.\n * @private\n */\nfireauth.args.validateMultiFactorSession_ = function(session, type) {\n return goog.isObject(session) && typeof session.type === 'string' &&\n session.type === type &&\n goog.isFunction(session.getRawSession);\n};\n\n\n/**\n * @param {*} info The multi-factor info object.\n * @return {boolean} Whether the info is a valid multi-factor info.\n * @private\n */\nfireauth.args.validateMultiFactorInfo_ = function(info) {\n return goog.isObject(info) && typeof info['uid'] === 'string';\n};\n\n\n/**\n * Specifies an argument that implements the fireauth.MultiFactorInfo\n * interface.\n * @param {?string=} name The name of the argument.\n * @param {?boolean=} optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.multiFactorInfo = function(name, optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: name || 'multiFactorInfo',\n typeLabel: 'a valid multiFactorInfo',\n optional: !!optional,\n validator: fireauth.args.validateMultiFactorInfo_\n });\n};\n\n\n/**\n * Specifies an argument that implements the firebase.auth.ApplicationVerifier\n * interface.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.applicationVerifier = function(opt_optional) {\n return /** @type {!fireauth.args.Argument} */ ({\n name: 'applicationVerifier',\n typeLabel: 'an implementation of firebase.auth.ApplicationVerifier',\n optional: !!opt_optional,\n validator:\n /** @type {function(!firebase.auth.ApplicationVerifier) : boolean} */ (\n function(applicationVerifier) {\n return !!(applicationVerifier &&\n typeof applicationVerifier.type === 'string' &&\n goog.isFunction(applicationVerifier.verify));\n })\n });\n};\n\n\n/**\n * Specifies an argument that can be either of two argument types.\n * @param {!fireauth.args.Argument} optionA\n * @param {!fireauth.args.Argument} optionB\n * @param {?string=} opt_name The name of the argument.\n * @param {?boolean=} opt_optional Whether or not this argument is optional.\n * Defaults to false.\n * @return {!fireauth.args.Argument}\n */\nfireauth.args.or = function(optionA, optionB, opt_name, opt_optional) {\n return {\n name: opt_name || '',\n typeLabel: optionA.typeLabel + ' or ' + optionB.typeLabel,\n optional: !!opt_optional,\n validator: function(value) {\n return optionA.validator(value) || optionB.validator(value);\n }\n };\n};\n\n\n/**\n * @param {string} str\n * @return {string} The string surrounded with quotes.\n * @private\n */\nfireauth.args.quoteString_ = function(str) {\n return '\"' + str + '\"';\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 utilities for exporting public APIs, with error\n * checking.\n */\n\ngoog.provide('fireauth.exportlib');\ngoog.provide('fireauth.exportlib.ExportedMethod');\n\ngoog.require('fireauth.args');\n\n\n/**\n * Type constant for Firebase Auth.\n * @const {string}\n */\nfireauth.exportlib.AUTH_TYPE = 'auth';\n\n\n/**\n * Represents an exported method, with the exported name of the method and the\n * expected arguments to that method.\n * @typedef {{\n * name: string,\n * args: (Array<!fireauth.args.Argument>|null|undefined)\n * }}\n */\nfireauth.exportlib.ExportedMethod;\n\n\n/**\n * Represents an exported property, with the exported name of the property and\n * the expected argument to the setter of this property.\n * @typedef {{\n * name: string,\n * arg: !fireauth.args.Argument\n * }}\n */\nfireauth.exportlib.ExportedProperty;\n\n\n/**\n * Exports prototype methods of an object.\n * @param {!Object} protObj The prototype of an object.\n * @param {!Object<string, fireauth.exportlib.ExportedMethod>} fnMap The map of\n * prototype functions to their export name and expected arguments.\n */\nfireauth.exportlib.exportPrototypeMethods = function(protObj, fnMap) {\n // This method exports methods by aliasing the unobfuscated function name\n // (specified as a string in the \"name\" field of ExportedMethod) to the\n // obfuscated function name (specified as a key of the fnMap object).\n //\n // To give a concrete example, let's say that we have this method:\n // fireauth.Auth.prototype.fetchProvidersForEmail = function() { ... };\n //\n // In the exports file, we export as follows:\n // fireauth.exportlib.exportPrototypeMethods(fireauth.Auth.prototype, {\n // fetchProvidersForEmail: {name: 'fetchProvidersForEmail', args: ...}\n // });\n //\n // When the compiler obfuscates the code, the code above will become something\n // like this:\n // fireauth.Auth.prototype.qZ = function() { ... };\n // fireauth.exportlib.exportPrototypeMethods(fireauth.Auth.prototype, {\n // qZ: {name: 'fetchProvidersForEmail', args: ...}\n // });\n //\n // (Of course, fireauth.Auth and fireauth.exportlib.exportPrototypeMethods\n // would also be obfuscated). Note that the key in fnMap is obfuscated but the\n // \"name\" field in the ExportedMethod is not. Now, exportPrototypeMethods can\n // export fetchProvidersForEmail by reading the key (\"qZ\") and the \"name\"\n // field (\"fetchProvidersForEmail\") and essentially executing this:\n // fireauth.Auth.prototype['fetchProvidersForEmail'] =\n // fireauth.Auth.prototype['qZ'];\n for (var obfuscatedFnName in fnMap) {\n var unobfuscatedFnName = fnMap[obfuscatedFnName].name;\n protObj[unobfuscatedFnName] =\n fireauth.exportlib.wrapMethodWithArgumentVerifier_(\n unobfuscatedFnName, protObj[obfuscatedFnName],\n fnMap[obfuscatedFnName].args);\n }\n};\n\n\n/**\n * Exports properties of an object. See the docs for exportPrototypeMethods for\n * more information about how this works.\n * @param {!Object} protObj The prototype of an object.\n * @param {!Object<string, !fireauth.exportlib.ExportedProperty>} propMap The\n * map of properties to their export names.\n */\nfireauth.exportlib.exportPrototypeProperties = function(protObj, propMap) {\n for (var obfuscatedPropName in propMap) {\n var unobfuscatedPropName = propMap[obfuscatedPropName].name;\n // Don't alias a property to itself.\n // Downside is that argument validation will not be possible. For now, to\n // get around it, ensure unobfuscated property names are different\n // than the corresponding obfuscated property names.\n if (unobfuscatedPropName === obfuscatedPropName) {\n continue;\n }\n /**\n * @this {!Object}\n * @param {string} obfuscatedPropName The obfuscated property name.\n * @return {*} The value of the property.\n */\n var getter = function(obfuscatedPropName) {\n return this[obfuscatedPropName];\n };\n /**\n * @this {!Object}\n * @param {string} unobfuscatedPropName The unobfuscated property name.\n * @param {string} obfuscatedPropName The obfuscated property name.\n * @param {!fireauth.args.Argument} expectedArg The expected argument to the\n * setter of this property.\n * @param {*} value The new value of the property.\n */\n var setter = function(unobfuscatedPropName, obfuscatedPropName,\n expectedArg, value) {\n // Validate the argument before setting it.\n fireauth.args.validate(\n unobfuscatedPropName, [expectedArg], [value], true);\n this[obfuscatedPropName] = value;\n };\n // Get the expected argument.\n var expectedArg = propMap[obfuscatedPropName].arg;\n Object.defineProperty(protObj, unobfuscatedPropName, {\n /**\n * @this {!Object}\n * @return {*} The value of the property.\n */\n get: goog.partial(getter, obfuscatedPropName),\n /**\n * @this {!Object}\n * @param {*} value The new value of the property.\n */\n set: goog.partial(setter, unobfuscatedPropName, obfuscatedPropName,\n expectedArg),\n enumerable: true\n });\n }\n};\n\n\n/**\n * Export a static method as a public API.\n * @param {!Object} parentObj The parent object to patch.\n * @param {string} name The public name of the method.\n * @param {!Function} func The method.\n * @param {?Array<!fireauth.args.Argument>=} opt_expectedArgs The expected\n * arguments to the method.\n */\nfireauth.exportlib.exportFunction = function(parentObj, name, func,\n opt_expectedArgs) {\n parentObj[name] = fireauth.exportlib.wrapMethodWithArgumentVerifier_(\n name, func, opt_expectedArgs);\n};\n\n\n/**\n * Wraps a method with a function that first verifies the arguments to the\n * method and then calls the original method.\n * @param {string} methodName The name of the method, which will be displayed\n * on the error message if the arguments are not valid.\n * @param {!Function} method The method to be wrapped.\n * @param {?Array<!fireauth.args.Argument>=} opt_expectedArgs The expected\n * arguments.\n * @return {!Function} The wrapped method.\n * @private\n */\nfireauth.exportlib.wrapMethodWithArgumentVerifier_ = function(methodName,\n method, opt_expectedArgs) {\n if (!opt_expectedArgs) {\n return method;\n }\n var shortName = fireauth.exportlib.extractMethodNameFromFullPath_(methodName);\n var wrapper = function() {\n var argumentsAsArray = Array.prototype.slice.call(arguments);\n fireauth.args.validate(shortName,\n /** @type {!Array<!fireauth.args.Argument>} */ (opt_expectedArgs),\n argumentsAsArray);\n return method.apply(this, argumentsAsArray);\n };\n // Reattach all static stuff to wrapper.\n for (var key in method) {\n wrapper[key] = method[key];\n }\n // Reattach all prototype stuff to wrapper.\n for (var key in method.prototype) {\n wrapper.prototype[key] = method.prototype[key];\n }\n // Return wrapper with all of method's static and prototype methods and\n // properties.\n return wrapper;\n};\n\n\n/**\n * From a full path to a method (e.g. \"fireauth.GoogleAuthProvider.credential\"),\n * get just the method name (\"credential\").\n * @param {string} path The full path.\n * @return {string} The method name.\n * @private\n */\nfireauth.exportlib.extractMethodNameFromFullPath_ = function(path) {\n var parts = path.split('.');\n return parts[parts.length - 1];\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\ngoog.provide('fireauth.exports');\n\ngoog.require('fireauth.ActionCodeInfo');\ngoog.require('fireauth.ActionCodeURL');\ngoog.require('fireauth.Auth');\ngoog.require('fireauth.AuthCredential');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.AuthErrorWithCredential');\ngoog.require('fireauth.AuthSettings');\ngoog.require('fireauth.AuthUser');\ngoog.require('fireauth.ConfirmationResult');\ngoog.require('fireauth.EmailAuthCredential');\ngoog.require('fireauth.EmailAuthProvider');\ngoog.require('fireauth.FacebookAuthProvider');\ngoog.require('fireauth.GRecaptchaMockFactory');\ngoog.require('fireauth.GithubAuthProvider');\ngoog.require('fireauth.GoogleAuthProvider');\ngoog.require('fireauth.InvalidOriginError');\ngoog.require('fireauth.MultiFactorError');\ngoog.require('fireauth.MultiFactorResolver');\ngoog.require('fireauth.MultiFactorUser');\ngoog.require('fireauth.OAuthCredential');\ngoog.require('fireauth.OAuthProvider');\ngoog.require('fireauth.PhoneAuthCredential');\ngoog.require('fireauth.PhoneAuthProvider');\ngoog.require('fireauth.PhoneMultiFactorGenerator');\ngoog.require('fireauth.RecaptchaVerifier');\ngoog.require('fireauth.SAMLAuthCredential');\ngoog.require('fireauth.SAMLAuthProvider');\ngoog.require('fireauth.TwitterAuthProvider');\ngoog.require('fireauth.args');\ngoog.require('fireauth.authStorage.Persistence');\ngoog.require('fireauth.exportlib');\ngoog.require('fireauth.grecaptcha');\ngoog.require('fireauth.idp.ProviderId');\ngoog.require('goog.Promise');\n\n/** @define {string} */\nconst AUTH_NPM_PACKAGE_VERSION = '';\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.Auth.prototype, {\n applyActionCode: {\n name: 'applyActionCode',\n args: [fireauth.args.string('code')]\n },\n checkActionCode: {\n name: 'checkActionCode',\n args: [fireauth.args.string('code')]\n },\n confirmPasswordReset: {\n name: 'confirmPasswordReset',\n args: [\n fireauth.args.string('code'),\n fireauth.args.string('newPassword')\n ]\n },\n createUserWithEmailAndPassword: {\n name: 'createUserWithEmailAndPassword',\n args: [fireauth.args.string('email'), fireauth.args.string('password')]\n },\n fetchSignInMethodsForEmail: {\n name: 'fetchSignInMethodsForEmail',\n args: [fireauth.args.string('email')]\n },\n getRedirectResult: {\n name: 'getRedirectResult',\n args: []\n },\n isSignInWithEmailLink: {\n name: 'isSignInWithEmailLink',\n args: [fireauth.args.string('emailLink')]\n },\n onAuthStateChanged: {\n name: 'onAuthStateChanged',\n args: [\n fireauth.args.or(\n fireauth.args.object(),\n fireauth.args.func(),\n 'nextOrObserver'),\n fireauth.args.func('opt_error', true),\n fireauth.args.func('opt_completed', true)\n ]\n },\n onIdTokenChanged: {\n name: 'onIdTokenChanged',\n args: [\n fireauth.args.or(\n fireauth.args.object(),\n fireauth.args.func(),\n 'nextOrObserver'),\n fireauth.args.func('opt_error', true),\n fireauth.args.func('opt_completed', true)\n ]\n },\n sendPasswordResetEmail: {\n name: 'sendPasswordResetEmail',\n args: [\n fireauth.args.string('email'),\n fireauth.args.or(\n fireauth.args.object('opt_actionCodeSettings', true),\n fireauth.args.null(null, true),\n 'opt_actionCodeSettings',\n true)\n ]\n },\n sendSignInLinkToEmail: {\n name: 'sendSignInLinkToEmail',\n args: [\n fireauth.args.string('email'),\n fireauth.args.object('actionCodeSettings')\n ]\n },\n setPersistence: {\n name: 'setPersistence',\n args: [fireauth.args.string('persistence')]\n },\n signInAndRetrieveDataWithCredential: {\n name: 'signInAndRetrieveDataWithCredential',\n args: [fireauth.args.authCredential()]\n },\n signInAnonymously: {\n name: 'signInAnonymously',\n args: []\n },\n signInWithCredential: {\n name: 'signInWithCredential',\n args: [fireauth.args.authCredential()]\n },\n signInWithCustomToken: {\n name: 'signInWithCustomToken',\n args: [fireauth.args.string('token')]\n },\n signInWithEmailAndPassword: {\n name: 'signInWithEmailAndPassword',\n args: [fireauth.args.string('email'), fireauth.args.string('password')]\n },\n signInWithEmailLink: {\n name: 'signInWithEmailLink',\n args: [\n fireauth.args.string('email'), fireauth.args.string('emailLink', true)\n ]\n },\n signInWithPhoneNumber: {\n name: 'signInWithPhoneNumber',\n args: [\n fireauth.args.string('phoneNumber'),\n fireauth.args.applicationVerifier()\n ]\n },\n signInWithPopup: {\n name: 'signInWithPopup',\n args: [fireauth.args.authProvider()]\n },\n signInWithRedirect: {\n name: 'signInWithRedirect',\n args: [fireauth.args.authProvider()]\n },\n updateCurrentUser: {\n name: 'updateCurrentUser',\n args: [\n fireauth.args.or(\n fireauth.args.firebaseUser(),\n fireauth.args.null(),\n 'user')\n ]\n },\n signOut: {\n name: 'signOut',\n args: []\n },\n toJSON: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n },\n useDeviceLanguage: {\n name: 'useDeviceLanguage',\n args: []\n },\n verifyPasswordResetCode: {\n name: 'verifyPasswordResetCode',\n args: [fireauth.args.string('code')]\n }\n });\n\nfireauth.exportlib.exportPrototypeProperties(\n fireauth.Auth.prototype, {\n 'lc': {\n name: 'languageCode',\n arg: fireauth.args.or(\n fireauth.args.string(),\n fireauth.args.null(),\n 'languageCode')\n },\n 'ti': {\n name: 'tenantId',\n arg: fireauth.args.or(\n fireauth.args.string(),\n fireauth.args.null(),\n 'tenantId')\n }\n });\n\n// Exports firebase.auth.Auth.Persistence.\nfireauth.Auth['Persistence'] = fireauth.authStorage.Persistence;\nfireauth.Auth['Persistence']['LOCAL'] = fireauth.authStorage.Persistence.LOCAL;\nfireauth.Auth['Persistence']['SESSION'] =\n fireauth.authStorage.Persistence.SESSION;\nfireauth.Auth['Persistence']['NONE'] = fireauth.authStorage.Persistence.NONE;\n\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.AuthUser.prototype, {\n 'delete': {\n name: 'delete',\n args: []\n },\n getIdTokenResult: {\n name: 'getIdTokenResult',\n args: [fireauth.args.bool('opt_forceRefresh', true)]\n },\n getIdToken: {\n name: 'getIdToken',\n args: [fireauth.args.bool('opt_forceRefresh', true)]\n },\n linkAndRetrieveDataWithCredential: {\n name: 'linkAndRetrieveDataWithCredential',\n args: [fireauth.args.authCredential()]\n },\n linkWithCredential: {\n name: 'linkWithCredential',\n args: [fireauth.args.authCredential()]\n },\n linkWithPhoneNumber: {\n name: 'linkWithPhoneNumber',\n args: [\n fireauth.args.string('phoneNumber'),\n fireauth.args.applicationVerifier()\n ]\n },\n linkWithPopup: {\n name: 'linkWithPopup',\n args: [fireauth.args.authProvider()]\n },\n linkWithRedirect: {\n name: 'linkWithRedirect',\n args: [fireauth.args.authProvider()]\n },\n reauthenticateAndRetrieveDataWithCredential: {\n name: 'reauthenticateAndRetrieveDataWithCredential',\n args: [fireauth.args.authCredential()]\n },\n reauthenticateWithCredential: {\n name: 'reauthenticateWithCredential',\n args: [fireauth.args.authCredential()]\n },\n reauthenticateWithPhoneNumber: {\n name: 'reauthenticateWithPhoneNumber',\n args: [\n fireauth.args.string('phoneNumber'),\n fireauth.args.applicationVerifier()\n ]\n },\n reauthenticateWithPopup: {\n name: 'reauthenticateWithPopup',\n args: [fireauth.args.authProvider()]\n },\n reauthenticateWithRedirect: {\n name: 'reauthenticateWithRedirect',\n args: [fireauth.args.authProvider()]\n },\n reload: {\n name: 'reload',\n args: []\n },\n sendEmailVerification: {\n name: 'sendEmailVerification',\n args: [\n fireauth.args.or(\n fireauth.args.object('opt_actionCodeSettings', true),\n fireauth.args.null(null, true),\n 'opt_actionCodeSettings',\n true)\n ]\n },\n toJSON: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n },\n unlink: {\n name: 'unlink',\n args: [fireauth.args.string('provider')]\n },\n updateEmail: {\n name: 'updateEmail',\n args: [fireauth.args.string('email')]\n },\n updatePassword: {\n name: 'updatePassword',\n args: [fireauth.args.string('password')]\n },\n updatePhoneNumber: {\n name: 'updatePhoneNumber',\n args: [fireauth.args.authCredential(fireauth.idp.ProviderId.PHONE)]\n },\n updateProfile: {\n name: 'updateProfile',\n args: [fireauth.args.object('profile')]\n },\n verifyBeforeUpdateEmail: {\n name: 'verifyBeforeUpdateEmail',\n args: [\n fireauth.args.string('email'),\n fireauth.args.or(\n fireauth.args.object('opt_actionCodeSettings', true),\n fireauth.args.null(null, true),\n 'opt_actionCodeSettings',\n true)\n ]\n }\n });\n\n// Ensure internal grecaptcha mock API do not get obfuscated.\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.GRecaptchaMockFactory.prototype, {\n execute: {\n name: 'execute'\n },\n render: {\n name: 'render'\n },\n reset: {\n name: 'reset'\n },\n getResponse: {\n name: 'getResponse'\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.grecaptcha.prototype, {\n execute: {\n name: 'execute'\n },\n render: {\n name: 'render'\n },\n reset: {\n name: 'reset'\n },\n getResponse: {\n name: 'getResponse'\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n goog.Promise.prototype, {\n thenAlways: {\n name: 'finally'\n },\n thenCatch: {\n name: 'catch'\n },\n then: {\n name: 'then'\n }\n });\n\nfireauth.exportlib.exportPrototypeProperties(\n fireauth.AuthSettings.prototype, {\n 'appVerificationDisabled': {\n name: 'appVerificationDisabledForTesting',\n arg: fireauth.args.bool('appVerificationDisabledForTesting')\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.ConfirmationResult.prototype, {\n confirm: {\n name: 'confirm',\n args: [\n fireauth.args.string('verificationCode')\n ]\n }\n });\n\nfireauth.exportlib.exportFunction(\n fireauth.AuthCredential, 'fromJSON',\n fireauth.AuthCredential.fromPlainObject, [\n fireauth.args.or(fireauth.args.string(), fireauth.args.object(), 'json')\n ]);\n\nfireauth.exportlib.exportFunction(\n fireauth.EmailAuthProvider, 'credential',\n fireauth.EmailAuthProvider.credential, [\n fireauth.args.string('email'),\n fireauth.args.string('password')\n ]);\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.EmailAuthCredential.prototype, {\n toPlainObject: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.FacebookAuthProvider.prototype, {\n addScope: {\n name: 'addScope',\n args: [fireauth.args.string('scope')]\n },\n setCustomParameters: {\n name: 'setCustomParameters',\n args: [fireauth.args.object('customOAuthParameters')]\n }\n });\nfireauth.exportlib.exportFunction(\n fireauth.FacebookAuthProvider, 'credential',\n fireauth.FacebookAuthProvider.credential, [\n fireauth.args.or(fireauth.args.string(), fireauth.args.object(),\n 'token')\n ]);\nfireauth.exportlib.exportFunction(\n fireauth.EmailAuthProvider, 'credentialWithLink',\n fireauth.EmailAuthProvider.credentialWithLink, [\n fireauth.args.string('email'),\n fireauth.args.string('emailLink')\n ]);\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.GithubAuthProvider.prototype, {\n addScope: {\n name: 'addScope',\n args: [fireauth.args.string('scope')]\n },\n setCustomParameters: {\n name: 'setCustomParameters',\n args: [fireauth.args.object('customOAuthParameters')]\n }\n });\nfireauth.exportlib.exportFunction(\n fireauth.GithubAuthProvider, 'credential',\n fireauth.GithubAuthProvider.credential, [\n fireauth.args.or(fireauth.args.string(), fireauth.args.object(),\n 'token')\n ]);\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.GoogleAuthProvider.prototype, {\n addScope: {\n name: 'addScope',\n args: [fireauth.args.string('scope')]\n },\n setCustomParameters: {\n name: 'setCustomParameters',\n args: [fireauth.args.object('customOAuthParameters')]\n }\n });\nfireauth.exportlib.exportFunction(\n fireauth.GoogleAuthProvider, 'credential',\n fireauth.GoogleAuthProvider.credential, [\n fireauth.args.or(fireauth.args.string(),\n fireauth.args.or(fireauth.args.object(), fireauth.args.null()),\n 'idToken'),\n fireauth.args.or(fireauth.args.string(), fireauth.args.null(),\n 'accessToken', true)\n ]);\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.TwitterAuthProvider.prototype, {\n setCustomParameters: {\n name: 'setCustomParameters',\n args: [fireauth.args.object('customOAuthParameters')]\n }\n });\nfireauth.exportlib.exportFunction(\n fireauth.TwitterAuthProvider, 'credential',\n fireauth.TwitterAuthProvider.credential, [\n fireauth.args.or(fireauth.args.string(), fireauth.args.object(),\n 'token'),\n fireauth.args.string('secret', true)\n ]);\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.OAuthProvider.prototype, {\n addScope: {\n name: 'addScope',\n args: [fireauth.args.string('scope')]\n },\n credential: {\n name: 'credential',\n args: [\n fireauth.args.or(\n fireauth.args.string(),\n fireauth.args.or(fireauth.args.object(), fireauth.args.null()),\n 'optionsOrIdToken'),\n fireauth.args.or(fireauth.args.string(), fireauth.args.null(),\n 'accessToken', true)\n ]\n },\n setCustomParameters: {\n name: 'setCustomParameters',\n args: [fireauth.args.object('customOAuthParameters')]\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.OAuthCredential.prototype, {\n toPlainObject: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.SAMLAuthCredential.prototype, {\n toPlainObject: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\n\nfireauth.exportlib.exportFunction(\n fireauth.PhoneAuthProvider, 'credential',\n fireauth.PhoneAuthProvider.credential, [\n fireauth.args.string('verificationId'),\n fireauth.args.string('verificationCode')\n ]);\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.PhoneAuthProvider.prototype, {\n verifyPhoneNumber: {\n name: 'verifyPhoneNumber',\n args: [\n fireauth.args.or(\n fireauth.args.string(),\n fireauth.args.phoneInfoOptions(),\n 'phoneInfoOptions'),\n fireauth.args.applicationVerifier()\n ]\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.PhoneAuthCredential.prototype, {\n toPlainObject: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.AuthError.prototype, {\n toJSON: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.AuthErrorWithCredential.prototype, {\n toJSON: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.InvalidOriginError.prototype, {\n toJSON: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.MultiFactorError.prototype, {\n toJSON: {\n name: 'toJSON',\n // This shouldn't take an argument but a blank string is being passed\n // on JSON.stringify and causing this to fail with an argument error.\n // So allow an optional string.\n args: [fireauth.args.string(null, true)]\n }\n });\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.MultiFactorResolver.prototype, {\n resolveSignIn: {\n name: 'resolveSignIn',\n args: [fireauth.args.multiFactorAssertion()]\n }\n });\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.MultiFactorUser.prototype, {\n getSession: {\n name: 'getSession',\n args: []\n },\n enroll: {\n name: 'enroll',\n args: [\n fireauth.args.multiFactorAssertion(),\n fireauth.args.string('displayName', true)\n ]\n },\n unenroll: {\n name: 'unenroll',\n args: [\n fireauth.args.or(\n fireauth.args.multiFactorInfo(),\n fireauth.args.string(),\n 'multiFactorInfoIdentifier')\n ]\n }\n });\n\nfireauth.exportlib.exportPrototypeMethods(\n fireauth.RecaptchaVerifier.prototype, {\n clear: {\n name: 'clear',\n args: []\n },\n render: {\n name: 'render',\n args: []\n },\n verify: {\n name: 'verify',\n args: []\n }\n });\n\nfireauth.exportlib.exportFunction(\n fireauth.ActionCodeURL, 'parseLink',\n fireauth.ActionCodeURL.parseLink, [fireauth.args.string('link')]);\n\nfireauth.exportlib.exportFunction(\n fireauth.PhoneMultiFactorGenerator, 'assertion',\n fireauth.PhoneMultiFactorGenerator.assertion,\n [fireauth.args.authCredential(fireauth.idp.ProviderId.PHONE)]);\n\n\n(function() {\n if (typeof firebase === 'undefined' || !firebase.INTERNAL ||\n !firebase.INTERNAL.registerComponent) {\n throw new Error('Cannot find the firebase namespace; be sure to include ' +\n 'firebase-app.js before this library.');\n } else {\n var namespace = {\n // Exports firebase.auth.ActionCodeInfo.Operation.\n 'ActionCodeInfo': {\n 'Operation': {\n 'EMAIL_SIGNIN': fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN,\n 'PASSWORD_RESET': fireauth.ActionCodeInfo.Operation.PASSWORD_RESET,\n 'RECOVER_EMAIL': fireauth.ActionCodeInfo.Operation.RECOVER_EMAIL,\n 'REVERT_SECOND_FACTOR_ADDITION':\n fireauth.ActionCodeInfo.Operation.REVERT_SECOND_FACTOR_ADDITION,\n 'VERIFY_AND_CHANGE_EMAIL':\n fireauth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL,\n 'VERIFY_EMAIL': fireauth.ActionCodeInfo.Operation.VERIFY_EMAIL\n }\n },\n 'Auth': fireauth.Auth,\n 'AuthCredential': fireauth.AuthCredential,\n 'Error': fireauth.AuthError\n };\n fireauth.exportlib.exportFunction(namespace,\n 'EmailAuthProvider', fireauth.EmailAuthProvider, []);\n fireauth.exportlib.exportFunction(namespace,\n 'FacebookAuthProvider', fireauth.FacebookAuthProvider, []);\n fireauth.exportlib.exportFunction(namespace,\n 'GithubAuthProvider', fireauth.GithubAuthProvider, []);\n fireauth.exportlib.exportFunction(namespace,\n 'GoogleAuthProvider', fireauth.GoogleAuthProvider, []);\n fireauth.exportlib.exportFunction(namespace,\n 'TwitterAuthProvider', fireauth.TwitterAuthProvider, []);\n fireauth.exportlib.exportFunction(namespace,\n 'OAuthProvider', fireauth.OAuthProvider, [\n fireauth.args.string('providerId')\n ]);\n fireauth.exportlib.exportFunction(namespace,\n 'SAMLAuthProvider', fireauth.SAMLAuthProvider, [\n fireauth.args.string('providerId')\n ]);\n fireauth.exportlib.exportFunction(namespace,\n 'PhoneAuthProvider', fireauth.PhoneAuthProvider, [\n fireauth.args.firebaseAuth(true)\n ]);\n fireauth.exportlib.exportFunction(namespace,\n 'RecaptchaVerifier', fireauth.RecaptchaVerifier, [\n fireauth.args.or(\n fireauth.args.string(),\n fireauth.args.element(),\n 'recaptchaContainer'),\n fireauth.args.object('recaptchaParameters', true),\n fireauth.args.firebaseApp(true)\n ]);\n fireauth.exportlib.exportFunction(namespace,\n 'ActionCodeURL', fireauth.ActionCodeURL, []);\n fireauth.exportlib.exportFunction(namespace,\n 'PhoneMultiFactorGenerator', fireauth.PhoneMultiFactorGenerator, []);\n\n // Create auth components to register with firebase.\n // Provides Auth public APIs.\n const authComponent = { \n 'name': fireauth.exportlib.AUTH_TYPE,\n 'instanceFactory': function(container) {\n var app = container['getProvider']('app')['getImmediate']();\n return new fireauth.Auth(app);\n },\n 'multipleInstances': false,\n 'serviceProps': namespace,\n 'instantiationMode': 'LAZY',\n 'type': 'PUBLIC'\n };\n \n // Provides Auth internal APIs.\n const authInteropComponent = { \n 'name': 'auth-internal',\n 'instanceFactory': function(container) {\n var auth = container['getProvider'](fireauth.exportlib.AUTH_TYPE)['getImmediate']();\n return {\n 'getUid': goog.bind(auth.getUid, auth),\n 'getToken': goog.bind(auth.getIdTokenInternal, auth),\n 'addAuthTokenListener':\n goog.bind(auth.addAuthTokenListenerInternal, auth),\n 'removeAuthTokenListener':\n goog.bind(auth.removeAuthTokenListenerInternal, auth)\n };\n },\n 'multipleInstances': false,\n 'instantiationMode': 'LAZY',\n 'type': 'PRIVATE'\n };\n \n firebase.INTERNAL.registerComponent(authComponent);\n firebase.INTERNAL.registerComponent(authInteropComponent);\n firebase.registerVersion('@firebase/auth', AUTH_NPM_PACKAGE_VERSION);\n\n // Expose User as firebase.User.\n firebase.INTERNAL.extendNamespace({\n 'User': fireauth.AuthUser\n });\n }\n})();","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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: unknown | 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): unknown {\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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]: unknown } = {};\n\n set(key: string, value: unknown | null) {\n if (value == null) {\n delete this.cache_[key];\n } else {\n this.cache_[key] = value;\n }\n }\n\n get(key: string): unknown {\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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: Window;\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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';\nimport {\n assert,\n base64,\n Sha1,\n stringToByteArray,\n stringify,\n isNodeSdk\n} from '@firebase/util';\nimport { SessionStorage } from '../storage/storage';\nimport { Logger, LogLevel } from '@firebase/logger';\n\ndeclare const window: Window;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const Windows: any;\n\nconst logClient = new Logger('@firebase/database');\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 * 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 {...*} varArgs\n * @return {string}\n * @private\n */\nconst buildLogMessage_ = function(...varArgs: unknown[]): string {\n let message = '';\n for (let i = 0; i < varArgs.length; i++) {\n const arg = varArgs[i];\n if (\n Array.isArray(arg) ||\n (arg &&\n typeof arg === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (arg as any).length === 'number')\n ) {\n message += buildLogMessage_.apply(null, arg);\n } else if (typeof arg === 'object') {\n message += stringify(arg);\n } else {\n message += arg;\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 logClient.logLevel = LogLevel.VERBOSE;\n logger = logClient.log.bind(logClient);\n if (persistent) {\n SessionStorage.set('logging_enabled', true);\n }\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)} varArgs\n */\nexport const log = function(...varArgs: unknown[]) {\n if (firstLog_ === true) {\n firstLog_ = false;\n if (logger === null && SessionStorage.get('logging_enabled') === true) {\n enableLogging(true);\n }\n }\n\n if (logger) {\n const message = buildLogMessage_.apply(null, varArgs);\n logger(message);\n }\n};\n\n/**\n * @param {!string} prefix\n * @return {function(...[*])}\n */\nexport const logWrapper = function(\n prefix: string\n): (...varArgs: unknown[]) => void {\n return function(...varArgs: unknown[]) {\n log(prefix, ...varArgs);\n };\n};\n\n/**\n * @param {...string} varArgs\n */\nexport const error = function(...varArgs: string[]) {\n const message = 'FIREBASE INTERNAL ERROR: ' + buildLogMessage_(...varArgs);\n logClient.error(message);\n};\n\n/**\n * @param {...string} varArgs\n */\nexport const fatal = function(...varArgs: string[]) {\n const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;\n logClient.error(message);\n throw new Error(message);\n};\n\n/**\n * @param {...*} varArgs\n */\nexport const warn = function(...varArgs: unknown[]) {\n const message = 'FIREBASE WARNING: ' + buildLogMessage_(...varArgs);\n logClient.warn(message);\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: unknown): 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 const 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((document as any).attachEvent) {\n // IE.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (document as any).attachEvent('onreadystatechange', () => {\n if (document.readyState === 'complete') {\n wrappedFn();\n }\n });\n // fallback to onload.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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]: unknown }\n): unknown {\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: unknown): string {\n if (typeof obj !== 'object' || obj === null) {\n return stringify(obj);\n }\n\n const keys = [];\n // eslint-disable-next-line guard-for-in\n for (const 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) {\n key += ',';\n }\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.<string>} 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 obj The object or array to iterate over\n * @param fn The function to apply\n */\nexport function each(obj: object, fn: (k: string, v: unknown) => void) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n fn(key, obj[key]);\n }\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: unknown) => 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 const bias = (1 << (ebits - 1)) - 1;\n let s, e, f, ln, i;\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 const 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 const 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) {\n hexByte = '0' + hexByte;\n }\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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('^-?(0*)\\\\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(() => {\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 {...*} varArgs Arbitrary args to be passed to opt_onComplete\n */\nexport const callUserCallback = function(\n callback?: Function | null,\n ...varArgs: unknown[]\n) {\n if (typeof callback === 'function') {\n exceptionGuard(() => {\n callback(...varArgs);\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: () => unknown\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (typeof timeout === 'object' && (timeout as any)['unref']) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (timeout as any)['unref']();\n }\n return timeout;\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\n/**\n * An immutable object representing a parsed path. It's immutable so that you\n * can pass them around to other functions without worrying about them changing\n * it.\n */\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.<string>} 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) {\n return null;\n }\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\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] !== '') {\n pathString += '/' + this.pieces_[i];\n }\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\n return pathString || '/';\n }\n\n /**\n * Shallow copy of the parts of the path.\n *\n * @param {number=} begin\n * @return {!Array<string>}\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) {\n return null;\n }\n\n const pieces = [];\n for (let i = this.pieceNum_; i < this.pieces_.length - 1; i++) {\n pieces.push(this.pieces_[i]);\n }\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\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) {\n pieces.push(childPieces[i]);\n }\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) {\n return cmp;\n }\n }\n if (leftKeys.length === rightKeys.length) {\n return 0;\n }\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<string>} */\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<string>} */\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\nimport { PersistentStorage } from './storage/storage';\nimport { LONG_POLLING, WEBSOCKET } from '../realtime/Constants';\nimport { each } from './util/util';\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 public includeNamespaceInQueryParams: boolean = false\n ) {\n this.host = host.toLowerCase();\n this.domain = this.host.substr(this.host.indexOf('.') + 1);\n this.internalHost =\n (PersistentStorage.get('host:' + host) as string) || this.host;\n }\n\n needsQueryParam(): boolean {\n return (\n this.host !== this.internalHost ||\n this.isCustomHost() ||\n this.includeNamespaceInQueryParams\n );\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 each(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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, warn, 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 * @param {!string} queryString\n * @return {!{[key:string]:string}} key value hash\n */\nfunction decodeQuery(queryString: string): { [key: string]: string } {\n const results = {};\n if (queryString.charAt(0) === '?') {\n queryString = queryString.substring(1);\n }\n for (const segment of queryString.split('&')) {\n if (segment.length === 0) {\n continue;\n }\n const kv = segment.split('=');\n if (kv.length === 2) {\n results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);\n } else {\n warn(`Invalid query segment '${segment}' in query '${queryString}'`);\n }\n }\n return results;\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 = parseDatabaseURL(dataURL),\n namespace = parsedUrl.namespace;\n\n if (parsedUrl.domain === 'firebase') {\n fatal(\n parsedUrl.host +\n ' is no longer supported. ' +\n 'Please use <YOUR FIREBASE>.firebaseio.com instead'\n );\n }\n\n // Catch common error of uninitialized namespace value.\n if (\n (!namespace || namespace === 'undefined') &&\n parsedUrl.domain !== 'localhost'\n ) {\n fatal(\n 'Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.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 /*persistenceKey=*/ '',\n /*includeNamespaceInQueryParams=*/ namespace !== parsedUrl.subdomain\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, namespace: string}}\n */\nexport const parseDatabaseURL = 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 namespace: string;\n} {\n // Default to empty strings in the event of a malformed string.\n let host = '',\n domain = '',\n subdomain = '',\n pathString = '',\n namespace = '';\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, path, and query string.\n let slashInd = dataURL.indexOf('/');\n if (slashInd === -1) {\n slashInd = dataURL.length;\n }\n let questionMarkInd = dataURL.indexOf('?');\n if (questionMarkInd === -1) {\n questionMarkInd = dataURL.length;\n }\n host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));\n if (slashInd < questionMarkInd) {\n // For pathString, questionMarkInd will always come after slashInd\n pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));\n }\n const queryParams = decodeQuery(\n dataURL.substring(Math.min(dataURL.length, questionMarkInd))\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 } else {\n colonInd = dataURL.length;\n }\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 // We interpret the subdomain of a 3 component URL as the namespace name.\n namespace = subdomain;\n } else if (parts.length === 2) {\n domain = parts[0];\n } else if (parts[0].slice(0, colonInd).toLowerCase() === 'localhost') {\n domain = 'localhost';\n }\n // Always treat the value of the `ns` as the namespace name if it is present.\n if ('ns' in queryParams) {\n namespace = queryParams['ns'];\n }\n }\n\n return {\n host,\n port,\n domain,\n subdomain,\n secure,\n scheme,\n pathString,\n namespace\n };\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 {\n contains,\n safeGet,\n errorPrefix as errorPrefixFxn,\n stringLength\n} from '@firebase/util';\nimport { isInvalidJSONNumber, each } from './util';\n\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: unknown): 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: unknown): boolean {\n return (\n priority === null ||\n typeof priority === 'string' ||\n (typeof priority === 'number' && !isInvalidJSONNumber(priority)) ||\n (priority &&\n typeof priority === 'object' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n contains(priority as any, '.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: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\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: unknown,\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 let hasActualChild = false;\n each(data, (key: string, value: unknown) => {\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<!Path>} 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: unknown,\n path: Path,\n optional: boolean\n) {\n if (optional && data === undefined) {\n return;\n }\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 each(data, (key: string, value: unknown) => {\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: unknown,\n optional: boolean\n) {\n if (optional && priority === undefined) {\n return;\n }\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 }\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};\n\nexport const validateEventType = function(\n fnName: string,\n argumentNumber: number,\n eventType: string,\n optional: boolean\n) {\n if (optional && eventType === undefined) {\n return;\n }\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) {\n return;\n }\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};\n\nexport const validatePathString = function(\n fnName: string,\n argumentNumber: number,\n pathString: string,\n optional: boolean\n) {\n if (optional && pathString === undefined) {\n return;\n }\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};\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 parsedUrl.repoInfo.host.split(':')[0] !== 'localhost') ||\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: unknown,\n optional: boolean\n) {\n if (optional && cred === undefined) {\n return;\n }\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};\n\nexport const validateBoolean = function(\n fnName: string,\n argumentNumber: number,\n bool: unknown,\n optional: boolean\n) {\n if (optional && bool === undefined) {\n return;\n }\n if (typeof bool !== 'boolean') {\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) + 'must be a boolean.'\n );\n }\n};\n\nexport const validateString = function(\n fnName: string,\n argumentNumber: number,\n string: unknown,\n optional: boolean\n) {\n if (optional && string === undefined) {\n return;\n }\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: unknown,\n optional: boolean\n) {\n if (optional && obj === undefined) {\n return;\n }\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: unknown,\n key: string,\n optional: boolean,\n optType?: string\n) {\n const objectContainsKey =\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n obj && typeof obj === 'object' && contains(obj as any, 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 (optType) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const val = safeGet(obj as any, key);\n if (\n (optType === 'number' && !(typeof val === 'number')) ||\n (optType === 'string' && !(typeof val === 'string')) ||\n (optType === 'boolean' && !(typeof val === 'boolean')) ||\n (optType === 'function' && !(typeof val === 'function')) ||\n (optType === '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 optType +\n '\")'\n );\n } else {\n throw new Error(\n errorPrefixFxn(fnName, argumentNumber, optional) +\n 'must contain the key \"' +\n key +\n '\" with type \"' +\n optType +\n '\"'\n );\n }\n }\n }\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, Deferred } from '@firebase/util';\nimport {\n validateWritablePath,\n validateFirebaseDataArg,\n validatePriority,\n validateFirebaseMergeDataArg\n} from '../core/util/validation';\nimport { warn } from '../core/util/util';\n\nimport { Repo } from '../core/Repo';\nimport { Path } from '../core/util/Path';\nimport { Indexable } from '../core/util/misc';\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<void> {\n validateArgCount('OnDisconnect.cancel', 0, 1, arguments.length);\n validateCallback('OnDisconnect.cancel', 1, onComplete, true);\n const deferred = new Deferred<void>();\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<void> {\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<void>();\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: unknown, onComplete?: (a: Error | null) => void): Promise<void> {\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<void>();\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: unknown,\n priority: number | string | null,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\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<void>();\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: Indexable,\n onComplete?: (a: Error | null) => void\n ): Promise<void> {\n validateArgCount('OnDisconnect.update', 1, 2, arguments.length);\n validateWritablePath('OnDisconnect.update', this.path_);\n if (Array.isArray(objectToMerge)) {\n const newObjectToMerge: { [k: string]: unknown } = {};\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<void>();\n this.repo_.onDisconnectUpdate(\n this.path_,\n objectToMerge,\n deferred.wrapCallback(onComplete)\n );\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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): unknown;\n\n /**\n * @param exportFormat True for export format (also wire protocol format).\n * @return Value of this node as JSON.\n */\n val(exportFormat?: boolean): unknown;\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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<NamedNode> {\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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: unknown, name: string): NamedNode;\n\n /**\n * @return {!string} String representation for inclusion in a query spec\n */\n abstract toString(): string;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, contains } from '@firebase/util';\nimport { doubleToIEEE754String } from '../util/util';\n\nimport { Node } from './Node';\nimport { Indexable } from '../util/misc';\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 {\n return 'string:' + priority;\n }\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 as Indexable, '.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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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';\nimport { Indexable } from '../util/misc';\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.<!string>}\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 | Indexable,\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.updateImmediateChild(\n childName,\n 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): boolean {\n return false;\n }\n\n /**\n * @inheritDoc\n */\n val(exportFormat?: boolean): {} {\n if (exportFormat && !this.getPriority().isEmpty()) {\n return {\n '.value': this.getValue(),\n '.priority': this.getPriority().val()\n };\n } else {\n return this.getValue();\n }\n }\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\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(): Indexable | 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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: unknown) => Node;\nlet MAX_NODE: Node;\n\nexport function setNodeFromJSON(val: (a: unknown) => 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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: unknown, 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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<K> = (key1: K, key2: K) => number;\n\n/**\n * An iterator over an LLRBNode.\n */\nexport class SortedMapIterator<K, V, T> {\n /** @private\n * @type {Array.<!LLRBNode>}\n */\n private nodeStack_: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>> = [];\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<K, V> | LLRBEmptyNode<K, V>,\n startKey: K | null,\n comparator: Comparator<K>,\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<K, V>;\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse_) {\n cmp *= -1;\n }\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) {\n return null;\n }\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 {\n result = ({ key: node.key, value: node.value } as unknown) as T;\n }\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) {\n return null;\n }\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 unknown) as T;\n }\n }\n}\n\n/**\n * Represents a node in a Left-leaning Red-Black tree.\n */\nexport class LLRBNode<K, V> {\n color: boolean;\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\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<K, V> | LLRBEmptyNode<K, V> | null,\n right?: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left =\n left != null ? left : (SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>);\n this.right =\n right != null ? right : (SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>);\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<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBNode<K, V> {\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) => unknown): 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<K, V> {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode<K, V>).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<K>): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n const 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<K, V> | LLRBEmptyNode<K, V> {\n if (this.left.isEmpty()) {\n return SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>;\n }\n let n: LLRBNode<K, V> = this;\n if (!n.left.isRed_() && !n.left.left.isRed_()) {\n n = n.moveRedLeft_();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).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<K>\n ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\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 = n.rotateRight_();\n }\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<K, V>;\n } else {\n smallest = (n.right as LLRBNode<K, V>).min_();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode<K, V>).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<K, V> {\n let n: LLRBNode<K, V> = this;\n if (n.right.isRed_() && !n.left.isRed_()) {\n n = n.rotateLeft_();\n }\n if (n.left.isRed_() && n.left.left.isRed_()) {\n n = n.rotateRight_();\n }\n if (n.left.isRed_() && n.right.isRed_()) {\n n = n.colorFlip_();\n }\n return n;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after moveRedLeft.\n */\n private moveRedLeft_(): LLRBNode<K, V> {\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<K, V>).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<K, V> {\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<K, V> {\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<K, V>;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after rotateRight.\n */\n private rotateRight_(): LLRBNode<K, V> {\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<K, V>;\n }\n\n /**\n * @private\n * @return {!LLRBNode} New tree, after colorFlip.\n */\n private colorFlip_(): LLRBNode<K, V> {\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 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 const 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<K, V> {\n key: K;\n value: V;\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\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<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBEmptyNode<K, V> {\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<K>): LLRBNode<K, V> {\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<K>): LLRBEmptyNode<K, V> {\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) => unknown): 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<K, V> {\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<K>,\n private root_:\n | LLRBNode<K, V>\n | LLRBEmptyNode<K, V> = SortedMap.EMPTY_NODE as LLRBEmptyNode<K, V>\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.<K, V>} New map, with item added.\n */\n insert(key: K, value: V): SortedMap<K, V> {\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.<K, V>} New map, with item removed.\n */\n remove(key: K): SortedMap<K, V> {\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()) {\n node = node.right;\n }\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) => unknown): 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.<K, V, T>} The iterator.\n */\n getIterator<T>(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getIteratorFrom<T>(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n false,\n resultGenerator\n );\n }\n\n getReverseIteratorFrom<T>(\n key: K,\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n key,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n\n getReverseIterator<T>(\n resultGenerator?: (k: K, v: V) => T\n ): SortedMapIterator<K, V, T> {\n return new SortedMapIterator(\n this.root_,\n null,\n this.comparator_,\n true,\n resultGenerator\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, SortedMap } from '../util/SortedMap';\n\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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.<!NamedNode>} 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.<K, V>}\n */\nexport const buildChildSet = function<K, V>(\n childList: NamedNode[],\n cmp: (a: NamedNode, b: NamedNode) => number,\n keyFn?: (a: NamedNode) => K,\n mapSortFn?: (a: K, b: K) => number\n): SortedMap<K, V> {\n childList.sort(cmp);\n\n const buildBalancedTree = function(\n low: number,\n high: number\n ): LLRBNode<K, V> | 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 unknown) as K);\n return new LLRBNode(\n key,\n (namedNode.node as unknown) as V,\n LLRBNode.BLACK,\n null,\n null\n );\n } else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 unknown) as K);\n return new LLRBNode(\n key,\n (namedNode.node as unknown) as V,\n LLRBNode.BLACK,\n left,\n right\n );\n }\n };\n\n const buildFrom12Array = function(base12: Base12Num): LLRBNode<K, V> {\n let node: LLRBNode<K, V> = 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 unknown) as K);\n attachPennant(\n new LLRBNode(\n key,\n (namedNode.node as unknown) as V,\n color,\n null,\n childTree\n )\n );\n };\n\n const attachPennant = function(pennant: LLRBNode<K, V>) {\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new SortedMap<K, V>(mapSortFn || (cmp as any), root);\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, contains, map, safeGet } from '@firebase/util';\nimport { buildChildSet } from './childSet';\n\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\nexport class IndexMap {\n /**\n * The default IndexMap for nodes without a priority\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<NamedNode, Node> | /*FallbackType*/ object;\n },\n private indexSet_: { [k: string]: Index }\n ) {}\n\n get(indexKey: string): SortedMap<NamedNode, Node> | null {\n const sortedMap = safeGet(this.indexes_, indexKey);\n if (!sortedMap) {\n throw new Error('No index defined for ' + indexKey);\n }\n\n if (sortedMap instanceof SortedMap) {\n return sortedMap;\n } else {\n // The index exists, but it falls back to just name comparison. Return null so that the calling code uses the\n // regular child map\n return null;\n }\n }\n\n hasIndex(indexDefinition: Index): boolean {\n return contains(this.indexSet_, indexDefinition.toString());\n }\n\n addIndex(\n indexDefinition: Index,\n existingChildren: SortedMap<string, Node>\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 = { ...this.indexSet_ };\n newIndexSet[indexName] = indexDefinition;\n const newIndexes = { ...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 */\n addToIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap<string, Node>\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap<NamedNode, Node>, 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 */\n removeFromIndexes(\n namedNode: NamedNode,\n existingChildren: SortedMap<string, Node>\n ): IndexMap {\n const newIndexes = map(\n this.indexes_,\n (indexedChildren: SortedMap<NamedNode, Node>) => {\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 );\n return new IndexMap(newIndexes, this.indexSet_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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<string, Node>,\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<string, Node>(NAME_COMPARATOR),\n null,\n IndexMap.Default\n ))\n );\n }\n\n /**\n *\n * @param {!SortedMap.<string, !Node>} 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<string, Node>,\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) {\n return this;\n }\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;\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 const newPriority = newChildren.isEmpty()\n ? EMPTY_NODE\n : 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()) {\n return null;\n }\n\n const obj: { [k: string]: unknown } = {};\n let numKeys = 0,\n maxKey = 0,\n allIntegerKeys = true;\n this.forEachChild(PRIORITY_INDEX, (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: unknown[] = [];\n // eslint-disable-next-line guard-for-in\n for (const key in obj) {\n array[(key as unknown) as number] = obj[key];\n }\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\n this.forEachChild(PRIORITY_INDEX, (key, childNode) => {\n const childHash = childNode.hash();\n if (childHash !== '') {\n toHash += ':' + key + ':' + childHash;\n }\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(\n index: Index,\n action: (key: string, node: Node) => boolean | void\n ): boolean {\n const idx = this.resolveIndex_(index);\n if (idx) {\n return idx.inorderTraversal(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<string | NamedNode, Node, NamedNode> {\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<string | NamedNode, Node, NamedNode> {\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<string | NamedNode, Node, NamedNode> {\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<string | NamedNode, Node, NamedNode> {\n const idx = this.resolveIndex_(indexDefinition);\n if (idx) {\n return idx.getReverseIteratorFrom(endPost, 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.<NamedNode, Node>}\n */\n private resolveIndex_(\n indexDefinition: Index\n ): SortedMap<NamedNode, Node> | 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<string, Node>(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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { contains, assert } from '@firebase/util';\n\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';\nimport { each } from '../util/util';\nimport { Indexable } from '../util/misc';\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: unknown | null,\n priority: unknown = 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 | Indexable;\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 = json;\n each(hinzeJsonObj, (key, child) => {\n if (key.substring(0, 1) !== '.') {\n // Ignore metadata nodes\n const childNode = nodeFromJSON(child);\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<string, Node>;\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 each(json, (key: string, childData: unknown) => {\n if (contains(json as object, 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\n return node.updatePriority(nodeFromJSON(priority));\n }\n}\n\nsetNodeFromJSON(nodeFromJSON);\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (NamedNode as any).MIN;\n }\n\n /**\n * @inheritDoc\n */\n maxPost(): NamedNode {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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(): unknown {\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(): unknown {\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(): unknown {\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) => boolean | void): boolean {\n validateArgCount('DataSnapshot.forEach', 1, 1, arguments.length);\n validateCallback('DataSnapshot.forEach', 1, action, false);\n\n if (this.node_.isLeafNode()) {\n return false;\n }\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()) {\n return false;\n } else {\n return !this.node_.isEmpty();\n }\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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\nexport type EventType =\n | 'value'\n | ' child_added'\n | ' child_changed'\n | ' child_moved'\n | ' child_removed';\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: EventType,\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, EventType } from './Event';\nimport { contains, assert } from '@firebase/util';\n\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_: {} | 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.<string, function(!DataSnapshot, ?string=)>} 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_?: {}\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 EventType,\n this,\n new DataSnapshot(change.snapshotNode, ref, index),\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 otherKeys = Object.keys(other.callbacks_);\n const thisKeys = Object.keys(this.callbacks_);\n const otherCount = otherKeys.length;\n const thisCount = thisKeys.length;\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 = otherKeys[0];\n const thisKey = thisKeys[0];\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 thisKeys.every(\n eventType =>\n other.callbacks_[eventType] === this.callbacks_[eventType]\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 assert,\n errorPrefix,\n validateArgCount,\n validateCallback,\n validateContextObject,\n Deferred\n} from '@firebase/util';\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';\n\nimport {\n ValueEventRegistration,\n ChildEventRegistration,\n EventRegistration\n} from '../core/view/EventRegistration';\n\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 | null): unknown;\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) => unknown) | object | null,\n context?: object | null\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.<string, !function(!DataSnapshot, ?string)>} callbacks\n * @param {?function(Error)} cancelCallback\n * @param {?Object} context\n * @protected\n */\n onChildEvent(\n callbacks: { [k: string]: SnapshotCallback },\n cancelCallback: ((a: Error) => unknown) | 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(\n eventType?: string,\n callback?: SnapshotCallback,\n context?: object | null\n ): void {\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 failureCallbackOrContext\n * @param context\n * @return {!firebase.Promise}\n */\n once(\n eventType: string,\n userCallback?: SnapshotCallback,\n failureCallbackOrContext?: ((a: Error) => void) | object | null,\n context?: object | null\n ): Promise<DataSnapshot> {\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 failureCallbackOrContext,\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<DataSnapshot>();\n\n // A dummy error handler in case a user wasn't expecting promises\n deferred.promise.catch(() => {});\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) {\n ret.cancel.bind(ret.context)(err);\n }\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 | null,\n context?: object | null\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 as (a: Error) => void;\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Node } from './snap/Node';\n\n/**\n * Helper class to store a sparse set of snapshots.\n */\nexport class SparseSnapshotTree {\n private value: Node | null = null;\n\n private readonly children: Map<string, SparseSnapshotTree> = new Map();\n\n /**\n * Gets the node stored at the given path if one exists.\n *\n * @param path Path to look up snapshot for.\n * @return 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.size > 0) {\n const childKey = path.getFront();\n path = path.popFront();\n if (this.children.has(childKey)) {\n const childTree = this.children.get(childKey);\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 to look up snapshot for.\n * @param data The new data, or null.\n */\n remember(path: Path, data: Node) {\n if (path.isEmpty()) {\n this.value = data;\n this.children.clear();\n } else if (this.value !== null) {\n this.value = this.value.updateChild(path, data);\n } else {\n const childKey = path.getFront();\n if (!this.children.has(childKey)) {\n this.children.set(childKey, new SparseSnapshotTree());\n }\n\n const child = this.children.get(childKey);\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 to look up snapshot for.\n * @return 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.clear();\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, (key, tree) => {\n self.remember(new Path(key), tree);\n });\n\n return this.forget(path);\n }\n } else if (this.children.size > 0) {\n const childKey = path.getFront();\n path = path.popFront();\n if (this.children.has(childKey)) {\n const safeToRemove = this.children.get(childKey).forget(path);\n if (safeToRemove) {\n this.children.delete(childKey);\n }\n }\n\n return this.children.size === 0;\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 prefixPath Path to look up node for.\n * @param func The function to invoke for each tree.\n */\n forEachTree(prefixPath: Path, func: (a: Path, b: Node) => unknown) {\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 func The function to invoke for each child.\n */\n forEachChild(func: (a: string, b: SparseSnapshotTree) => void) {\n this.children.forEach((tree, key) => {\n func(key, tree);\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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';\nimport { Indexable } from './misc';\n\n/**\n * Generate placeholders for deferred values.\n * @param {?Object} values\n * @return {!Object}\n */\nexport const generateWithValues = function(\n values: {\n [k: string]: unknown;\n } | null\n): { [k: string]: unknown } {\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n value: { [k: string]: any } | string | number | boolean,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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(''), (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 | Indexable\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, (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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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<!boolean>} 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<boolean>,\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, each } from './util';\n\nlet emptyChildrenSingleton: SortedMap<string, ImmutableTree<null>>;\n\n/**\n * Singleton empty children collection.\n *\n * @const\n * @type {!SortedMap.<string, !ImmutableTree.<?>>}\n */\nconst EmptyChildren = (): SortedMap<string, ImmutableTree<null>> => {\n if (!emptyChildrenSingleton) {\n emptyChildrenSingleton = new SortedMap<string, ImmutableTree<null>>(\n stringCompare\n );\n }\n return emptyChildrenSingleton;\n};\n\n/**\n * A tree with immutable elements.\n */\nexport class ImmutableTree<T> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static Empty = new ImmutableTree<any>(null);\n\n /**\n * @template T\n * @param {!Object.<string, !T>} obj\n * @return {!ImmutableTree.<!T>}\n */\n static fromObject<T>(obj: { [k: string]: T }): ImmutableTree<T> {\n let tree: ImmutableTree<T> = ImmutableTree.Empty;\n each(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.<string, !ImmutableTree.<T>>=} children\n */\n constructor(\n public readonly value: T | null,\n public readonly children: SortedMap<\n string,\n ImmutableTree<T>\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.<T>} The subtree at the given path\n */\n subtree(relativePath: Path): ImmutableTree<T> {\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.<T>} Resulting tree.\n */\n set(relativePath: Path, toSet: T | null): ImmutableTree<T> {\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.<T>} Resulting tree.\n */\n remove(relativePath: Path): ImmutableTree<T> {\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<T>): ImmutableTree<T> {\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.<string, V>):V} fn\n * @return {V}\n */\n fold<V>(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.<string, V>):V} fn\n * @return {V}\n * @private\n */\n private fold_<V>(\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(\n (childKey: string, childTree: ImmutableTree<T>) => {\n accum[childKey] = childTree.fold_(pathSoFar.child(childKey), fn);\n }\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<V>(path: Path, f: (path: Path, value: T) => V | null): V | null {\n return this.findOnPath_(path, Path.Empty, f);\n }\n\n private findOnPath_<V>(\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.<T>}\n */\n foreachOnPath(\n path: Path,\n f: (path: Path, value: T) => void\n ): ImmutableTree<T> {\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<T> {\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((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<T>) => {\n if (childTree.value) {\n f(childName, childTree.value);\n }\n }\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\nimport { ImmutableTree } from '../util/ImmutableTree';\nimport { Node } from '../snap/Node';\n\n/**\n * @param {!OperationSource} source\n * @param {!Path} path\n * @param {!ImmutableTree.<!Node>} 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<Node>\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 | null\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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, (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, (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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Change } from './Change';\nimport { assert, assertionError } from '@firebase/util';\n\nexport class ChildChangeAccumulator {\n private readonly changeMap: Map<string, Change> = new Map();\n\n trackChildChange(change: Change) {\n const type = change.type;\n const childKey = 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 = this.changeMap.get(childKey);\n if (oldChange) {\n const oldType = oldChange.type;\n if (type === Change.CHILD_ADDED && oldType === Change.CHILD_REMOVED) {\n this.changeMap.set(\n childKey,\n Change.childChangedChange(\n childKey,\n change.snapshotNode,\n oldChange.snapshotNode\n )\n );\n } else if (\n type === Change.CHILD_REMOVED &&\n oldType === Change.CHILD_ADDED\n ) {\n this.changeMap.delete(childKey);\n } else if (\n type === Change.CHILD_REMOVED &&\n oldType === Change.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n Change.childRemovedChange(childKey, oldChange.oldSnap)\n );\n } else if (\n type === Change.CHILD_CHANGED &&\n oldType === Change.CHILD_ADDED\n ) {\n this.changeMap.set(\n childKey,\n Change.childAddedChange(childKey, change.snapshotNode)\n );\n } else if (\n type === Change.CHILD_CHANGED &&\n oldType === Change.CHILD_CHANGED\n ) {\n this.changeMap.set(\n childKey,\n Change.childChangedChange(\n childKey,\n change.snapshotNode,\n oldChange.oldSnap\n )\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.set(childKey, change);\n }\n }\n\n getChanges(): Change[] {\n return Array.from(this.changeMap.values());\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 */\n// eslint-disable-next-line @typescript-eslint/class-name-casing\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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.<!Change>} 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\n .getEventCache()\n .getNode()\n .isIndexed(this.filter_.getIndex()),\n 'Event snap not indexed'\n );\n assert(\n viewCache\n .getServerCache()\n .getNode()\n .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.<!Change>} 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\n .getNode()\n .getPriority()\n .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.<!Node>} 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<Node>,\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.<!Node>} merge\n * @return {!Node}\n * @private\n */\n private applyMerge_(node: Node, merge: ImmutableTree<Node>): Node {\n merge.foreach((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.<!Node>} 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<Node>,\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\n .getServerCache()\n .getNode()\n .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<!boolean>} 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<boolean>,\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, (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((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 (\n viewCache\n .getEventCache()\n .getNode()\n .hasChild(childKey)\n ) {\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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.<!Change>} changes\n * @param {!Node} eventCache\n * @param {!Array.<!EventRegistration>} eventRegistrations\n * @return {!Array.<!Event>}\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.<!Event>} events\n * @param {!string} eventType\n * @param {!Array.<!Change>} changes\n * @param {!Array.<!EventRegistration>} 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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.<!Event>} 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(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.<!Event>}\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.<!Event>}\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, (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.<!Change>} changes\n * @param {!Node} eventCache\n * @param {EventRegistration=} eventRegistration\n * @return {!Array.<!Event>}\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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 private readonly views: Map<string, View> = new Map();\n\n isEmpty(): boolean {\n return this.views.size === 0;\n }\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 = this.views.get(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 for (const view of this.views.values()) {\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.<!Event>} 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 = this.views.get(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(\n /** @type {!Node} */ eventCache,\n eventCacheComplete,\n false\n ),\n new CacheNode(\n /** @type {!Node} */ serverCache,\n serverCacheComplete,\n false\n )\n );\n view = new View(query, viewCache);\n this.views.set(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.<!Query>, events:!Array.<!Event>}} 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 for (const [viewQueryId, view] of this.views.entries()) {\n cancelEvents = cancelEvents.concat(\n view.removeEventRegistration(eventRegistration, cancelError)\n );\n if (view.isEmpty()) {\n this.views.delete(viewQueryId);\n\n // We'll deal with complete views later.\n if (\n !view\n .getQuery()\n .getQueryParams()\n .loadsAllData()\n ) {\n removed.push(view.getQuery());\n }\n }\n }\n } else {\n // remove the callback from the specific view.\n const view = this.views.get(queryId);\n if (view) {\n cancelEvents = cancelEvents.concat(\n view.removeEventRegistration(eventRegistration, cancelError)\n );\n if (view.isEmpty()) {\n this.views.delete(queryId);\n\n // We'll deal with complete views later.\n if (\n !view\n .getQuery()\n .getQueryParams()\n .loadsAllData()\n ) {\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, events: cancelEvents };\n }\n\n getQueryViews(): View[] {\n const result = [];\n for (const view of this.views.values()) {\n if (\n !view\n .getQuery()\n .getQueryParams()\n .loadsAllData()\n ) {\n result.push(view);\n }\n }\n return result;\n }\n\n /**\n * @param path The path to the desired complete snapshot\n * @return A complete cache, if it exists\n */\n getCompleteServerCache(path: Path): Node | null {\n let serverCache: Node | null = null;\n for (const view of this.views.values()) {\n serverCache = serverCache || view.getCompleteServerCache(path);\n }\n return serverCache;\n }\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 this.views.get(queryId);\n }\n }\n\n viewExistsForQuery(query: Query): boolean {\n return this.viewForQuery(query) != null;\n }\n\n hasCompleteView(): boolean {\n return this.getCompleteView() != null;\n }\n\n getCompleteView(): View | null {\n for (const view of this.views.values()) {\n if (\n view\n .getQuery()\n .getQueryParams()\n .loadsAllData()\n ) {\n return view;\n }\n }\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Node, NamedNode } from './snap/Node';\nimport { PRIORITY_INDEX } from './snap/indexes/PriorityIndex';\nimport { assert } from '@firebase/util';\nimport { ChildrenNode } from './snap/ChildrenNode';\nimport { each } from './util/util';\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 */\nexport class CompoundWrite {\n constructor(private writeTree_: ImmutableTree<Node>) {}\n\n static Empty = new CompoundWrite(new ImmutableTree(null));\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 addWrites(path: Path, updates: { [name: string]: Node }): CompoundWrite {\n let newWrite = this as CompoundWrite;\n each(updates, (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 <em>not</em> modify a write at a higher\n * location, which must be removed by calling this method with that path.\n *\n * @param 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 The path to check for\n * @return 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 The path to get a complete write\n * @return 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 A list of all complete children.\n */\n getCompleteChildren(): NamedNode[] {\n const children: NamedNode[] = [];\n const 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(\n PRIORITY_INDEX,\n (childName, childNode) => {\n children.push(new NamedNode(childName, childNode));\n }\n );\n }\n } else {\n this.writeTree_.children.inorderTraversal((childName, childTree) => {\n if (childTree.value != null) {\n children.push(new NamedNode(childName, childTree.value));\n }\n });\n }\n return children;\n }\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 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 The node to apply this CompoundWrite to\n * @return The node with all writes applied\n */\n apply(node: Node): Node {\n return applySubtreeWrite(Path.Empty, this.writeTree_, node);\n }\n}\n\nfunction applySubtreeWrite(\n relativePath: Path,\n writeTree: ImmutableTree<Node>,\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((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 = applySubtreeWrite(relativePath.child(childKey), childTree, node);\n }\n });\n // If there was a priority write, we only apply it if the node is not empty\n if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {\n node = node.updateChild(relativePath.child('.priority'), priorityWrite);\n }\n return node;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { safeGet, assert, assertionError } from '@firebase/util';\n\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';\nimport { each } from './util/util';\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.<!WriteRecord>}\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,\n snap,\n writeId,\n 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.<string, !Node>} 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,\n children: changedChildren,\n 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(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 each(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.<number>=} 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, (childName, childSnap) => {\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(\n PRIORITY_INDEX,\n (childName, childNode) => {\n const node = merge\n .childCompoundWrite(new Path(childName))\n .apply(childNode);\n completeChildren = completeChildren.updateImmediateChild(\n childName,\n node\n );\n }\n );\n // Add any complete children we have from the set\n merge.getCompleteChildren().forEach(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(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 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 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 private recordContainsPath_(writeRecord: WriteRecord, path: Path): boolean {\n if (writeRecord.snap) {\n return writeRecord.path.contains(path);\n } else {\n for (const childName in writeRecord.children) {\n if (\n writeRecord.children.hasOwnProperty(childName) &&\n writeRecord.path.child(childName).contains(path)\n ) {\n return true;\n }\n }\n return false;\n }\n }\n\n /**\n * Re-layer the writes and merges into a tree so we can efficiently calculate event snapshots\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 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 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.<number>=} 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(\n completeServerChildren: ChildrenNode | null\n ): 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.<!NamedNode>}\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\nimport { errorForServerCode, each } from './util/util';\nimport { AckUserWrite } from './operation/AckUserWrite';\nimport { ChildrenNode } from './snap/ChildrenNode';\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.<!Event>\n * ):!Array.<!Event>,\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?: unknown) => 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 */\n private syncPointTree_: ImmutableTree<SyncPoint> = ImmutableTree.Empty;\n\n /**\n * A tree of all pending user writes (user-initiated set()'s, transaction()'s, update()'s, etc.).\n */\n private pendingWriteTree_ = new WriteTree();\n\n private readonly tagToQueryMap: Map<number, string> = new Map();\n private readonly queryToTagMap: Map<string, number> = new Map();\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 * @return 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 * @return 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 revert True if the given write failed and needs to be reverted\n * @return 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 each(write.children, (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 * @return 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 * @return 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 * @return 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 * @return 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 * @return 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 * @return 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 * @return 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, (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((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 !this.queryToTagMap.has(queryKey),\n 'View does not exist, but we have a tag'\n );\n const tag = SyncTree.getNextQueryTag_();\n this.queryToTagMap.set(queryKey, tag);\n this.tagToQueryMap.set(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 eventRegistration If null, all callbacks are removed.\n * @param cancelError If a cancelError is provided, appropriate cancel events will be returned.\n * @return 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.<!Query>, events: !Array.<!Event>}}\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(query => {\n return query.getQueryParams().loadsAllData();\n });\n const covered = this.syncPointTree_.findOnPath(\n path,\n (relativePath, parentSyncPoint) => {\n return parentSyncPoint.hasCompleteView();\n }\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.get(\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 *\n * @param path The path to the data we want\n * @param writeIdsToExclude A specific set to be excluded\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(\n path,\n (pathSoFar, syncPoint) => {\n const relativePath = Path.relativePath(pathSoFar, path);\n const serverCache = syncPoint.getCompleteServerCache(relativePath);\n if (serverCache) {\n return serverCache;\n }\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 private collectDistinctViewsForSubTree_(\n subtree: ImmutableTree<SyncPoint>\n ): View[] {\n return subtree.fold<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 each(childMap, (_key: string, childViews: View[]) => {\n views = views.concat(childViews);\n });\n return views;\n }\n }\n );\n }\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.get(removedQueryKey);\n this.queryToTagMap.delete(removedQueryKey);\n this.tagToQueryMap.delete(removedQueryTag);\n }\n }\n }\n\n /**\n * Normalizes a query to a query we send the server for listening\n *\n * @return The normalized query\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 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 * @return This method can return events to support synchronous data sources\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<Query[]>(\n (relativePath, maybeChildSyncPoint, childMap) => {\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 each(childMap, (_key: string, childQueries: Query[]) => {\n queries = queries.concat(childQueries);\n });\n return queries;\n }\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 private createListenerForView_(\n view: View\n ): { hashFn(): string; onComplete(a: string, b?: unknown): 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 */\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 */\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 */\n private queryKeyForTag_(tag: number): string | null {\n return this.tagToQueryMap.get(tag);\n }\n\n /**\n * Return the tag associated with the given query.\n */\n private tagForQuery_(query: Query): number | null {\n const queryKey = SyncTree.makeQueryKey_(query);\n return this.queryToTagMap.get(queryKey);\n }\n\n /**\n * Static tracker for next query tag.\n */\n private static nextQueryTag_ = 1;\n\n /**\n * Static accessor for query tags.\n */\n private static getNextQueryTag_(): number {\n return SyncTree.nextQueryTag_++;\n }\n\n /**\n * A helper method to apply tagged operations\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 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 applyOperationHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree<SyncPoint>,\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 applyOperationDescendantsHelper_(\n operation: Operation,\n syncPointTree: ImmutableTree<SyncPoint>,\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FirebaseAuthTokenData } from '@firebase/app-types/private';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport { log, warn } from './util/util';\nimport { FirebaseApp } from '@firebase/app-types';\n\n/**\n * Abstraction around FirebaseApp's token fetching capabilities.\n */\nexport class AuthTokenProvider {\n private auth_: FirebaseAuthInternal | null = null;\n constructor(\n private app_: FirebaseApp,\n private authProvider_: Provider<FirebaseAuthInternalName>\n ) {\n this.auth_ = authProvider_.getImmediate({ optional: true });\n if (!this.auth_) {\n authProvider_.get().then(auth => (this.auth_ = auth));\n }\n }\n\n /**\n * @param {boolean} forceRefresh\n * @return {!Promise<FirebaseAuthTokenData>}\n */\n getToken(forceRefresh: boolean): Promise<FirebaseAuthTokenData> {\n if (!this.auth_) {\n return Promise.resolve(null);\n }\n\n return this.auth_.getToken(forceRefresh).catch(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 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 if (this.auth_) {\n this.auth_.addAuthTokenListener(listener);\n } else {\n setTimeout(() => listener(null), 0);\n this.authProvider_\n .get()\n .then(auth => auth.addAuthTokenListener(listener));\n }\n }\n\n removeTokenChangeListener(listener: (token: string | null) => void) {\n this.authProvider_\n .get()\n .then(auth => auth.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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, contains } from '@firebase/util';\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)) {\n this.counters_[name] = 0;\n }\n\n this.counters_[name] += amount;\n }\n\n get() {\n return deepCopy(this.counters_);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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]: unknown } = {};\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<T>(\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] as T;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { each } from '../util/util';\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 = { ...newStats };\n if (this.last_) {\n each(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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\nimport { setTimeoutNonBlocking, each } 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 each(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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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.<EventList>}\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.<Event>} 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.<Event>} 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.<!Event>} 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.<Event>}\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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: unknown[]): void;\n context: unknown;\n }>;\n } = {};\n\n /**\n * @param {!Array.<string>} allowedEvents_\n */\n constructor(private allowedEvents_: string[]) {\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): unknown[];\n\n /**\n * To be called by derived classes to trigger events.\n * @param {!string} eventType\n * @param {...*} varArgs\n */\n protected trigger(eventType: string, ...varArgs: unknown[]) {\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, varArgs);\n }\n }\n }\n\n on(eventType: string, callback: (a: unknown) => void, context: unknown) {\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: unknown) => void, context: unknown) {\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(et => {\n return et === eventType;\n }),\n 'Unknown event: ' + eventType\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\n\ndeclare const document: Document;\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.<boolean>}\n */\n getInitialEvent(eventType: string): boolean[] {\n assert(eventType === 'visible', 'Unknown event type: ' + eventType);\n return [this.visible_];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, isMobileCordova } from '@firebase/util';\nimport { EventEmitter } from './EventEmitter';\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.<boolean>}\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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: unknown[] = [];\n currentResponseNum = 0;\n closeAfterResponse = -1;\n onClose: (() => void) | null = null;\n\n /**\n * @param onMessage_\n */\n constructor(private onMessage_: (a: {}) => 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: unknown[]) {\n this.pendingResponses[requestNum] = data;\n while (this.pendingResponses[this.currentResponseNum]) {\n const toProcess = this.pendingResponses[\n this.currentResponseNum\n ] as unknown[];\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 executeWhenDOMReady,\n isChromeExtensionContentScript,\n isWindowsStoreApp,\n log,\n logWrapper,\n LUIDGenerator,\n splitStringBySize\n} from '../core/util/util';\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 { base64Encode, stringify, isNodeSdk } from '@firebase/util';\n\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: unknown[]) => 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: {}) => 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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_) {\n return;\n }\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) {\n return; // we closed the connection.\n }\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 as string;\n this.password = arg2 as string;\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 as number, () => {\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 as number, data as unknown[]);\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 }\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 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 if (isNodeSdk()) {\n return false;\n } else if (BrowserPollConnection.forceAllow_) {\n return true;\n } else {\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.forceDisallow_ &&\n typeof document !== 'undefined' &&\n document.createElement != null &&\n !isChromeExtensionContentScript() &&\n !isWindowsStoreApp()\n );\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: {}) {\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()) {\n return;\n }\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: unknown) {\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\n// eslint-disable-next-line @typescript-eslint/interface-name-prefix\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 outstandingRequests = new Set<number>();\n\n //A queue of the pending segments waiting for transmission to the server.\n pendingSegs: Array<{ seg: number; ts: number; d: unknown }> = [];\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: unknown[]) => void;\n onMessageCB: (...args: unknown[]) => 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: unknown[]) => void,\n onMessageCB: (...args: unknown[]) => 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[\n FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier\n ] = commandCB;\n window[\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 = '<script>document.domain=\"' + currentDomain + '\";</script>';\n }\n const iframeContents = '<html><body>' + script + '</body></html>';\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.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } else if ((iframe as any).document) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n iframe.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 // 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.size < (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 as unknown[]).length +\n SEG_HEADER_SIZE +\n 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: unknown) {\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);\n\n const doNewRequest = () => {\n this.outstandingRequests.delete(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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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) {\n return;\n }\n const newScript = this.myIFrame.doc.createElement('script');\n newScript.type = 'text/javascript';\n newScript.async = true;\n newScript.src = url;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n newScript.onload = (newScript as any).onreadystatechange = function() {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const rstate = (newScript as any).readyState;\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nexport let SDK_VERSION = '';\n\n// SDK_VERSION should be set before any database instance is created\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 {\n assert,\n CONSTANTS as ENV_CONSTANTS,\n jsonEval,\n stringify,\n isNodeSdk\n} from '@firebase/util';\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 { PersistentStorage } from '../core/storage/storage';\nimport { Transport } from './Transport';\nimport { StatsCollection } from '../core/stats/StatsCollection';\nimport { SDK_VERSION } from '../core/version';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ndeclare const MozWebSocket: any;\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: {}) => void;\n mySock: WebSocket | null;\n private log_: (...a: unknown[]) => 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: {}) => 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/<wire_protocol>/<sdk_version>/<platform>/<device>\n const options: { [k: string]: object } = {\n headers: {\n 'User-Agent': `Firebase/${PROTOCOL_VERSION}/${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 => {\n this.handleIncomingFrame(m as {});\n };\n\n this.mySock.onerror = e => {\n this.log_('WebSocket error. Closing connection.');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const error = (e as any).message || (e as any).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) as object;\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]: unknown }) {\n if (this.mySock === null) {\n return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n }\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: {}) {\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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.<function(new:Transport, string, RepoInfo, string=)>}\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\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n const transports = (this.transports_ = [] as TransportConstructor[]);\n for (const transport of TransportManager.ALL_TRANSPORTS) {\n if (transport && transport['isAvailable']()) {\n transports.push(transport);\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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';\nimport { Indexable } from '../core/util/misc';\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: unknown[] = [];\n sessionId: string;\n\n private conn_: Transport;\n private healthyTimeout_: number;\n private isHealthy_: boolean;\n private log_: (...args: unknown[]) => 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: {}) => 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_(): void {\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 healthyTimeoutMS = conn['healthyTimeout'] || 0;\n if (healthyTimeoutMS > 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(healthyTimeoutMS)) 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: Indexable) => {\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]: unknown }) {\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: Indexable) {\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onSecondaryControl_(data as Indexable);\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]: unknown }) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n const layer: string = requireKey('t', parsedData) as string;\n const data: unknown = requireKey('d', parsedData);\n if (layer === 'c') {\n this.onControl_(data as { [k: string]: unknown });\n } else if (layer === 'd') {\n this.onDataMessage_(data);\n }\n }\n\n private onDataMessage_(message: unknown) {\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]: unknown }) {\n const cmd: string = requireKey(MESSAGE_TYPE, controlData) as string;\n if (MESSAGE_DATA in controlData) {\n const payload = controlData[MESSAGE_DATA];\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(\n payload as {\n ts: number;\n v: string;\n h: string;\n s: string;\n }\n );\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 as string);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload as string);\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 }): void {\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. <ns>.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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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: unknown) => 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: unknown,\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: unknown,\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: unknown,\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: unknown,\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.<string, *>} stats\n */\n reportStats(stats: { [k: string]: unknown }) {}\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 contains,\n isEmpty,\n safeGet,\n CONSTANTS,\n stringify,\n assert,\n isAdmin,\n isValidFormat,\n isMobileCordova,\n isReactNative,\n isNodeSdk\n} from '@firebase/util';\n\nimport { error, log, logWrapper, warn, ObjectToUniqueKey } from './util/util';\nimport { Path } from './util/Path';\nimport { VisibilityMonitor } from './util/VisibilityMonitor';\nimport { OnlineMonitor } from './util/OnlineMonitor';\n\nimport { Connection } from '../realtime/Connection';\n\nimport { ServerActions } from './ServerActions';\nimport { AuthTokenProvider } from './AuthTokenProvider';\nimport { RepoInfo } from './RepoInfo';\nimport { Query } from '../api/Query';\nimport { SDK_VERSION } from './version';\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?: unknown): 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: unknown;\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 interruptReasons_: { [reason: string]: boolean } = {};\n /** Map<path, Map<queryId, ListenSpec>> */\n private readonly listens: Map<\n /* path */ string,\n Map</* queryId */ string, ListenSpec>\n > = new Map();\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 establishConnectionTimer_: number | null = null;\n\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: unknown) => void } = {};\n private requestNumber_ = 0;\n\n private realtime_: {\n sendRequest(a: object): void;\n close(): void;\n } | null = null;\n\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 private static nextPersistentConnectionId_ = 0;\n\n /**\n * Counter for number of connections created. Mainly used for tagging in the logs\n */\n private static nextConnectionId_ = 0;\n\n /**\n * @implements {ServerActions}\n * @param repoInfo_ Data about the namespace we are connecting to\n * @param onDataUpdate_ A callback for new data from the server\n */\n constructor(\n private repoInfo_: RepoInfo,\n private onDataUpdate_: (\n a: string,\n b: unknown,\n c: boolean,\n d: number | null\n ) => void,\n private onConnectStatus_: (a: boolean) => void,\n private onServerInfoUpdate_: (a: unknown) => 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 protected sendRequest(\n action: string,\n body: unknown,\n onResponse?: (a: unknown) => 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: unknown) => void\n ) {\n const queryId = query.queryIdentifier();\n const pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n if (!this.listens.has(pathString)) {\n this.listens.set(pathString, new Map());\n }\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.get(pathString)!.has(queryId),\n 'listen() called twice for same path/queryId.'\n );\n const listenSpec: ListenSpec = {\n onComplete,\n hashFn: currentHashFn,\n query,\n tag\n };\n this.listens.get(pathString)!.set(queryId, listenSpec);\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n }\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]: unknown } = { /*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]: unknown }) => {\n const payload: unknown = message[/*data*/ 'd'];\n const status = message[/*status*/ 's'] as string;\n\n // print warnings in any case...\n PersistentConnection.warnOnListenWarnings_(payload, query);\n\n const currentListenSpec =\n this.listens.get(pathString) &&\n this.listens.get(pathString)!.get(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 private static warnOnListenWarnings_(payload: unknown, query: Query) {\n if (payload && typeof payload === 'object' && contains(payload, 'w')) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const warnings = safeGet(payload as any, 'w');\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n const indexSpec =\n '\".indexOn\": \"' +\n query\n .getQueryParams()\n .getIndex()\n .toString() +\n '\"';\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 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]: unknown } = { 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(\n authMethod,\n requestData,\n (res: { [k: string]: unknown }) => {\n const status = res[/*status*/ 's'] as string;\n const data = (res[/*data*/ 'd'] as string) || '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 /**\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]: unknown } = { /*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: unknown,\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: unknown,\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: unknown,\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]: unknown }) => {\n if (onComplete) {\n setTimeout(() => {\n onComplete(\n response[/*status*/ 's'] as string,\n response[/* data */ 'd'] as string\n );\n }, Math.floor(0));\n }\n });\n }\n\n /**\n * @inheritDoc\n */\n put(\n pathString: string,\n data: unknown,\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: unknown,\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: unknown,\n onComplete: (a: string, b: string | null) => void,\n hash?: string\n ) {\n const request: { [k: string]: unknown } = {\n /*path*/ p: pathString,\n /*data*/ d: data\n };\n\n if (hash !== undefined) {\n request[/*hash*/ 'h'] = hash;\n }\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]: unknown }) => {\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(\n message[/*status*/ 's'] as string,\n message[/* data */ 'd'] as string\n );\n }\n });\n }\n\n /**\n * @inheritDoc\n */\n reportStats(stats: { [k: string]: unknown }) {\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 private onDataMessage_(message: { [k: string]: unknown }) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + stringify(message));\n const reqNum = message['r'] as string;\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'] as string, message['b'] as {});\n }\n }\n\n private onDataPush_(action: string, body: { [k: string]: unknown }) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge*/ false,\n body['t'] as number\n );\n } else if (action === 'm') {\n this.onDataUpdate_(\n body[/*path*/ 'p'] as string,\n body[/*data*/ 'd'],\n /*isMerge=*/ true,\n body['t'] as number\n );\n } else if (action === 'c') {\n this.onListenRevoked_(\n body[/*path*/ 'p'] as string,\n body[/*query*/ 'q'] as unknown[]\n );\n } else if (action === 'ac') {\n this.onAuthRevoked_(\n body[/*status code*/ 's'] as string,\n body[/* explanation */ 'd'] as string\n );\n } else if (action === 'sd') {\n 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\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n }, Math.floor(timeout)) as any;\n }\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 }\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(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= */ 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, 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 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 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) {\n put.onComplete('disconnect');\n }\n\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n }\n\n // Clean up array occasionally.\n if (this.outstandingPutCount_ === 0) {\n this.outstandingPuts_ = [];\n }\n }\n\n private onListenRevoked_(pathString: string, query?: unknown[]) {\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) {\n listen.onComplete('permission_denied');\n }\n }\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.has(normalizedPathString)) {\n const map = this.listens.get(normalizedPathString)!;\n listen = map.get(queryId);\n map.delete(queryId);\n if (map.size === 0) {\n this.listens.delete(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]: unknown }) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log(\n 'FIREBASE: ' + (body['msg'] as string).replace('\\n', '\\nFIREBASE: ')\n );\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 for (const queries of this.listens.values()) {\n for (const listenSpec of queries.values()) {\n this.sendListen_(listenSpec);\n }\n }\n\n for (let i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) {\n this.sendPut_(i);\n }\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 */\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['sdk.' + clientName + '.' + SDK_VERSION.replace(/\\./g, '-')] = 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 private shouldReconnect_(): boolean {\n const online = OnlineMonitor.getInstance().currentlyOnline();\n return isEmpty(this.interruptReasons_) && online;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, jsonEval, safeGet, querystring } from '@firebase/util';\nimport { logWrapper, warn } from './util/util';\n\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]: unknown }): void {\n throw new Error('Method not implemented.');\n }\n\n /** @private {function(...[*])} */\n private log_: (...args: unknown[]) => 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.<string, !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: unknown,\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: unknown) => 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 queryStringParameters = query\n .getQueryParams()\n .toRestQueryStringParameters();\n\n this.restRequest_(\n pathString + '.json',\n queryStringParameters,\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.<string, *>} queryStringParameters\n * @param {?function(?number, *=)} callback\n * @private\n */\n private restRequest_(\n pathString: string,\n queryStringParameters: { [k: string]: string | number } = {},\n callback: ((a: number | null, b?: unknown) => 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 'ns=' +\n this.repoInfo_.namespace +\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 a querystring-formatted string (e.g. &arg=val&arg2=val2) from a\n * params object (e.g. {arg: 'val', arg2: 'val2'})\n * Note: You must prepend it with ? when adding it to a URL.\n */\nexport function querystring(querystringParams: {\n [key: string]: string | number;\n}): string {\n const params = [];\n for (const [key, value] of Object.entries(querystringParams)) {\n if (Array.isArray(value)) {\n value.forEach(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\n * (e.g. {arg: 'val', arg2: 'val2'})\n */\nexport function querystringDecode(querystring: string): object {\n const obj: { [key: string]: unknown } = {};\n const tokens = querystring.replace(/^\\?/, '').split('&');\n\n tokens.forEach(token => {\n if (token) {\n const key = token.split('=');\n obj[key[0]] = key[1];\n }\n });\n return obj;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, map, isEmpty } from '@firebase/util';\nimport { beingCrawled, each, exceptionGuard, warn, log } from './util/util';\n\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 '@firebase/app-types';\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';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\nimport { Indexable } from './util/misc';\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 transactionsInit_: () => void;\n private infoData_: SnapshotHolder;\n private abortTransactions_: (path: Path) => Path;\n private rerunTransactions_: (changedPath: Path) => Path;\n private interceptServerDataCallback_:\n | ((a: string, b: unknown) => 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 // TODO: This should be @private but it's used by test_access.js and internal.js\n persistentConnection_: PersistentConnection | null = null;\n\n constructor(\n public repoInfo_: RepoInfo,\n forceRestClient: boolean,\n public app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>\n ) {\n const authTokenProvider = new AuthTokenProvider(app, authProvider);\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.transactionsInit_();\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 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 The namespace represented by the repo.\n */\n name(): string {\n return this.repoInfo_.namespace;\n }\n\n /**\n * @return 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 */\n generateServerValues(): Indexable {\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 onDataUpdate_(\n pathString: string,\n data: unknown,\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(\n data as { [k: string]: unknown },\n (raw: unknown) => 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(\n data as { [k: string]: unknown },\n (raw: unknown) => 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 // TODO: This should be @private but it's used by test_access.js and internal.js\n interceptServerData_(callback: ((a: string, b: unknown) => unknown) | null) {\n this.interceptServerDataCallback_ = callback;\n }\n\n private onConnectStatus_(connectStatus: boolean) {\n this.updateInfo_('connected', connectStatus);\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n }\n\n private onServerInfoUpdate_(updates: object) {\n each(updates, (key: string, value: unknown) => {\n this.updateInfo_(key, value);\n });\n }\n\n private updateInfo_(pathString: string, value: unknown) {\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 private getNextWriteId_(): number {\n return this.nextWriteId_++;\n }\n\n setWithPriority(\n path: Path,\n newVal: unknown,\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 update(\n path: Path,\n childrenToMerge: { [k: string]: unknown },\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 each(childrenToMerge, (changedKey: string, changedValue: unknown) => {\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 each(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 */\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 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 onDisconnectSet(\n path: Path,\n value: unknown,\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 onDisconnectSetWithPriority(\n path: Path,\n value: unknown,\n priority: unknown,\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 onDisconnectUpdate(\n path: Path,\n childrenToMerge: { [k: string]: unknown },\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 each(childrenToMerge, (childName: string, childNode: unknown) => {\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 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 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') {\n return;\n }\n\n let stats: { [k: string]: unknown };\n if (showDelta) {\n if (!this.statsListener_) {\n this.statsListener_ = new StatsListener(this.stats_);\n }\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 each(stats, (stat: string, value: unknown) => {\n let paddedStat = stat;\n // pad stat names to be the same length (plus 2 extra spaces).\n for (let i = stat.length; i < longestName + 2; i++) {\n paddedStat += ' ';\n }\n console.log(paddedStat + value);\n });\n }\n\n statsIncrementCounter(metric: string) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n }\n\n private log_(...varArgs: unknown[]) {\n let prefix = '';\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n log(prefix, ...varArgs);\n }\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(() => {\n if (status === 'ok') {\n callback(null);\n } else {\n const code = (status || 'error').toUpperCase();\n let message = code;\n if (errorReason) {\n message += ': ' + errorReason;\n }\n\n const error = new Error(message);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, (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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/util';\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 const next = iterator.getNext();\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n const 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, stringify } from '@firebase/util';\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 { 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_: unknown | null = null;\n private indexStartName_ = '';\n private indexEndValue_: unknown | 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(): unknown {\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(): unknown {\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: unknown, 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: unknown, 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(): {} {\n const WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n const obj: { [k: string]: unknown } = {};\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.<string,*>} query string parameters\n */\n toRestQueryStringParameters(): { [k: string]: string | number } {\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, Deferred } from '@firebase/util';\n\nimport { SyncPoint } from '../core/SyncPoint';\nimport { Database } from './Database';\nimport { DataSnapshot } from './DataSnapshot';\nimport * as types from '@firebase/database-types';\n\nexport interface ReferenceConstructor {\n new (repo: Repo, path: Path): Reference;\n}\n\nexport class Reference extends Query {\n then: Promise<Reference>['then'];\n catch: Promise<Reference>['catch'];\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()) {\n return null;\n } else {\n return this.path.getBack();\n }\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 {\n validatePathString('Reference.child', 1, pathString, false);\n }\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: Reference = this;\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(\n newVal: unknown,\n onComplete?: (a: Error | null) => void\n ): Promise<unknown> {\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<unknown> {\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]: unknown } = {};\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 as { [k: string]: unknown },\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: unknown,\n newPriority: string | number | null,\n onComplete?: (a: Error | null) => void\n ): Promise<unknown> {\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\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<unknown> {\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: unknown) => unknown,\n onComplete?: (a: Error | null, b: boolean, c: DataSnapshot | null) => void,\n applyLocally?: boolean\n ): Promise<TransactionResult> {\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\n if (applyLocally === undefined) {\n applyLocally = true;\n }\n\n const deferred = new Deferred<TransactionResult>();\n if (typeof onComplete === 'function') {\n deferred.promise.catch(() => {});\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<unknown> {\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?: unknown, 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 = Promise.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 promise.catch(() => {});\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, contains, safeGet } from '@firebase/util';\nimport { Path } from './Path';\n\nimport { each } from './util';\n\n/**\n * Node in a Tree.\n */\nexport class TreeNode<T> {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n children: { [name: string]: TreeNode<T> } = {};\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<T> {\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<T> | null = null,\n private node_: TreeNode<T> = new TreeNode<T>()\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.<T>} Tree for path.\n */\n subTree(pathObj: string | Path): Tree<T> {\n // TODO: Require pathObj to be Path?\n let path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n let child = this as Tree<T>,\n next = path.getFront();\n while (next !== null) {\n const childNode = safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n next = path.getFront();\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.<T>)} action Action to be called for each child.\n */\n forEachChild(action: (tree: Tree<T>) => void) {\n each(this.node_.children, (child: string, childTree: TreeNode<T>) => {\n action(new Tree<T>(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.<T>)} 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<T>) => void,\n includeSelf?: boolean,\n childrenFirst?: boolean\n ) {\n if (includeSelf && !childrenFirst) {\n action(this);\n }\n\n this.forEachChild(child => {\n child.forEachDescendant(action, /*includeSelf=*/ true, childrenFirst);\n });\n\n if (includeSelf && childrenFirst) {\n action(this);\n }\n }\n\n /**\n * Calls action on each ancestor node.\n *\n * @param {function(!Tree.<T>)} 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<T>) => unknown,\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.<T>)} action Action to be called for each child.\n */\n forEachImmediateDescendantWithValue(action: (tree: Tree<T>) => void) {\n this.forEachChild(child => {\n if (child.getValue() !== null) {\n action(child);\n } else {\n child.forEachImmediateDescendantWithValue(action);\n }\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<T> | 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) {\n this.parent_.updateChild_(this.name_, this);\n }\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.<T>} child The child to update.\n * @private\n */\n private updateChild_(childName: string, child: Tree<T>) {\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, contains, safeGet } from '@firebase/util';\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';\n\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// eslint-disable-next-line @typescript-eslint/no-explicit-any\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 */\ninterface Transaction {\n path: Path;\n update: (a: unknown) => unknown;\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// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).transactionsInit_ = function() {\n /**\n * Stores queues of outstanding transactions for Firebase locations.\n *\n * @type {!Tree.<Array.<!Transaction>>}\n * @private\n */\n this.transactionQueueTree_ = new Tree<Transaction[]>();\n};\n\ndeclare module './Repo' {\n interface Repo {\n startTransaction(\n path: Path,\n transactionUpdate: (a: unknown) => 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: unknown) => unknown,\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,\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n priorityForNode = safeGet(newVal as any, '.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.<number>=} excludeSets A specific set to exclude\n * @return {Node}\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\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.<Array.<Transaction>>=} node transactionQueueTree node to start at.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).sendReadyTransactions_ = function(\n node: Tree<Transaction[]> = 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.<Transaction>} queue Queue of transactions under the specified location.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).sendTransactionQueue_ = function(\n path: Path,\n queue: Transaction[]\n) {\n // Mark transactions as sent and increment retry count!\n const setsToIgnore = queue.map(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 {\n queue[i].status = TransactionStatus.RUN;\n }\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// eslint-disable-next-line @typescript-eslint/no-explicit-any\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.<Transaction>} queue The queue of transactions to run.\n * @param {!Path} path The path the queue is for.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).rerunTransactionQueue_ = function(\n queue: Transaction[],\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(q => {\n return q.status === TransactionStatus.RUN;\n });\n const setsToIgnore = txnsToRerun.map(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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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.<Array.<!Transaction>>} The rootmost node with a transaction.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).getAncestorTransactionNode_ = function(\n path: Path\n): Tree<Transaction[]> {\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 front = path.getFront();\n while (front !== null && transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n front = path.getFront();\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.<Array.<Transaction>>} transactionNode\n * @return {Array.<Transaction>} The generated queue.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).buildTransactionQueue_ = function(\n transactionNode: Tree<Transaction[]>\n): Transaction[] {\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((a, b) => {\n return a.order - b.order;\n });\n\n return transactionQueue;\n};\n\n/**\n * @param {!Tree.<Array.<Transaction>>} node\n * @param {Array.<Transaction>} queue\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).aggregateTransactionQueuesForNode_ = function(\n node: Tree<Transaction[]>,\n queue: Transaction[]\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.<Array.<!Transaction>>} node\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).pruneCompletedTransactionsBelowNode_ = function(\n node: Tree<Transaction[]>\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// eslint-disable-next-line @typescript-eslint/no-explicit-any\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<Transaction[]>) => {\n this.abortTransactionsOnNode_(node);\n });\n\n this.abortTransactionsOnNode_(transactionNode);\n\n transactionNode.forEachDescendant((node: Tree<Transaction[]>) => {\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.<Array.<Transaction>>} node Node to abort transactions for.\n * @private\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(Repo.prototype as any).abortTransactionsOnNode_ = function(\n node: Tree<Transaction[]>\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app-types';\nimport { safeGet } from '@firebase/util';\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';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\n/** @const {string} */\nconst DATABASE_URL_OPTION = 'databaseURL';\n\n/**\n * This variable is also defined in the firebase node.js admin SDK. Before\n * modifying this definition, consult the definition in:\n *\n * https://github.com/firebase/firebase-admin-node\n *\n * and make sure the two are consistent.\n */\nconst FIREBASE_DATABASE_EMULATOR_HOST_VAR = 'FIREBASE_DATABASE_EMULATOR_HOST';\n\nlet _staticInstance: RepoManager;\n\n/**\n * Creates and caches Repo instances.\n */\nexport class RepoManager {\n /**\n * @private {!Object.<string, Object<string, !fb.core.Repo>>}\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 of Object.keys(this.repos_)) {\n for (const dbUrl of Object.keys(this.repos_[appName])) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n }\n\n resume() {\n for (const appName of Object.keys(this.repos_)) {\n for (const dbUrl of Object.keys(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(\n app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n url?: string\n ): Database {\n let dbUrl: string | undefined = 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.initializeApp().'\n );\n }\n\n let parsedUrl = parseRepoInfo(dbUrl);\n let repoInfo = parsedUrl.repoInfo;\n\n let dbEmulatorHost: string | undefined = undefined;\n if (typeof process !== 'undefined') {\n dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];\n }\n if (dbEmulatorHost) {\n dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;\n parsedUrl = parseRepoInfo(dbUrl);\n repoInfo = parsedUrl.repoInfo;\n }\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, authProvider);\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(\n repoInfo: RepoInfo,\n app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>\n ): 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, authProvider);\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Reference } from './Reference';\nimport { Repo } from '../core/Repo';\nimport { RepoManager } from '../core/RepoManager';\nimport { validateArgCount } from '@firebase/util';\nimport { validateUrl } from '../core/util/validation';\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport { RepoInfo } from '../core/RepoInfo';\nimport { FirebaseDatabase } from '@firebase/database-types';\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 to the path specified in the provided\n * argument.\n *\n * @param {string|Reference=} path The relative string path or an existing\n * Reference to a database location.\n * @throws If a Reference is provided, throws if it does not belong to the\n * same project.\n * @return {!Reference} Firebase reference.\n */\n ref(path?: string): Reference;\n ref(path?: Reference): Reference;\n ref(path?: string | Reference): Reference {\n this.checkDeleted_('ref');\n validateArgCount('database.ref', 0, 1, arguments.length);\n\n if (path instanceof Reference) {\n return this.refFromURL(path.toString());\n }\n\n return path !== undefined ? this.root_.child(path) : 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_.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_.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<void>} */\n async delete(): Promise<void> {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.database as any).checkDeleted_('delete');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n RepoManager.getInstance().deleteRepo((this.database as any).repo_ as Repo);\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.database as any).repo_ = null;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (this.database as any).root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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: unknown) => void) | null\n) {\n return ref.repo.interceptServerData_(callback);\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).simpleListen = function(\n pathString: string,\n onComplete: (a: unknown) => void\n) {\n this.sendRequest('q', { p: pathString }, onComplete);\n};\n\n/**\n * @param {*} data\n * @param {function(*)} onEcho\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n(PersistentConnection.prototype as any).echo = function(\n data: unknown,\n onEcho: (a: unknown) => 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 onComplete,\n hash\n ) {\n if (hash !== undefined) {\n hash = newHash();\n }\n oldPut.call(this, pathString, data, onComplete, 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 * 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app';\nimport { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Database } from './src/api/Database';\nimport { DataSnapshot } from './src/api/DataSnapshot';\nimport { Query } from './src/api/Query';\nimport { Reference } from './src/api/Reference';\nimport { enableLogging } from './src/core/util/util';\nimport { RepoManager } from './src/core/RepoManager';\nimport * as INTERNAL from './src/api/internal';\nimport * as TEST_ACCESS from './src/api/test_access';\nimport { isNodeSdk } from '@firebase/util';\nimport * as types from '@firebase/database-types';\nimport { setSDKVersion } from './src/core/version';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { name, version } from './package.json';\n\nconst ServerValue = Database.ServerValue;\n\nexport function registerDatabase(instance: FirebaseNamespace) {\n // set SDK_VERSION\n setSDKVersion(instance.SDK_VERSION);\n\n // Register the Database Service with the 'firebase' namespace.\n const namespace = (instance as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'database',\n (container, url) => {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider('auth-internal');\n\n return RepoManager.getInstance().databaseFromApp(\n app,\n authProvider,\n url\n );\n },\n ComponentType.PUBLIC\n )\n .setServiceProps(\n // firebase.database namespace properties\n {\n Reference,\n Query,\n Database,\n DataSnapshot,\n enableLogging,\n INTERNAL,\n ServerValue,\n TEST_ACCESS\n }\n )\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n\n if (isNodeSdk()) {\n module.exports = namespace;\n }\n}\n\nregisterDatabase(firebase);\n\n// Types to export for the admin SDK\nexport { Database, Query, Reference, enableLogging, ServerValue };\n\nexport { DataSnapshot } from './src/api/DataSnapshot';\nexport { OnDisconnect } from './src/api/onDisconnect';\n\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n database?: {\n (app?: FirebaseApp): types.FirebaseDatabase;\n enableLogging: typeof types.enableLogging;\n ServerValue: types.ServerValue;\n Database: typeof types.FirebaseDatabase;\n };\n }\n interface FirebaseApp {\n database?(databaseURL?: string): types.FirebaseDatabase;\n }\n}\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Bootstrap for the Google JS Library (Closure).\r\n *\r\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\r\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\r\n * to include their own deps file(s) from different locations.\r\n *\r\n * Avoid including base.js more than once. This is strictly discouraged and not\r\n * supported. goog.require(...) won't work properly in that case.\r\n *\r\n * @provideGoog\r\n */\r\n\r\n\r\n/**\r\n * @define {boolean} Overridden to true by the compiler.\r\n */\r\nvar COMPILED = false;\r\n\r\n\r\n/**\r\n * Base namespace for the Closure library. Checks to see goog is already\r\n * defined in the current scope before assigning to prevent clobbering if\r\n * base.js is loaded more than once.\r\n *\r\n * @const\r\n */\r\nvar goog = goog || {};\r\n\r\n/**\r\n * Reference to the global context. In most cases this will be 'window'.\r\n * @const\r\n * @suppress {newCheckTypes}\r\n */\r\ngoog.global = this;\r\n\r\n\r\n/**\r\n * A hook for overriding the define values in uncompiled mode.\r\n *\r\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\r\n * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\r\n * `goog.define` will use the value instead of the default value. This\r\n * allows flags to be overwritten without compilation (this is normally\r\n * accomplished with the compiler's \"define\" flag).\r\n *\r\n * Example:\r\n * <pre>\r\n * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\r\n * </pre>\r\n *\r\n * @type {Object<string, (string|number|boolean)>|undefined}\r\n */\r\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\r\n\r\n\r\n/**\r\n * A hook for overriding the define values in uncompiled or compiled mode,\r\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In\r\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\r\n *\r\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\r\n * string literals or the compiler will emit an error.\r\n *\r\n * While any @define value may be set, only those set with goog.define will be\r\n * effective for uncompiled code.\r\n *\r\n * Example:\r\n * <pre>\r\n * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\r\n * </pre>\r\n *\r\n * @type {Object<string, (string|number|boolean)>|undefined}\r\n */\r\ngoog.global.CLOSURE_DEFINES;\r\n\r\n\r\n/**\r\n * Returns true if the specified value is not undefined.\r\n *\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is defined.\r\n */\r\ngoog.isDef = function(val) {\r\n // void 0 always evaluates to undefined and hence we do not need to depend on\r\n // the definition of the global variable named 'undefined'.\r\n return val !== void 0;\r\n};\r\n\r\n/**\r\n * Returns true if the specified value is a string.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a string.\r\n */\r\ngoog.isString = function(val) {\r\n return typeof val == 'string';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is a boolean.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is boolean.\r\n */\r\ngoog.isBoolean = function(val) {\r\n return typeof val == 'boolean';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is a number.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a number.\r\n */\r\ngoog.isNumber = function(val) {\r\n return typeof val == 'number';\r\n};\r\n\r\n\r\n/**\r\n * Builds an object structure for the provided namespace path, ensuring that\r\n * names that already exist are not overwritten. For example:\r\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\r\n * Used by goog.provide and goog.exportSymbol.\r\n * @param {string} name name of the object that this file defines.\r\n * @param {*=} opt_object the object to expose at the end of the path.\r\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\r\n * is `goog.global`.\r\n * @private\r\n */\r\ngoog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {\r\n var parts = name.split('.');\r\n var cur = opt_objectToExportTo || goog.global;\r\n\r\n // Internet Explorer exhibits strange behavior when throwing errors from\r\n // methods externed in this manner. See the testExportSymbolExceptions in\r\n // base_test.html for an example.\r\n if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\r\n cur.execScript('var ' + parts[0]);\r\n }\r\n\r\n for (var part; parts.length && (part = parts.shift());) {\r\n if (!parts.length && goog.isDef(opt_object)) {\r\n // last part and we have an object; use it\r\n cur[part] = opt_object;\r\n } else if (cur[part] && cur[part] !== Object.prototype[part]) {\r\n cur = cur[part];\r\n } else {\r\n cur = cur[part] = {};\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Defines a named value. In uncompiled mode, the value is retrieved from\r\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\r\n * has the property specified, and otherwise used the defined defaultValue.\r\n * When compiled the default can be overridden using the compiler options or the\r\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\r\n * can be used safely in modules. Note that the value type MUST be either\r\n * boolean, number, or string.\r\n *\r\n * @param {string} name The distinguished name to provide.\r\n * @param {T} defaultValue\r\n * @return {T} The defined value.\r\n * @template T\r\n */\r\ngoog.define = function(name, defaultValue) {\r\n var value = defaultValue;\r\n if (!COMPILED) {\r\n var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\r\n var defines = goog.global.CLOSURE_DEFINES;\r\n if (uncompiledDefines &&\r\n // Anti DOM-clobbering runtime check (b/37736576).\r\n /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\r\n Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\r\n value = uncompiledDefines[name];\r\n } else if (\r\n defines &&\r\n // Anti DOM-clobbering runtime check (b/37736576).\r\n /** @type {?} */ (defines).nodeType === undefined &&\r\n Object.prototype.hasOwnProperty.call(defines, name)) {\r\n value = defines[name];\r\n }\r\n }\r\n goog.exportPath_(name, value);\r\n return value;\r\n};\r\n\r\n\r\n/**\r\n * @define {number} Integer year indicating the set of browser features that are\r\n * guaranteed to be present. This is defined to include exactly features that\r\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\r\n * specified year. For example,\r\n * ```js\r\n * if (goog.FEATURESET_YEAR >= 2019) {\r\n * // use APIs known to be available on all major stable browsers Jan 1, 2019\r\n * } else {\r\n * // polyfill for older browsers\r\n * }\r\n * ```\r\n * This is intended to be the primary define for removing\r\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\r\n * and should inform the default value for most other defines:\r\n * ```js\r\n * const ASSUME_NATIVE_PROMISE =\r\n * goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\r\n * ```\r\n *\r\n * The default assumption is that IE9 is the lowest supported browser, which was\r\n * first available Jan 1, 2012.\r\n *\r\n * TODO(user): Reference more thorough documentation when it's available.\r\n */\r\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\r\n\r\n\r\n/**\r\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\r\n * that should not be included in a production. It can be easily stripped\r\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\r\n * JSCompiler. For example, most toString() methods should be declared inside an\r\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\r\n * purposes and it is difficult for the JSCompiler to statically determine\r\n * whether they are used.\r\n */\r\ngoog.DEBUG = goog.define('goog.DEBUG', true);\r\n\r\n\r\n/**\r\n * @define {string} LOCALE defines the locale being used for compilation. It is\r\n * used to select locale specific data to be compiled in js binary. BUILD rule\r\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\r\n * option.\r\n *\r\n * Take into account that the locale code format is important. You should use\r\n * the canonical Unicode format with hyphen as a delimiter. Language must be\r\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\r\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\r\n *\r\n * See more info about locale codes here:\r\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\r\n *\r\n * For language codes you should use values defined by ISO 693-1. See it here\r\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\r\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\r\n * be used instead of the new code (he).\r\n *\r\n */\r\ngoog.LOCALE = goog.define('goog.LOCALE', 'en'); // default to en\r\n\r\n\r\n/**\r\n * @define {boolean} Whether this code is running on trusted sites.\r\n *\r\n * On untrusted sites, several native functions can be defined or overridden by\r\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\r\n * to false forces closure to use its own implementations when possible.\r\n *\r\n * If your JavaScript can be loaded by a third party site and you are wary about\r\n * relying on non-standard implementations, specify\r\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\r\n */\r\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether a project is expected to be running in strict mode.\r\n *\r\n * This define can be used to trigger alternate implementations compatible with\r\n * running in EcmaScript Strict mode or warn about unavailable functionality.\r\n * @see https://goo.gl/PudQ4y\r\n *\r\n */\r\ngoog.STRICT_MODE_COMPATIBLE = goog.define('goog.STRICT_MODE_COMPATIBLE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\r\n * be disallowed in the compilation unit.\r\n */\r\ngoog.DISALLOW_TEST_ONLY_CODE =\r\n goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\r\n * loading scripts via goog.require. @see appendScriptSrcNode_.\r\n */\r\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\r\n goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\r\n\r\n\r\n/**\r\n * Defines a namespace in Closure.\r\n *\r\n * A namespace may only be defined once in a codebase. It may be defined using\r\n * goog.provide() or goog.module().\r\n *\r\n * The presence of one or more goog.provide() calls in a file indicates\r\n * that the file defines the given objects/namespaces.\r\n * Provided symbols must not be null or undefined.\r\n *\r\n * In addition, goog.provide() creates the object stubs for a namespace\r\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\r\n * goog.foo.bar if it does not already exist).\r\n *\r\n * Build tools also scan for provide/require/module statements\r\n * to discern dependencies, build dependency files (see deps.js), etc.\r\n *\r\n * @see goog.require\r\n * @see goog.module\r\n * @param {string} name Namespace provided by this file in the form\r\n * \"goog.package.part\".\r\n */\r\ngoog.provide = function(name) {\r\n if (goog.isInModuleLoader_()) {\r\n throw new Error('goog.provide cannot be used within a module.');\r\n }\r\n if (!COMPILED) {\r\n // Ensure that the same namespace isn't provided twice.\r\n // A goog.module/goog.provide maps a goog.require to a specific file\r\n if (goog.isProvided_(name)) {\r\n throw new Error('Namespace \"' + name + '\" already declared.');\r\n }\r\n }\r\n\r\n goog.constructNamespace_(name);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} name Namespace provided by this file in the form\r\n * \"goog.package.part\".\r\n * @param {Object=} opt_obj The object to embed in the namespace.\r\n * @private\r\n */\r\ngoog.constructNamespace_ = function(name, opt_obj) {\r\n if (!COMPILED) {\r\n delete goog.implicitNamespaces_[name];\r\n\r\n var namespace = name;\r\n while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\r\n if (goog.getObjectByName(namespace)) {\r\n break;\r\n }\r\n goog.implicitNamespaces_[namespace] = true;\r\n }\r\n }\r\n\r\n goog.exportPath_(name, opt_obj);\r\n};\r\n\r\n\r\n/**\r\n * Returns CSP nonce, if set for any script tag.\r\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\r\n * Defaults to global context.\r\n * @return {string} CSP nonce or empty string if no nonce is present.\r\n */\r\ngoog.getScriptNonce = function(opt_window) {\r\n if (opt_window && opt_window != goog.global) {\r\n return goog.getScriptNonce_(opt_window.document);\r\n }\r\n if (goog.cspNonce_ === null) {\r\n goog.cspNonce_ = goog.getScriptNonce_(goog.global.document);\r\n }\r\n return goog.cspNonce_;\r\n};\r\n\r\n\r\n/**\r\n * According to the CSP3 spec a nonce must be a valid base64 string.\r\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\r\n * @private @const\r\n */\r\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\r\n\r\n\r\n/**\r\n * @private {?string}\r\n */\r\ngoog.cspNonce_ = null;\r\n\r\n\r\n/**\r\n * Returns CSP nonce, if set for any script tag.\r\n * @param {!Document} doc\r\n * @return {string} CSP nonce or empty string if no nonce is present.\r\n * @private\r\n */\r\ngoog.getScriptNonce_ = function(doc) {\r\n var script = doc.querySelector && doc.querySelector('script[nonce]');\r\n if (script) {\r\n // Try to get the nonce from the IDL property first, because browsers that\r\n // implement additional nonce protection features (currently only Chrome) to\r\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\r\n // See https://github.com/whatwg/html/issues/2369\r\n var nonce = script['nonce'] || script.getAttribute('nonce');\r\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\r\n return nonce;\r\n }\r\n }\r\n return '';\r\n};\r\n\r\n\r\n/**\r\n * Module identifier validation regexp.\r\n * Note: This is a conservative check, it is very possible to be more lenient,\r\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\r\n * restrictions are intended to leave the door open for using goog.require\r\n * with relative file paths rather than module identifiers.\r\n * @private\r\n */\r\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\r\n\r\n\r\n/**\r\n * Defines a module in Closure.\r\n *\r\n * Marks that this file must be loaded as a module and claims the namespace.\r\n *\r\n * A namespace may only be defined once in a codebase. It may be defined using\r\n * goog.provide() or goog.module().\r\n *\r\n * goog.module() has three requirements:\r\n * - goog.module may not be used in the same file as goog.provide.\r\n * - goog.module must be the first statement in the file.\r\n * - only one goog.module is allowed per file.\r\n *\r\n * When a goog.module annotated file is loaded, it is enclosed in\r\n * a strict function closure. This means that:\r\n * - any variables declared in a goog.module file are private to the file\r\n * (not global), though the compiler is expected to inline the module.\r\n * - The code must obey all the rules of \"strict\" JavaScript.\r\n * - the file will be marked as \"use strict\"\r\n *\r\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\r\n * itself. If declared symbols are desired, use\r\n * goog.module.declareLegacyNamespace().\r\n *\r\n *\r\n * See the public goog.module proposal: http://goo.gl/Va1hin\r\n *\r\n * @param {string} name Namespace provided by this file in the form\r\n * \"goog.package.part\", is expected but not required.\r\n * @return {void}\r\n */\r\ngoog.module = function(name) {\r\n if (!goog.isString(name) || !name ||\r\n name.search(goog.VALID_MODULE_RE_) == -1) {\r\n throw new Error('Invalid module identifier');\r\n }\r\n if (!goog.isInGoogModuleLoader_()) {\r\n throw new Error(\r\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\r\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\r\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\r\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\r\n 'module. For more info see: ' +\r\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\r\n }\r\n if (goog.moduleLoaderState_.moduleName) {\r\n throw new Error('goog.module may only be called once per module.');\r\n }\r\n\r\n // Store the module name for the loader.\r\n goog.moduleLoaderState_.moduleName = name;\r\n if (!COMPILED) {\r\n // Ensure that the same namespace isn't provided twice.\r\n // A goog.module/goog.provide maps a goog.require to a specific file\r\n if (goog.isProvided_(name)) {\r\n throw new Error('Namespace \"' + name + '\" already declared.');\r\n }\r\n delete goog.implicitNamespaces_[name];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {string} name The module identifier.\r\n * @return {?} The module exports for an already loaded module or null.\r\n *\r\n * Note: This is not an alternative to goog.require, it does not\r\n * indicate a hard dependency, instead it is used to indicate\r\n * an optional dependency or to access the exports of a module\r\n * that has already been loaded.\r\n * @suppress {missingProvide}\r\n */\r\ngoog.module.get = function(name) {\r\n\r\n return goog.module.getInternal_(name);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} name The module identifier.\r\n * @return {?} The module exports for an already loaded module or null.\r\n * @private\r\n */\r\ngoog.module.getInternal_ = function(name) {\r\n if (!COMPILED) {\r\n if (name in goog.loadedModules_) {\r\n return goog.loadedModules_[name].exports;\r\n } else if (!goog.implicitNamespaces_[name]) {\r\n var ns = goog.getObjectByName(name);\r\n return ns != null ? ns : null;\r\n }\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Types of modules the debug loader can load.\r\n * @enum {string}\r\n */\r\ngoog.ModuleType = {\r\n ES6: 'es6',\r\n GOOG: 'goog'\r\n};\r\n\r\n\r\n/**\r\n * @private {?{\r\n * moduleName: (string|undefined),\r\n * declareLegacyNamespace:boolean,\r\n * type: ?goog.ModuleType\r\n * }}\r\n */\r\ngoog.moduleLoaderState_ = null;\r\n\r\n\r\n/**\r\n * @private\r\n * @return {boolean} Whether a goog.module or an es6 module is currently being\r\n * initialized.\r\n */\r\ngoog.isInModuleLoader_ = function() {\r\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\r\n};\r\n\r\n\r\n/**\r\n * @private\r\n * @return {boolean} Whether a goog.module is currently being initialized.\r\n */\r\ngoog.isInGoogModuleLoader_ = function() {\r\n return !!goog.moduleLoaderState_ &&\r\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\r\n};\r\n\r\n\r\n/**\r\n * @private\r\n * @return {boolean} Whether an es6 module is currently being initialized.\r\n */\r\ngoog.isInEs6ModuleLoader_ = function() {\r\n var inLoader = !!goog.moduleLoaderState_ &&\r\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\r\n\r\n if (inLoader) {\r\n return true;\r\n }\r\n\r\n var jscomp = goog.global['$jscomp'];\r\n\r\n if (jscomp) {\r\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\r\n // that has some of the runtime, but not all of it. This can happen if\r\n // optimizations are turned on so the unused runtime is removed but renaming\r\n // and Closure pass are off (so $jscomp is still named $jscomp and the\r\n // goog.provide/require calls still exist).\r\n if (typeof jscomp.getCurrentModulePath != 'function') {\r\n return false;\r\n }\r\n\r\n // Bundled ES6 module.\r\n return !!jscomp.getCurrentModulePath();\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Provide the module's exports as a globally accessible object under the\r\n * module's declared name. This is intended to ease migration to goog.module\r\n * for files that have existing usages.\r\n * @suppress {missingProvide}\r\n */\r\ngoog.module.declareLegacyNamespace = function() {\r\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\r\n throw new Error(\r\n 'goog.module.declareLegacyNamespace must be called from ' +\r\n 'within a goog.module');\r\n }\r\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\r\n throw new Error(\r\n 'goog.module must be called prior to ' +\r\n 'goog.module.declareLegacyNamespace.');\r\n }\r\n goog.moduleLoaderState_.declareLegacyNamespace = true;\r\n};\r\n\r\n\r\n/**\r\n * Associates an ES6 module with a Closure module ID so that is available via\r\n * goog.require. The associated ID acts like a goog.module ID - it does not\r\n * create any global names, it is merely available via goog.require /\r\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\r\n * goog.module.get will return the entire module as if it was import *'d. This\r\n * allows Closure files to reference ES6 modules for the sake of migration.\r\n *\r\n * @param {string} namespace\r\n * @suppress {missingProvide}\r\n */\r\ngoog.declareModuleId = function(namespace) {\r\n if (!COMPILED) {\r\n if (!goog.isInEs6ModuleLoader_()) {\r\n throw new Error(\r\n 'goog.declareModuleId may only be called from ' +\r\n 'within an ES6 module');\r\n }\r\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\r\n throw new Error(\r\n 'goog.declareModuleId may only be called once per module.');\r\n }\r\n if (namespace in goog.loadedModules_) {\r\n throw new Error(\r\n 'Module with namespace \"' + namespace + '\" already exists.');\r\n }\r\n }\r\n if (goog.moduleLoaderState_) {\r\n // Not bundled - debug loading.\r\n goog.moduleLoaderState_.moduleName = namespace;\r\n } else {\r\n // Bundled - not debug loading, no module loader state.\r\n var jscomp = goog.global['$jscomp'];\r\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\r\n throw new Error(\r\n 'Module with namespace \"' + namespace +\r\n '\" has been loaded incorrectly.');\r\n }\r\n var exports = jscomp.require(jscomp.getCurrentModulePath());\r\n goog.loadedModules_[namespace] = {\r\n exports: exports,\r\n type: goog.ModuleType.ES6,\r\n moduleId: namespace\r\n };\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Marks that the current file should only be used for testing, and never for\r\n * live code in production.\r\n *\r\n * In the case of unit tests, the message may optionally be an exact namespace\r\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\r\n * provide (if not explicitly defined in the code).\r\n *\r\n * @param {string=} opt_message Optional message to add to the error that's\r\n * raised when used in production code.\r\n */\r\ngoog.setTestOnly = function(opt_message) {\r\n if (goog.DISALLOW_TEST_ONLY_CODE) {\r\n opt_message = opt_message || '';\r\n throw new Error(\r\n 'Importing test-only code into non-debug environment' +\r\n (opt_message ? ': ' + opt_message : '.'));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Forward declares a symbol. This is an indication to the compiler that the\r\n * symbol may be used in the source yet is not required and may not be provided\r\n * in compilation.\r\n *\r\n * The most common usage of forward declaration is code that takes a type as a\r\n * function parameter but does not need to require it. By forward declaring\r\n * instead of requiring, no hard dependency is made, and (if not required\r\n * elsewhere) the namespace may never be required and thus, not be pulled\r\n * into the JavaScript binary. If it is required elsewhere, it will be type\r\n * checked as normal.\r\n *\r\n * Before using goog.forwardDeclare, please read the documentation at\r\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\r\n * understand the options and tradeoffs when working with forward declarations.\r\n *\r\n * @param {string} name The namespace to forward declare in the form of\r\n * \"goog.package.part\".\r\n */\r\ngoog.forwardDeclare = function(name) {};\r\n\r\n\r\n/**\r\n * Forward declare type information. Used to assign types to goog.global\r\n * referenced object that would otherwise result in unknown type references\r\n * and thus block property disambiguation.\r\n */\r\ngoog.forwardDeclare('Document');\r\ngoog.forwardDeclare('HTMLScriptElement');\r\ngoog.forwardDeclare('XMLHttpRequest');\r\n\r\n\r\nif (!COMPILED) {\r\n /**\r\n * Check if the given name has been goog.provided. This will return false for\r\n * names that are available only as implicit namespaces.\r\n * @param {string} name name of the object to look for.\r\n * @return {boolean} Whether the name has been provided.\r\n * @private\r\n */\r\n goog.isProvided_ = function(name) {\r\n return (name in goog.loadedModules_) ||\r\n (!goog.implicitNamespaces_[name] &&\r\n goog.isDefAndNotNull(goog.getObjectByName(name)));\r\n };\r\n\r\n /**\r\n * Namespaces implicitly defined by goog.provide. For example,\r\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\r\n * 'goog.events' must be namespaces.\r\n *\r\n * @type {!Object<string, (boolean|undefined)>}\r\n * @private\r\n */\r\n goog.implicitNamespaces_ = {'goog.module': true};\r\n\r\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\r\n // here and because the existing module package has not been moved yet out of\r\n // the goog.module namespace. This satisifies both the debug loader and\r\n // ahead-of-time dependency management.\r\n}\r\n\r\n\r\n/**\r\n * Returns an object based on its fully qualified external name. The object\r\n * is not found if null or undefined. If you are using a compilation pass that\r\n * renames property names beware that using this function will not find renamed\r\n * properties.\r\n *\r\n * @param {string} name The fully qualified name.\r\n * @param {Object=} opt_obj The object within which to look; default is\r\n * |goog.global|.\r\n * @return {?} The value (object or primitive) or, if not found, null.\r\n */\r\ngoog.getObjectByName = function(name, opt_obj) {\r\n var parts = name.split('.');\r\n var cur = opt_obj || goog.global;\r\n for (var i = 0; i < parts.length; i++) {\r\n cur = cur[parts[i]];\r\n if (!goog.isDefAndNotNull(cur)) {\r\n return null;\r\n }\r\n }\r\n return cur;\r\n};\r\n\r\n\r\n/**\r\n * Globalizes a whole namespace, such as goog or goog.lang.\r\n *\r\n * @param {!Object} obj The namespace to globalize.\r\n * @param {Object=} opt_global The object to add the properties to.\r\n * @deprecated Properties may be explicitly exported to the global scope, but\r\n * this should no longer be done in bulk.\r\n */\r\ngoog.globalize = function(obj, opt_global) {\r\n var global = opt_global || goog.global;\r\n for (var x in obj) {\r\n global[x] = obj[x];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds a dependency from a file to the files it requires.\r\n * @param {string} relPath The path to the js file.\r\n * @param {!Array<string>} provides An array of strings with\r\n * the names of the objects this file provides.\r\n * @param {!Array<string>} requires An array of strings with\r\n * the names of the objects this file requires.\r\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\r\n * how the file must be loaded. The boolean 'true' is equivalent\r\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\r\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\r\n */\r\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\r\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\r\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\r\n }\r\n};\r\n\r\n\r\n\r\n\r\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\r\n// to do \"debug-mode\" development. The dependency system can sometimes be\r\n// confusing, as can the debug DOM loader's asynchronous nature.\r\n//\r\n// With the DOM loader, a call to goog.require() is not blocking -- the script\r\n// will not load until some point after the current script. If a namespace is\r\n// needed at runtime, it needs to be defined in a previous script, or loaded via\r\n// require() with its registered dependencies.\r\n//\r\n// User-defined namespaces may need their own deps file. For a reference on\r\n// creating a deps file, see:\r\n// Externally: https://developers.google.com/closure/library/docs/depswriter\r\n//\r\n// Because of legacy clients, the DOM loader can't be easily removed from\r\n// base.js. Work was done to make it disableable or replaceable for\r\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\r\n// for example). See bootstrap/ for more information.\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to enable the debug loader.\r\n *\r\n * If enabled, a call to goog.require() will attempt to load the namespace by\r\n * appending a script tag to the DOM (if the namespace has been registered).\r\n *\r\n * If disabled, goog.require() will simply assert that the namespace has been\r\n * provided (and depend on the fact that some outside tool correctly ordered\r\n * the script).\r\n */\r\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', true);\r\n\r\n\r\n/**\r\n * @param {string} msg\r\n * @private\r\n */\r\ngoog.logToConsole_ = function(msg) {\r\n if (goog.global.console) {\r\n goog.global.console['error'](msg);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Implements a system for the dynamic resolution of dependencies that works in\r\n * parallel with the BUILD system.\r\n *\r\n * Note that all calls to goog.require will be stripped by the compiler.\r\n *\r\n * @see goog.provide\r\n * @param {string} namespace Namespace (as was given in goog.provide,\r\n * goog.module, or goog.declareModuleId) in the form\r\n * \"goog.package.part\".\r\n * @return {?} If called within a goog.module or ES6 module file, the associated\r\n * namespace or module otherwise null.\r\n */\r\ngoog.require = function(namespace) {\r\n if (!COMPILED) {\r\n // Might need to lazy load on old IE.\r\n if (goog.ENABLE_DEBUG_LOADER) {\r\n goog.debugLoader_.requested(namespace);\r\n }\r\n\r\n // If the object already exists we do not need to do anything.\r\n if (goog.isProvided_(namespace)) {\r\n if (goog.isInModuleLoader_()) {\r\n return goog.module.getInternal_(namespace);\r\n }\r\n } else if (goog.ENABLE_DEBUG_LOADER) {\r\n var moduleLoaderState = goog.moduleLoaderState_;\r\n goog.moduleLoaderState_ = null;\r\n try {\r\n goog.debugLoader_.load_(namespace);\r\n } finally {\r\n goog.moduleLoaderState_ = moduleLoaderState;\r\n }\r\n }\r\n\r\n return null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Requires a symbol for its type information. This is an indication to the\r\n * compiler that the symbol may appear in type annotations, yet it is not\r\n * referenced at runtime.\r\n *\r\n * When called within a goog.module or ES6 module file, the return value may be\r\n * assigned to or destructured into a variable, but it may not be otherwise used\r\n * in code outside of a type annotation.\r\n *\r\n * Note that all calls to goog.requireType will be stripped by the compiler.\r\n *\r\n * @param {string} namespace Namespace (as was given in goog.provide,\r\n * goog.module, or goog.declareModuleId) in the form\r\n * \"goog.package.part\".\r\n * @return {?}\r\n */\r\ngoog.requireType = function(namespace) {\r\n // Return an empty object so that single-level destructuring of the return\r\n // value doesn't crash at runtime when using the debug loader. Multi-level\r\n // destructuring isn't supported.\r\n return {};\r\n};\r\n\r\n\r\n/**\r\n * Path for included scripts.\r\n * @type {string}\r\n */\r\ngoog.basePath = '';\r\n\r\n\r\n/**\r\n * A hook for overriding the base path.\r\n * @type {string|undefined}\r\n */\r\ngoog.global.CLOSURE_BASE_PATH;\r\n\r\n\r\n/**\r\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\r\n * deps files will attempt to be loaded.\r\n * @type {boolean|undefined}\r\n */\r\ngoog.global.CLOSURE_NO_DEPS;\r\n\r\n\r\n/**\r\n * A function to import a single script. This is meant to be overridden when\r\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\r\n * in the global scope so that it can be set before base.js is loaded, which\r\n * allows deps.js to be imported properly.\r\n *\r\n * The first parameter the script source, which is a relative URI. The second,\r\n * optional parameter is the script contents, in the event the script needed\r\n * transformation. It should return true if the script was imported, false\r\n * otherwise.\r\n * @type {(function(string, string=): boolean)|undefined}\r\n */\r\ngoog.global.CLOSURE_IMPORT_SCRIPT;\r\n\r\n\r\n/**\r\n * Null function used for default values of callbacks, etc.\r\n * @return {void} Nothing.\r\n */\r\ngoog.nullFunction = function() {};\r\n\r\n\r\n/**\r\n * When defining a class Foo with an abstract method bar(), you can do:\r\n * Foo.prototype.bar = goog.abstractMethod\r\n *\r\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\r\n * when bar() is invoked.\r\n *\r\n * @type {!Function}\r\n * @throws {Error} when invoked to indicate the method should be overridden.\r\n */\r\ngoog.abstractMethod = function() {\r\n throw new Error('unimplemented abstract method');\r\n};\r\n\r\n\r\n/**\r\n * Adds a `getInstance` static method that always returns the same\r\n * instance object.\r\n * @param {!Function} ctor The constructor for the class to add the static\r\n * method to.\r\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\r\n * but we don't have a better type to use here.\r\n */\r\ngoog.addSingletonGetter = function(ctor) {\r\n // instance_ is immediately set to prevent issues with sealed constructors\r\n // such as are encountered when a constructor is returned as the export object\r\n // of a goog.module in unoptimized code.\r\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\r\n /** @type {undefined|!Object} @suppress {underscore} */\r\n ctor.instance_ = undefined;\r\n ctor.getInstance = function() {\r\n if (ctor.instance_) {\r\n return ctor.instance_;\r\n }\r\n if (goog.DEBUG) {\r\n // NOTE: JSCompiler can't optimize away Array#push.\r\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\r\n }\r\n // Cast to avoid conformance violations that ctor.instance_ is unknown\r\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * All singleton classes that have been instantiated, for testing. Don't read\r\n * it directly, use the `goog.testing.singleton` module. The compiler\r\n * removes this variable if unused.\r\n * @type {!Array<!Function>}\r\n * @private\r\n */\r\ngoog.instantiatedSingletons_ = [];\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to load goog.modules using `eval` when using\r\n * the debug loader. This provides a better debugging experience as the\r\n * source is unmodified and can be edited using Chrome Workspaces or similar.\r\n * However in some environments the use of `eval` is banned\r\n * so we provide an alternative.\r\n */\r\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the exports of goog.modules should be sealed when\r\n * possible.\r\n */\r\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\r\n\r\n\r\n/**\r\n * The registry of initialized modules:\r\n * The module identifier or path to module exports map.\r\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\r\n */\r\ngoog.loadedModules_ = {};\r\n\r\n\r\n/**\r\n * True if the debug loader enabled and used.\r\n * @const {boolean}\r\n */\r\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\r\n\r\n\r\n/**\r\n * @define {string} How to decide whether to transpile. Valid values\r\n * are 'always', 'never', and 'detect'. The default ('detect') is to\r\n * use feature detection to determine which language levels need\r\n * transpilation.\r\n */\r\n// NOTE(sdh): we could expand this to accept a language level to bypass\r\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\r\n// would leave ES3 and ES5 files alone.\r\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\r\n\r\n/**\r\n * @define {boolean} If true assume that ES modules have already been\r\n * transpiled by the jscompiler (in the same way that transpile.js would\r\n * transpile them - to jscomp modules). Useful only for servers that wish to use\r\n * the debug loader and transpile server side. Thus this is only respected if\r\n * goog.TRANSPILE is \"never\".\r\n */\r\ngoog.ASSUME_ES_MODULES_TRANSPILED =\r\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\r\n\r\n\r\n/**\r\n * @define {string} If a file needs to be transpiled what the output language\r\n * should be. By default this is the highest language level this file detects\r\n * the current environment supports. Generally this flag should not be set, but\r\n * it could be useful to override. Example: If the current environment supports\r\n * ES6 then by default ES7+ files will be transpiled to ES6, unless this is\r\n * overridden.\r\n *\r\n * Valid values include: es3, es5, es6, es7, and es8. Anything not recognized\r\n * is treated as es3.\r\n *\r\n * Note that setting this value does not force transpilation. Just if\r\n * transpilation occurs this will be the output. So this is most useful when\r\n * goog.TRANSPILE is set to 'always' and then forcing the language level to be\r\n * something lower than what the environment detects.\r\n */\r\ngoog.TRANSPILE_TO_LANGUAGE = goog.define('goog.TRANSPILE_TO_LANGUAGE', '');\r\n\r\n\r\n/**\r\n * @define {string} Path to the transpiler. Executing the script at this\r\n * path (relative to base.js) should define a function $jscomp.transpile.\r\n */\r\ngoog.TRANSPILER = goog.define('goog.TRANSPILER', 'transpile.js');\r\n\r\n\r\n/**\r\n * @package {?boolean}\r\n * Visible for testing.\r\n */\r\ngoog.hasBadLetScoping = null;\r\n\r\n\r\n/**\r\n * @return {boolean}\r\n * @package Visible for testing.\r\n */\r\ngoog.useSafari10Workaround = function() {\r\n if (goog.hasBadLetScoping == null) {\r\n var hasBadLetScoping;\r\n try {\r\n hasBadLetScoping = !eval(\r\n '\"use strict\";' +\r\n 'let x = 1; function f() { return typeof x; };' +\r\n 'f() == \"number\";');\r\n } catch (e) {\r\n // Assume that ES6 syntax isn't supported.\r\n hasBadLetScoping = false;\r\n }\r\n goog.hasBadLetScoping = hasBadLetScoping;\r\n }\r\n return goog.hasBadLetScoping;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} moduleDef\r\n * @return {string}\r\n * @package Visible for testing.\r\n */\r\ngoog.workaroundSafari10EvalBug = function(moduleDef) {\r\n return '(function(){' + moduleDef +\r\n '\\n' + // Terminate any trailing single line comment.\r\n ';' + // Terminate any trailing expression.\r\n '})();\\n';\r\n};\r\n\r\n\r\n/**\r\n * @param {function(?):?|string} moduleDef The module definition.\r\n */\r\ngoog.loadModule = function(moduleDef) {\r\n // NOTE: we allow function definitions to be either in the from\r\n // of a string to eval (which keeps the original source intact) or\r\n // in a eval forbidden environment (CSP) we allow a function definition\r\n // which in its body must call `goog.module`, and return the exports\r\n // of the module.\r\n var previousState = goog.moduleLoaderState_;\r\n try {\r\n goog.moduleLoaderState_ = {\r\n moduleName: '',\r\n declareLegacyNamespace: false,\r\n type: goog.ModuleType.GOOG\r\n };\r\n var exports;\r\n if (goog.isFunction(moduleDef)) {\r\n exports = moduleDef.call(undefined, {});\r\n } else if (goog.isString(moduleDef)) {\r\n if (goog.useSafari10Workaround()) {\r\n moduleDef = goog.workaroundSafari10EvalBug(moduleDef);\r\n }\r\n\r\n exports = goog.loadModuleFromSource_.call(undefined, moduleDef);\r\n } else {\r\n throw new Error('Invalid module definition');\r\n }\r\n\r\n var moduleName = goog.moduleLoaderState_.moduleName;\r\n if (goog.isString(moduleName) && moduleName) {\r\n // Don't seal legacy namespaces as they may be used as a parent of\r\n // another namespace\r\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\r\n goog.constructNamespace_(moduleName, exports);\r\n } else if (\r\n goog.SEAL_MODULE_EXPORTS && Object.seal &&\r\n typeof exports == 'object' && exports != null) {\r\n Object.seal(exports);\r\n }\r\n\r\n var data = {\r\n exports: exports,\r\n type: goog.ModuleType.GOOG,\r\n moduleId: goog.moduleLoaderState_.moduleName\r\n };\r\n goog.loadedModules_[moduleName] = data;\r\n } else {\r\n throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\r\n }\r\n } finally {\r\n goog.moduleLoaderState_ = previousState;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @private @const\r\n */\r\ngoog.loadModuleFromSource_ = /** @type {function(string):?} */ (function() {\r\n // NOTE: we avoid declaring parameters or local variables here to avoid\r\n // masking globals or leaking values into the module definition.\r\n 'use strict';\r\n var exports = {};\r\n eval(arguments[0]);\r\n return exports;\r\n});\r\n\r\n\r\n/**\r\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\r\n * path components.\r\n * @param {string} path\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.normalizePath_ = function(path) {\r\n var components = path.split('/');\r\n var i = 0;\r\n while (i < components.length) {\r\n if (components[i] == '.') {\r\n components.splice(i, 1);\r\n } else if (\r\n i && components[i] == '..' && components[i - 1] &&\r\n components[i - 1] != '..') {\r\n components.splice(--i, 2);\r\n } else {\r\n i++;\r\n }\r\n }\r\n return components.join('/');\r\n};\r\n\r\n\r\n/**\r\n * Provides a hook for loading a file when using Closure's goog.require() API\r\n * with goog.modules. In particular this hook is provided to support Node.js.\r\n *\r\n * @type {(function(string):string)|undefined}\r\n */\r\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\r\n\r\n\r\n/**\r\n * Loads file by synchronous XHR. Should not be used in production environments.\r\n * @param {string} src Source URL.\r\n * @return {?string} File contents, or null if load failed.\r\n * @private\r\n */\r\ngoog.loadFileSync_ = function(src) {\r\n if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\r\n return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\r\n } else {\r\n try {\r\n /** @type {XMLHttpRequest} */\r\n var xhr = new goog.global['XMLHttpRequest']();\r\n xhr.open('get', src, false);\r\n xhr.send();\r\n // NOTE: Successful http: requests have a status of 200, but successful\r\n // file: requests may have a status of zero. Any other status, or a\r\n // thrown exception (particularly in case of file: requests) indicates\r\n // some sort of error, which we treat as a missing or unavailable file.\r\n return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\r\n } catch (err) {\r\n // No need to rethrow or log, since errors should show up on their own.\r\n return null;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Lazily retrieves the transpiler and applies it to the source.\r\n * @param {string} code JS code.\r\n * @param {string} path Path to the code.\r\n * @param {string} target Language level output.\r\n * @return {string} The transpiled code.\r\n * @private\r\n */\r\ngoog.transpile_ = function(code, path, target) {\r\n var jscomp = goog.global['$jscomp'];\r\n if (!jscomp) {\r\n goog.global['$jscomp'] = jscomp = {};\r\n }\r\n var transpile = jscomp.transpile;\r\n if (!transpile) {\r\n var transpilerPath = goog.basePath + goog.TRANSPILER;\r\n var transpilerCode = goog.loadFileSync_(transpilerPath);\r\n if (transpilerCode) {\r\n // This must be executed synchronously, since by the time we know we\r\n // need it, we're about to load and write the ES6 code synchronously,\r\n // so a normal script-tag load will be too slow. Wrapped in a function\r\n // so that code is eval'd in the global scope.\r\n (function() {\r\n eval(transpilerCode + '\\n//# sourceURL=' + transpilerPath);\r\n }).call(goog.global);\r\n // Even though the transpiler is optional, if $gwtExport is found, it's\r\n // a sign the transpiler was loaded and the $jscomp.transpile *should*\r\n // be there.\r\n if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] &&\r\n !goog.global['$gwtExport']['$jscomp']['transpile']) {\r\n throw new Error(\r\n 'The transpiler did not properly export the \"transpile\" ' +\r\n 'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport']));\r\n }\r\n // transpile.js only exports a single $jscomp function, transpile. We\r\n // grab just that and add it to the existing definition of $jscomp which\r\n // contains the polyfills.\r\n goog.global['$jscomp'].transpile =\r\n goog.global['$gwtExport']['$jscomp']['transpile'];\r\n jscomp = goog.global['$jscomp'];\r\n transpile = jscomp.transpile;\r\n }\r\n }\r\n if (!transpile) {\r\n // The transpiler is an optional component. If it's not available then\r\n // replace it with a pass-through function that simply logs.\r\n var suffix = ' requires transpilation but no transpiler was found.';\r\n transpile = jscomp.transpile = function(code, path) {\r\n // TODO(sdh): figure out some way to get this error to show up\r\n // in test results, noting that the failure may occur in many\r\n // different ways, including in loadModule() before the test\r\n // runner even comes up.\r\n goog.logToConsole_(path + suffix);\r\n return code;\r\n };\r\n }\r\n // Note: any transpilation errors/warnings will be logged to the console.\r\n return transpile(code, path, target);\r\n};\r\n\r\n//==============================================================================\r\n// Language Enhancements\r\n//==============================================================================\r\n\r\n\r\n/**\r\n * This is a \"fixed\" version of the typeof operator. It differs from the typeof\r\n * operator in such a way that null returns 'null' and arrays return 'array'.\r\n * @param {?} value The value to get the type of.\r\n * @return {string} The name of the type.\r\n */\r\ngoog.typeOf = function(value) {\r\n var s = typeof value;\r\n if (s == 'object') {\r\n if (value) {\r\n // Check these first, so we can avoid calling Object.prototype.toString if\r\n // possible.\r\n //\r\n // IE improperly marshals typeof across execution contexts, but a\r\n // cross-context object will still return false for \"instanceof Object\".\r\n if (value instanceof Array) {\r\n return 'array';\r\n } else if (value instanceof Object) {\r\n return s;\r\n }\r\n\r\n // HACK: In order to use an Object prototype method on the arbitrary\r\n // value, the compiler requires the value be cast to type Object,\r\n // even though the ECMA spec explicitly allows it.\r\n var className = Object.prototype.toString.call(\r\n /** @type {!Object} */ (value));\r\n // In Firefox 3.6, attempting to access iframe window objects' length\r\n // property throws an NS_ERROR_FAILURE, so we need to special-case it\r\n // here.\r\n if (className == '[object Window]') {\r\n return 'object';\r\n }\r\n\r\n // We cannot always use constructor == Array or instanceof Array because\r\n // different frames have different Array objects. In IE6, if the iframe\r\n // where the array was created is destroyed, the array loses its\r\n // prototype. Then dereferencing val.splice here throws an exception, so\r\n // we can't use goog.isFunction. Calling typeof directly returns 'unknown'\r\n // so that will work. In this case, this function will return false and\r\n // most array functions will still work because the array is still\r\n // array-like (supports length and []) even though it has lost its\r\n // prototype.\r\n // Mark Miller noticed that Object.prototype.toString\r\n // allows access to the unforgeable [[Class]] property.\r\n // 15.2.4.2 Object.prototype.toString ( )\r\n // When the toString method is called, the following steps are taken:\r\n // 1. Get the [[Class]] property of this object.\r\n // 2. Compute a string value by concatenating the three strings\r\n // \"[object \", Result(1), and \"]\".\r\n // 3. Return Result(2).\r\n // and this behavior survives the destruction of the execution context.\r\n if ((className == '[object Array]' ||\r\n // In IE all non value types are wrapped as objects across window\r\n // boundaries (not iframe though) so we have to do object detection\r\n // for this edge case.\r\n typeof value.length == 'number' &&\r\n typeof value.splice != 'undefined' &&\r\n typeof value.propertyIsEnumerable != 'undefined' &&\r\n !value.propertyIsEnumerable('splice')\r\n\r\n )) {\r\n return 'array';\r\n }\r\n // HACK: There is still an array case that fails.\r\n // function ArrayImpostor() {}\r\n // ArrayImpostor.prototype = [];\r\n // var impostor = new ArrayImpostor;\r\n // this can be fixed by getting rid of the fast path\r\n // (value instanceof Array) and solely relying on\r\n // (value && Object.prototype.toString.vall(value) === '[object Array]')\r\n // but that would require many more function calls and is not warranted\r\n // unless closure code is receiving objects from untrusted sources.\r\n\r\n // IE in cross-window calls does not correctly marshal the function type\r\n // (it appears just as an object) so we cannot use just typeof val ==\r\n // 'function'. However, if the object has a call property, it is a\r\n // function.\r\n if ((className == '[object Function]' ||\r\n typeof value.call != 'undefined' &&\r\n typeof value.propertyIsEnumerable != 'undefined' &&\r\n !value.propertyIsEnumerable('call'))) {\r\n return 'function';\r\n }\r\n\r\n } else {\r\n return 'null';\r\n }\r\n\r\n } else if (s == 'function' && typeof value.call == 'undefined') {\r\n // In Safari typeof nodeList returns 'function', and on Firefox typeof\r\n // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We\r\n // would like to return object for those and we can detect an invalid\r\n // function by making sure that the function object has a call method.\r\n return 'object';\r\n }\r\n return s;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is null.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is null.\r\n */\r\ngoog.isNull = function(val) {\r\n return val === null;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is defined and not null.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is defined and not null.\r\n */\r\ngoog.isDefAndNotNull = function(val) {\r\n // Note that undefined == null.\r\n return val != null;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is an array.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is an array.\r\n */\r\ngoog.isArray = function(val) {\r\n return goog.typeOf(val) == 'array';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the object looks like an array. To qualify as array like\r\n * the value needs to be either a NodeList or an object with a Number length\r\n * property. Note that for this function neither strings nor functions are\r\n * considered \"array-like\".\r\n *\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is an array.\r\n */\r\ngoog.isArrayLike = function(val) {\r\n var type = goog.typeOf(val);\r\n // We do not use goog.isObject here in order to exclude function values.\r\n return type == 'array' || type == 'object' && typeof val.length == 'number';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the object looks like a Date. To qualify as Date-like the\r\n * value needs to be an object and have a getFullYear() function.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a like a Date.\r\n */\r\ngoog.isDateLike = function(val) {\r\n return goog.isObject(val) && typeof val.getFullYear == 'function';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is a function.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is a function.\r\n */\r\ngoog.isFunction = function(val) {\r\n return goog.typeOf(val) == 'function';\r\n};\r\n\r\n\r\n/**\r\n * Returns true if the specified value is an object. This includes arrays and\r\n * functions.\r\n * @param {?} val Variable to test.\r\n * @return {boolean} Whether variable is an object.\r\n */\r\ngoog.isObject = function(val) {\r\n var type = typeof val;\r\n return type == 'object' && val != null || type == 'function';\r\n // return Object(val) === val also works, but is slower, especially if val is\r\n // not an object.\r\n};\r\n\r\n\r\n/**\r\n * Gets a unique ID for an object. This mutates the object so that further calls\r\n * with the same object as a parameter returns the same value. The unique ID is\r\n * guaranteed to be unique across the current session amongst objects that are\r\n * passed into `getUid`. There is no guarantee that the ID is unique or\r\n * consistent across sessions. It is unsafe to generate unique ID for function\r\n * prototypes.\r\n *\r\n * @param {Object} obj The object to get the unique ID for.\r\n * @return {number} The unique ID for the object.\r\n */\r\ngoog.getUid = function(obj) {\r\n // TODO(arv): Make the type stricter, do not accept null.\r\n\r\n // In Opera window.hasOwnProperty exists but always returns false so we avoid\r\n // using it. As a consequence the unique ID generated for BaseClass.prototype\r\n // and SubClass.prototype will be the same.\r\n return obj[goog.UID_PROPERTY_] ||\r\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\r\n};\r\n\r\n\r\n/**\r\n * Whether the given object is already assigned a unique ID.\r\n *\r\n * This does not modify the object.\r\n *\r\n * @param {!Object} obj The object to check.\r\n * @return {boolean} Whether there is an assigned unique id for the object.\r\n */\r\ngoog.hasUid = function(obj) {\r\n return !!obj[goog.UID_PROPERTY_];\r\n};\r\n\r\n\r\n/**\r\n * Removes the unique ID from an object. This is useful if the object was\r\n * previously mutated using `goog.getUid` in which case the mutation is\r\n * undone.\r\n * @param {Object} obj The object to remove the unique ID field from.\r\n */\r\ngoog.removeUid = function(obj) {\r\n // TODO(arv): Make the type stricter, do not accept null.\r\n\r\n // In IE, DOM nodes are not instances of Object and throw an exception if we\r\n // try to delete. Instead we try to use removeAttribute.\r\n if (obj !== null && 'removeAttribute' in obj) {\r\n obj.removeAttribute(goog.UID_PROPERTY_);\r\n }\r\n\r\n try {\r\n delete obj[goog.UID_PROPERTY_];\r\n } catch (ex) {\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Name for unique ID property. Initialized in a way to help avoid collisions\r\n * with other closure JavaScript on the same page.\r\n * @type {string}\r\n * @private\r\n */\r\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\r\n\r\n\r\n/**\r\n * Counter for UID.\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.uidCounter_ = 0;\r\n\r\n\r\n/**\r\n * Adds a hash code field to an object. The hash code is unique for the\r\n * given object.\r\n * @param {Object} obj The object to get the hash code for.\r\n * @return {number} The hash code for the object.\r\n * @deprecated Use goog.getUid instead.\r\n */\r\ngoog.getHashCode = goog.getUid;\r\n\r\n\r\n/**\r\n * Removes the hash code field from an object.\r\n * @param {Object} obj The object to remove the field from.\r\n * @deprecated Use goog.removeUid instead.\r\n */\r\ngoog.removeHashCode = goog.removeUid;\r\n\r\n\r\n/**\r\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\r\n * arrays will be cloned recursively.\r\n *\r\n * WARNINGS:\r\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\r\n * refer to themselves will cause infinite recursion.\r\n *\r\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\r\n * UIDs created by <code>getUid</code> into cloned results.\r\n *\r\n * @param {*} obj The value to clone.\r\n * @return {*} A clone of the input value.\r\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\r\n */\r\ngoog.cloneObject = function(obj) {\r\n var type = goog.typeOf(obj);\r\n if (type == 'object' || type == 'array') {\r\n if (typeof obj.clone === 'function') {\r\n return obj.clone();\r\n }\r\n var clone = type == 'array' ? [] : {};\r\n for (var key in obj) {\r\n clone[key] = goog.cloneObject(obj[key]);\r\n }\r\n return clone;\r\n }\r\n\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * A native implementation of goog.bind.\r\n * @param {?function(this:T, ...)} fn A function to partially apply.\r\n * @param {T} selfObj Specifies the object which this should point to when the\r\n * function is run.\r\n * @param {...*} var_args Additional arguments that are partially applied to the\r\n * function.\r\n * @return {!Function} A partially-applied form of the function goog.bind() was\r\n * invoked as a method of.\r\n * @template T\r\n * @private\r\n */\r\ngoog.bindNative_ = function(fn, selfObj, var_args) {\r\n return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\r\n};\r\n\r\n\r\n/**\r\n * A pure-JS implementation of goog.bind.\r\n * @param {?function(this:T, ...)} fn A function to partially apply.\r\n * @param {T} selfObj Specifies the object which this should point to when the\r\n * function is run.\r\n * @param {...*} var_args Additional arguments that are partially applied to the\r\n * function.\r\n * @return {!Function} A partially-applied form of the function goog.bind() was\r\n * invoked as a method of.\r\n * @template T\r\n * @private\r\n */\r\ngoog.bindJs_ = function(fn, selfObj, var_args) {\r\n if (!fn) {\r\n throw new Error();\r\n }\r\n\r\n if (arguments.length > 2) {\r\n var boundArgs = Array.prototype.slice.call(arguments, 2);\r\n return function() {\r\n // Prepend the bound arguments to the current arguments.\r\n var newArgs = Array.prototype.slice.call(arguments);\r\n Array.prototype.unshift.apply(newArgs, boundArgs);\r\n return fn.apply(selfObj, newArgs);\r\n };\r\n\r\n } else {\r\n return function() {\r\n return fn.apply(selfObj, arguments);\r\n };\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Partially applies this function to a particular 'this object' and zero or\r\n * more arguments. The result is a new function with some arguments of the first\r\n * function pre-filled and the value of this 'pre-specified'.\r\n *\r\n * Remaining arguments specified at call-time are appended to the pre-specified\r\n * ones.\r\n *\r\n * Also see: {@link #partial}.\r\n *\r\n * Usage:\r\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\r\n * barMethBound('arg3', 'arg4');</pre>\r\n *\r\n * @param {?function(this:T, ...)} fn A function to partially apply.\r\n * @param {T} selfObj Specifies the object which this should point to when the\r\n * function is run.\r\n * @param {...*} var_args Additional arguments that are partially applied to the\r\n * function.\r\n * @return {!Function} A partially-applied form of the function goog.bind() was\r\n * invoked as a method of.\r\n * @template T\r\n * @suppress {deprecated} See above.\r\n */\r\ngoog.bind = function(fn, selfObj, var_args) {\r\n // TODO(nicksantos): narrow the type signature.\r\n if (Function.prototype.bind &&\r\n // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\r\n // extension environment. This means that for Chrome extensions, they get\r\n // the implementation of Function.prototype.bind that calls goog.bind\r\n // instead of the native one. Even worse, we don't want to introduce a\r\n // circular dependency between goog.bind and Function.prototype.bind, so\r\n // we have to hack this to make sure it works correctly.\r\n Function.prototype.bind.toString().indexOf('native code') != -1) {\r\n goog.bind = goog.bindNative_;\r\n } else {\r\n goog.bind = goog.bindJs_;\r\n }\r\n return goog.bind.apply(null, arguments);\r\n};\r\n\r\n\r\n/**\r\n * Like goog.bind(), except that a 'this object' is not required. Useful when\r\n * the target function is already bound.\r\n *\r\n * Usage:\r\n * var g = goog.partial(f, arg1, arg2);\r\n * g(arg3, arg4);\r\n *\r\n * @param {Function} fn A function to partially apply.\r\n * @param {...*} var_args Additional arguments that are partially applied to fn.\r\n * @return {!Function} A partially-applied form of the function goog.partial()\r\n * was invoked as a method of.\r\n */\r\ngoog.partial = function(fn, var_args) {\r\n var args = Array.prototype.slice.call(arguments, 1);\r\n return function() {\r\n // Clone the array (with slice()) and append additional arguments\r\n // to the existing arguments.\r\n var newArgs = args.slice();\r\n newArgs.push.apply(newArgs, arguments);\r\n return fn.apply(/** @type {?} */ (this), newArgs);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Copies all the members of a source object to a target object. This method\r\n * does not work on all browsers for all objects that contain keys such as\r\n * toString or hasOwnProperty. Use goog.object.extend for this purpose.\r\n * @param {Object} target Target.\r\n * @param {Object} source Source.\r\n */\r\ngoog.mixin = function(target, source) {\r\n for (var x in source) {\r\n target[x] = source[x];\r\n }\r\n\r\n // For IE7 or lower, the for-in-loop does not contain any properties that are\r\n // not enumerable on the prototype object (for example, isPrototypeOf from\r\n // Object.prototype) but also it will not include 'replace' on objects that\r\n // extend String and change 'replace' (not that it is common for anyone to\r\n // extend anything except Object).\r\n};\r\n\r\n\r\n/**\r\n * @return {number} An integer value representing the number of milliseconds\r\n * between midnight, January 1, 1970 and the current time.\r\n */\r\ngoog.now = (goog.TRUSTED_SITE && Date.now) || (function() {\r\n // Unary plus operator converts its operand to a number which in\r\n // the case of\r\n // a date is done by calling getTime().\r\n return +new Date();\r\n });\r\n\r\n\r\n/**\r\n * Evals JavaScript in the global scope. In IE this uses execScript, other\r\n * browsers use goog.global.eval. If goog.global.eval does not evaluate in the\r\n * global scope (for example, in Safari), appends a script tag instead.\r\n * Throws an exception if neither execScript or eval is defined.\r\n * @param {string} script JavaScript string.\r\n */\r\ngoog.globalEval = function(script) {\r\n if (goog.global.execScript) {\r\n goog.global.execScript(script, 'JavaScript');\r\n } else if (goog.global.eval) {\r\n // Test to see if eval works\r\n if (goog.evalWorksForGlobals_ == null) {\r\n try {\r\n goog.global.eval('var _evalTest_ = 1;');\r\n } catch (ignore) {\r\n }\r\n if (typeof goog.global['_evalTest_'] != 'undefined') {\r\n try {\r\n delete goog.global['_evalTest_'];\r\n } catch (ignore) {\r\n // Microsoft edge fails the deletion above in strict mode.\r\n }\r\n goog.evalWorksForGlobals_ = true;\r\n } else {\r\n goog.evalWorksForGlobals_ = false;\r\n }\r\n }\r\n\r\n if (goog.evalWorksForGlobals_) {\r\n goog.global.eval(script);\r\n } else {\r\n /** @type {!Document} */\r\n var doc = goog.global.document;\r\n var scriptElt =\r\n /** @type {!HTMLScriptElement} */ (doc.createElement('SCRIPT'));\r\n scriptElt.type = 'text/javascript';\r\n scriptElt.defer = false;\r\n // Note(user): can't use .innerHTML since \"t('<test>')\" will fail and\r\n // .text doesn't work in Safari 2. Therefore we append a text node.\r\n scriptElt.appendChild(doc.createTextNode(script));\r\n doc.head.appendChild(scriptElt);\r\n doc.head.removeChild(scriptElt);\r\n }\r\n } else {\r\n throw new Error('goog.globalEval not available');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Indicates whether or not we can call 'eval' directly to eval code in the\r\n * global scope. Set to a Boolean by the first call to goog.globalEval (which\r\n * empirically tests whether eval works for globals). @see goog.globalEval\r\n * @type {?boolean}\r\n * @private\r\n */\r\ngoog.evalWorksForGlobals_ = null;\r\n\r\n\r\n/**\r\n * Optional map of CSS class names to obfuscated names used with\r\n * goog.getCssName().\r\n * @private {!Object<string, string>|undefined}\r\n * @see goog.setCssNameMapping\r\n */\r\ngoog.cssNameMapping_;\r\n\r\n\r\n/**\r\n * Optional obfuscation style for CSS class names. Should be set to either\r\n * 'BY_WHOLE' or 'BY_PART' if defined.\r\n * @type {string|undefined}\r\n * @private\r\n * @see goog.setCssNameMapping\r\n */\r\ngoog.cssNameMappingStyle_;\r\n\r\n\r\n\r\n/**\r\n * A hook for modifying the default behavior goog.getCssName. The function\r\n * if present, will receive the standard output of the goog.getCssName as\r\n * its input.\r\n *\r\n * @type {(function(string):string)|undefined}\r\n */\r\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\r\n\r\n\r\n/**\r\n * Handles strings that are intended to be used as CSS class names.\r\n *\r\n * This function works in tandem with @see goog.setCssNameMapping.\r\n *\r\n * Without any mapping set, the arguments are simple joined with a hyphen and\r\n * passed through unaltered.\r\n *\r\n * When there is a mapping, there are two possible styles in which these\r\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\r\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\r\n * style, the full css name is looked up in the map directly. If a rewrite is\r\n * not specified by the map, the compiler will output a warning.\r\n *\r\n * When the mapping is passed to the compiler, it will replace calls to\r\n * goog.getCssName with the strings from the mapping, e.g.\r\n * var x = goog.getCssName('foo');\r\n * var y = goog.getCssName(this.baseClass, 'active');\r\n * becomes:\r\n * var x = 'foo';\r\n * var y = this.baseClass + '-active';\r\n *\r\n * If one argument is passed it will be processed, if two are passed only the\r\n * modifier will be processed, as it is assumed the first argument was generated\r\n * as a result of calling goog.getCssName.\r\n *\r\n * @param {string} className The class name.\r\n * @param {string=} opt_modifier A modifier to be appended to the class name.\r\n * @return {string} The class name or the concatenation of the class name and\r\n * the modifier.\r\n */\r\ngoog.getCssName = function(className, opt_modifier) {\r\n // String() is used for compatibility with compiled soy where the passed\r\n // className can be non-string objects.\r\n if (String(className).charAt(0) == '.') {\r\n throw new Error(\r\n 'className passed in goog.getCssName must not start with \".\".' +\r\n ' You passed: ' + className);\r\n }\r\n\r\n var getMapping = function(cssName) {\r\n return goog.cssNameMapping_[cssName] || cssName;\r\n };\r\n\r\n var renameByParts = function(cssName) {\r\n // Remap all the parts individually.\r\n var parts = cssName.split('-');\r\n var mapped = [];\r\n for (var i = 0; i < parts.length; i++) {\r\n mapped.push(getMapping(parts[i]));\r\n }\r\n return mapped.join('-');\r\n };\r\n\r\n var rename;\r\n if (goog.cssNameMapping_) {\r\n rename =\r\n goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\r\n } else {\r\n rename = function(a) {\r\n return a;\r\n };\r\n }\r\n\r\n var result =\r\n opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\r\n\r\n // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\r\n // processing of the class name.\r\n if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\r\n return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\r\n }\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Sets the map to check when returning a value from goog.getCssName(). Example:\r\n * <pre>\r\n * goog.setCssNameMapping({\r\n * \"goog\": \"a\",\r\n * \"disabled\": \"b\",\r\n * });\r\n *\r\n * var x = goog.getCssName('goog');\r\n * // The following evaluates to: \"a a-b\".\r\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\r\n * </pre>\r\n * When declared as a map of string literals to string literals, the JSCompiler\r\n * will replace all calls to goog.getCssName() using the supplied map if the\r\n * --process_closure_primitives flag is set.\r\n *\r\n * @param {!Object} mapping A map of strings to strings where keys are possible\r\n * arguments to goog.getCssName() and values are the corresponding values\r\n * that should be returned.\r\n * @param {string=} opt_style The style of css name mapping. There are two valid\r\n * options: 'BY_PART', and 'BY_WHOLE'.\r\n * @see goog.getCssName for a description.\r\n */\r\ngoog.setCssNameMapping = function(mapping, opt_style) {\r\n goog.cssNameMapping_ = mapping;\r\n goog.cssNameMappingStyle_ = opt_style;\r\n};\r\n\r\n\r\n/**\r\n * To use CSS renaming in compiled mode, one of the input files should have a\r\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\r\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\r\n * mode, JavaScript code should be loaded before this base.js file that declares\r\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\r\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\r\n * are made in uncompiled mode.\r\n *\r\n * A hook for overriding the CSS name mapping.\r\n * @type {!Object<string, string>|undefined}\r\n */\r\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\r\n\r\n\r\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\r\n // This does not call goog.setCssNameMapping() because the JSCompiler\r\n // requires that goog.setCssNameMapping() be called with an object literal.\r\n goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\r\n}\r\n\r\n\r\n/**\r\n * Gets a localized message.\r\n *\r\n * This function is a compiler primitive. If you give the compiler a localized\r\n * message bundle, it will replace the string at compile-time with a localized\r\n * version, and expand goog.getMsg call to a concatenated string.\r\n *\r\n * Messages must be initialized in the form:\r\n * <code>\r\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\r\n * </code>\r\n *\r\n * This function produces a string which should be treated as plain text. Use\r\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\r\n * produce SafeHtml.\r\n *\r\n * @param {string} str Translatable string, places holders in the form {$foo}.\r\n * @param {Object<string, string>=} opt_values Maps place holder name to value.\r\n * @return {string} message with placeholders filled.\r\n */\r\ngoog.getMsg = function(str, opt_values) {\r\n if (opt_values) {\r\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\r\n return (opt_values != null && key in opt_values) ? opt_values[key] :\r\n match;\r\n });\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Gets a localized message. If the message does not have a translation, gives a\r\n * fallback message.\r\n *\r\n * This is useful when introducing a new message that has not yet been\r\n * translated into all languages.\r\n *\r\n * This function is a compiler primitive. Must be used in the form:\r\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\r\n * where MSG_A and MSG_B were initialized with goog.getMsg.\r\n *\r\n * @param {string} a The preferred message.\r\n * @param {string} b The fallback message.\r\n * @return {string} The best translated message.\r\n */\r\ngoog.getMsgWithFallback = function(a, b) {\r\n return a;\r\n};\r\n\r\n\r\n/**\r\n * Exposes an unobfuscated global namespace path for the given object.\r\n * Note that fields of the exported object *will* be obfuscated, unless they are\r\n * exported in turn via this function or goog.exportProperty.\r\n *\r\n * Also handy for making public items that are defined in anonymous closures.\r\n *\r\n * ex. goog.exportSymbol('public.path.Foo', Foo);\r\n *\r\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\r\n * public.path.Foo.staticFunction();\r\n *\r\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\r\n * Foo.prototype.myMethod);\r\n * new public.path.Foo().myMethod();\r\n *\r\n * @param {string} publicPath Unobfuscated name to export.\r\n * @param {*} object Object the name should point to.\r\n * @param {Object=} opt_objectToExportTo The object to add the path to; default\r\n * is goog.global.\r\n */\r\ngoog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {\r\n goog.exportPath_(publicPath, object, opt_objectToExportTo);\r\n};\r\n\r\n\r\n/**\r\n * Exports a property unobfuscated into the object's namespace.\r\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\r\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\r\n * @param {Object} object Object whose static property is being exported.\r\n * @param {string} publicName Unobfuscated name to export.\r\n * @param {*} symbol Object the name should point to.\r\n */\r\ngoog.exportProperty = function(object, publicName, symbol) {\r\n object[publicName] = symbol;\r\n};\r\n\r\n\r\n/**\r\n * Inherit the prototype methods from one constructor into another.\r\n *\r\n * Usage:\r\n * <pre>\r\n * function ParentClass(a, b) { }\r\n * ParentClass.prototype.foo = function(a) { };\r\n *\r\n * function ChildClass(a, b, c) {\r\n * ChildClass.base(this, 'constructor', a, b);\r\n * }\r\n * goog.inherits(ChildClass, ParentClass);\r\n *\r\n * var child = new ChildClass('a', 'b', 'see');\r\n * child.foo(); // This works.\r\n * </pre>\r\n *\r\n * @param {!Function} childCtor Child class.\r\n * @param {!Function} parentCtor Parent class.\r\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\r\n * Function.\r\n */\r\ngoog.inherits = function(childCtor, parentCtor) {\r\n /** @constructor */\r\n function tempCtor() {}\r\n tempCtor.prototype = parentCtor.prototype;\r\n childCtor.superClass_ = parentCtor.prototype;\r\n childCtor.prototype = new tempCtor();\r\n /** @override */\r\n childCtor.prototype.constructor = childCtor;\r\n\r\n /**\r\n * Calls superclass constructor/method.\r\n *\r\n * This function is only available if you use goog.inherits to\r\n * express inheritance relationships between classes.\r\n *\r\n * NOTE: This is a replacement for goog.base and for superClass_\r\n * property defined in childCtor.\r\n *\r\n * @param {!Object} me Should always be \"this\".\r\n * @param {string} methodName The method name to call. Calling\r\n * superclass constructor can be done with the special string\r\n * 'constructor'.\r\n * @param {...*} var_args The arguments to pass to superclass\r\n * method/constructor.\r\n * @return {*} The return value of the superclass method/constructor.\r\n */\r\n childCtor.base = function(me, methodName, var_args) {\r\n // Copying using loop to avoid deop due to passing arguments object to\r\n // function. This is faster in many JS engines as of late 2014.\r\n var args = new Array(arguments.length - 2);\r\n for (var i = 2; i < arguments.length; i++) {\r\n args[i - 2] = arguments[i];\r\n }\r\n return parentCtor.prototype[methodName].apply(me, args);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Call up to the superclass.\r\n *\r\n * If this is called from a constructor, then this calls the superclass\r\n * constructor with arguments 1-N.\r\n *\r\n * If this is called from a prototype method, then you must pass the name of the\r\n * method as the second argument to this function. If you do not, you will get a\r\n * runtime error. This calls the superclass' method with arguments 2-N.\r\n *\r\n * This function only works if you use goog.inherits to express inheritance\r\n * relationships between your classes.\r\n *\r\n * This function is a compiler primitive. At compile-time, the compiler will do\r\n * macro expansion to remove a lot of the extra overhead that this function\r\n * introduces. The compiler will also enforce a lot of the assumptions that this\r\n * function makes, and treat it as a compiler error if you break them.\r\n *\r\n * @param {!Object} me Should always be \"this\".\r\n * @param {*=} opt_methodName The method name if calling a super method.\r\n * @param {...*} var_args The rest of the arguments.\r\n * @return {*} The return value of the superclass method.\r\n * @suppress {es5Strict} This method can not be used in strict mode, but\r\n * all Closure Library consumers must depend on this file.\r\n * @deprecated goog.base is not strict mode compatible. Prefer the static\r\n * \"base\" method added to the constructor by goog.inherits\r\n * or ES6 classes and the \"super\" keyword.\r\n */\r\ngoog.base = function(me, opt_methodName, var_args) {\r\n var caller = arguments.callee.caller;\r\n\r\n if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {\r\n throw new Error(\r\n 'arguments.caller not defined. goog.base() cannot be used ' +\r\n 'with strict mode code. See ' +\r\n 'http://www.ecma-international.org/ecma-262/5.1/#sec-C');\r\n }\r\n\r\n if (typeof caller.superClass_ !== 'undefined') {\r\n // Copying using loop to avoid deop due to passing arguments object to\r\n // function. This is faster in many JS engines as of late 2014.\r\n var ctorArgs = new Array(arguments.length - 1);\r\n for (var i = 1; i < arguments.length; i++) {\r\n ctorArgs[i - 1] = arguments[i];\r\n }\r\n // This is a constructor. Call the superclass constructor.\r\n return /** @type {!Function} */ (caller.superClass_)\r\n .constructor.apply(me, ctorArgs);\r\n }\r\n\r\n if (typeof opt_methodName != 'string' && typeof opt_methodName != 'symbol') {\r\n throw new Error(\r\n 'method names provided to goog.base must be a string or a symbol');\r\n }\r\n\r\n // Copying using loop to avoid deop due to passing arguments object to\r\n // function. This is faster in many JS engines as of late 2014.\r\n var args = new Array(arguments.length - 2);\r\n for (var i = 2; i < arguments.length; i++) {\r\n args[i - 2] = arguments[i];\r\n }\r\n var foundCaller = false;\r\n for (var ctor = me.constructor; ctor;\r\n ctor = ctor.superClass_ && ctor.superClass_.constructor) {\r\n if (ctor.prototype[opt_methodName] === caller) {\r\n foundCaller = true;\r\n } else if (foundCaller) {\r\n return ctor.prototype[opt_methodName].apply(me, args);\r\n }\r\n }\r\n\r\n // If we did not find the caller in the prototype chain, then one of two\r\n // things happened:\r\n // 1) The caller is an instance method.\r\n // 2) This method was not called by the right caller.\r\n if (me[opt_methodName] === caller) {\r\n return me.constructor.prototype[opt_methodName].apply(me, args);\r\n } else {\r\n throw new Error(\r\n 'goog.base called from a method of one name ' +\r\n 'to a method of a different name');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Allow for aliasing within scope functions. This function exists for\r\n * uncompiled code - in compiled code the calls will be inlined and the aliases\r\n * applied. In uncompiled code the function is simply run since the aliases as\r\n * written are valid JavaScript.\r\n *\r\n *\r\n * @param {function()} fn Function to call. This function can contain aliases\r\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\r\n * (e.g. \"var Timer = goog.Timer\").\r\n */\r\ngoog.scope = function(fn) {\r\n if (goog.isInModuleLoader_()) {\r\n throw new Error('goog.scope is not supported within a module.');\r\n }\r\n fn.call(goog.global);\r\n};\r\n\r\n\r\n/*\r\n * To support uncompiled, strict mode bundles that use eval to divide source\r\n * like so:\r\n * eval('someSource;//# sourceUrl sourcefile.js');\r\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\r\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\r\n * be defined externally.\r\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\r\n * extern generation when that compiler option is enabled.\r\n */\r\nif (!COMPILED) {\r\n goog.global['COMPILED'] = COMPILED;\r\n}\r\n\r\n\r\n//==============================================================================\r\n// goog.defineClass implementation\r\n//==============================================================================\r\n\r\n\r\n/**\r\n * Creates a restricted form of a Closure \"class\":\r\n * - from the compiler's perspective, the instance returned from the\r\n * constructor is sealed (no new properties may be added). This enables\r\n * better checks.\r\n * - the compiler will rewrite this definition to a form that is optimal\r\n * for type checking and optimization (initially this will be a more\r\n * traditional form).\r\n *\r\n * @param {Function} superClass The superclass, Object or null.\r\n * @param {goog.defineClass.ClassDescriptor} def\r\n * An object literal describing\r\n * the class. It may have the following properties:\r\n * \"constructor\": the constructor function\r\n * \"statics\": an object literal containing methods to add to the constructor\r\n * as \"static\" methods or a function that will receive the constructor\r\n * function as its only parameter to which static properties can\r\n * be added.\r\n * all other properties are added to the prototype.\r\n * @return {!Function} The class constructor.\r\n */\r\ngoog.defineClass = function(superClass, def) {\r\n // TODO(johnlenz): consider making the superClass an optional parameter.\r\n var constructor = def.constructor;\r\n var statics = def.statics;\r\n // Wrap the constructor prior to setting up the prototype and static methods.\r\n if (!constructor || constructor == Object.prototype.constructor) {\r\n constructor = function() {\r\n throw new Error(\r\n 'cannot instantiate an interface (no constructor defined).');\r\n };\r\n }\r\n\r\n var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\r\n if (superClass) {\r\n goog.inherits(cls, superClass);\r\n }\r\n\r\n // Remove all the properties that should not be copied to the prototype.\r\n delete def.constructor;\r\n delete def.statics;\r\n\r\n goog.defineClass.applyProperties_(cls.prototype, def);\r\n if (statics != null) {\r\n if (statics instanceof Function) {\r\n statics(cls);\r\n } else {\r\n goog.defineClass.applyProperties_(cls, statics);\r\n }\r\n }\r\n\r\n return cls;\r\n};\r\n\r\n\r\n/**\r\n * @typedef {{\r\n * constructor: (!Function|undefined),\r\n * statics: (Object|undefined|function(Function):void)\r\n * }}\r\n */\r\ngoog.defineClass.ClassDescriptor;\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the instances returned by goog.defineClass should\r\n * be sealed when possible.\r\n *\r\n * When sealing is disabled the constructor function will not be wrapped by\r\n * goog.defineClass, making it incompatible with ES6 class methods.\r\n */\r\ngoog.defineClass.SEAL_CLASS_INSTANCES =\r\n goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\r\n\r\n\r\n/**\r\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\r\n * defined, this function will wrap the constructor in a function that seals the\r\n * results of the provided constructor function.\r\n *\r\n * @param {!Function} ctr The constructor whose results maybe be sealed.\r\n * @param {Function} superClass The superclass constructor.\r\n * @return {!Function} The replacement constructor.\r\n * @private\r\n */\r\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\r\n if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\r\n // Do now wrap the constructor when sealing is disabled. Angular code\r\n // depends on this for injection to work properly.\r\n return ctr;\r\n }\r\n\r\n // Compute whether the constructor is sealable at definition time, rather\r\n // than when the instance is being constructed.\r\n var superclassSealable = !goog.defineClass.isUnsealable_(superClass);\r\n\r\n /**\r\n * @this {Object}\r\n * @return {?}\r\n */\r\n var wrappedCtr = function() {\r\n // Don't seal an instance of a subclass when it calls the constructor of\r\n // its super class as there is most likely still setup to do.\r\n var instance = ctr.apply(this, arguments) || this;\r\n instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\r\n\r\n if (this.constructor === wrappedCtr && superclassSealable &&\r\n Object.seal instanceof Function) {\r\n Object.seal(instance);\r\n }\r\n return instance;\r\n };\r\n\r\n return wrappedCtr;\r\n};\r\n\r\n\r\n/**\r\n * @param {Function} ctr The constructor to test.\r\n * @return {boolean} Whether the constructor has been tagged as unsealable\r\n * using goog.tagUnsealableClass.\r\n * @private\r\n */\r\ngoog.defineClass.isUnsealable_ = function(ctr) {\r\n return ctr && ctr.prototype &&\r\n ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_];\r\n};\r\n\r\n\r\n// TODO(johnlenz): share these values with the goog.object\r\n/**\r\n * The names of the fields that are defined on Object.prototype.\r\n * @type {!Array<string>}\r\n * @private\r\n * @const\r\n */\r\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\r\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\r\n 'toLocaleString', 'toString', 'valueOf'\r\n];\r\n\r\n\r\n// TODO(johnlenz): share this function with the goog.object\r\n/**\r\n * @param {!Object} target The object to add properties to.\r\n * @param {!Object} source The object to copy properties from.\r\n * @private\r\n */\r\ngoog.defineClass.applyProperties_ = function(target, source) {\r\n // TODO(johnlenz): update this to support ES5 getters/setters\r\n\r\n var key;\r\n for (key in source) {\r\n if (Object.prototype.hasOwnProperty.call(source, key)) {\r\n target[key] = source[key];\r\n }\r\n }\r\n\r\n // For IE the for-in-loop does not contain any properties that are not\r\n // enumerable on the prototype object (for example isPrototypeOf from\r\n // Object.prototype) and it will also not include 'replace' on objects that\r\n // extend String and change 'replace' (not that it is common for anyone to\r\n // extend anything except Object).\r\n for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\r\n key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\r\n if (Object.prototype.hasOwnProperty.call(source, key)) {\r\n target[key] = source[key];\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sealing classes breaks the older idiom of assigning properties on the\r\n * prototype rather than in the constructor. As such, goog.defineClass\r\n * must not seal subclasses of these old-style classes until they are fixed.\r\n * Until then, this marks a class as \"broken\", instructing defineClass\r\n * not to seal subclasses.\r\n * @param {!Function} ctr The legacy constructor to tag as unsealable.\r\n */\r\ngoog.tagUnsealableClass = function(ctr) {\r\n if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) {\r\n ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Name for unsealable tag property.\r\n * @const @private {string}\r\n */\r\ngoog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable';\r\n\r\n\r\n// There's a bug in the compiler where without collapse properties the\r\n// Closure namespace defines do not guard code correctly. To help reduce code\r\n// size also check for !COMPILED even though it redundant until this is fixed.\r\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\r\n\r\n /**\r\n * Tries to detect whether is in the context of an HTML document.\r\n * @return {boolean} True if it looks like HTML document.\r\n * @private\r\n */\r\n goog.inHtmlDocument_ = function() {\r\n /** @type {!Document} */\r\n var doc = goog.global.document;\r\n return doc != null && 'write' in doc; // XULDocument misses write.\r\n };\r\n\r\n\r\n /**\r\n * We'd like to check for if the document readyState is 'loading'; however\r\n * there are bugs on IE 10 and below where the readyState being anything other\r\n * than 'complete' is not reliable.\r\n * @return {boolean}\r\n * @private\r\n */\r\n goog.isDocumentLoading_ = function() {\r\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\r\n // detect those browsers.\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n return doc.attachEvent ? doc.readyState != 'complete' :\r\n doc.readyState == 'loading';\r\n };\r\n\r\n\r\n /**\r\n * Tries to detect the base path of base.js script that bootstraps Closure.\r\n * @private\r\n */\r\n goog.findBasePath_ = function() {\r\n if (goog.isDef(goog.global.CLOSURE_BASE_PATH) &&\r\n // Anti DOM-clobbering runtime check (b/37736576).\r\n goog.isString(goog.global.CLOSURE_BASE_PATH)) {\r\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\r\n return;\r\n } else if (!goog.inHtmlDocument_()) {\r\n return;\r\n }\r\n /** @type {!Document} */\r\n var doc = goog.global.document;\r\n // If we have a currentScript available, use it exclusively.\r\n var currentScript = doc.currentScript;\r\n if (currentScript) {\r\n var scripts = [currentScript];\r\n } else {\r\n var scripts = doc.getElementsByTagName('SCRIPT');\r\n }\r\n // Search backwards since the current script is in almost all cases the one\r\n // that has base.js.\r\n for (var i = scripts.length - 1; i >= 0; --i) {\r\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\r\n var src = script.src;\r\n var qmark = src.lastIndexOf('?');\r\n var l = qmark == -1 ? src.length : qmark;\r\n if (src.substr(l - 7, 7) == 'base.js') {\r\n goog.basePath = src.substr(0, l - 7);\r\n return;\r\n }\r\n }\r\n };\r\n\r\n goog.findBasePath_();\r\n\r\n /** @struct @constructor @final */\r\n goog.Transpiler = function() {\r\n /** @private {?Object<string, boolean>} */\r\n this.requiresTranspilation_ = null;\r\n /** @private {string} */\r\n this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;\r\n };\r\n\r\n\r\n /**\r\n * Returns a newly created map from language mode string to a boolean\r\n * indicating whether transpilation should be done for that mode as well as\r\n * the highest level language that this environment supports.\r\n *\r\n * Guaranteed invariant:\r\n * For any two modes, l1 and l2 where l2 is a newer mode than l1,\r\n * `map[l1] == true` implies that `map[l2] == true`.\r\n *\r\n * Note this method is extracted and used elsewhere, so it cannot rely on\r\n * anything external (it should easily be able to be transformed into a\r\n * standalone, top level function).\r\n *\r\n * @private\r\n * @return {{\r\n * target: string,\r\n * map: !Object<string, boolean>\r\n * }}\r\n */\r\n goog.Transpiler.prototype.createRequiresTranspilation_ = function() {\r\n var transpilationTarget = 'es3';\r\n var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false};\r\n var transpilationRequiredForAllLaterModes = false;\r\n\r\n /**\r\n * Adds an entry to requiresTranspliation for the given language mode.\r\n *\r\n * IMPORTANT: Calls must be made in order from oldest to newest language\r\n * mode.\r\n * @param {string} modeName\r\n * @param {function(): boolean} isSupported Returns true if the JS engine\r\n * supports the given mode.\r\n */\r\n function addNewerLanguageTranspilationCheck(modeName, isSupported) {\r\n if (transpilationRequiredForAllLaterModes) {\r\n requiresTranspilation[modeName] = true;\r\n } else if (isSupported()) {\r\n transpilationTarget = modeName;\r\n requiresTranspilation[modeName] = false;\r\n } else {\r\n requiresTranspilation[modeName] = true;\r\n transpilationRequiredForAllLaterModes = true;\r\n }\r\n }\r\n\r\n /**\r\n * Does the given code evaluate without syntax errors and return a truthy\r\n * result?\r\n */\r\n function /** boolean */ evalCheck(/** string */ code) {\r\n try {\r\n return !!eval(code);\r\n } catch (ignored) {\r\n return false;\r\n }\r\n }\r\n\r\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\r\n goog.global.navigator.userAgent :\r\n '';\r\n\r\n // Identify ES3-only browsers by their incorrect treatment of commas.\r\n addNewerLanguageTranspilationCheck('es5', function() {\r\n return evalCheck('[1,].length==1');\r\n });\r\n addNewerLanguageTranspilationCheck('es6', function() {\r\n // Edge has a non-deterministic (i.e., not reproducible) bug with ES6:\r\n // https://github.com/Microsoft/ChakraCore/issues/1496.\r\n var re = /Edge\\/(\\d+)(\\.\\d)*/i;\r\n var edgeUserAgent = userAgent.match(re);\r\n if (edgeUserAgent) {\r\n // The Reflect.construct test below is flaky on Edge. It can sometimes\r\n // pass or fail on 40 15.15063, so just exit early for Edge and treat\r\n // it as ES5. Until we're on a more up to date version just always use\r\n // ES5. See https://github.com/Microsoft/ChakraCore/issues/3217.\r\n return false;\r\n }\r\n // Test es6: [FF50 (?), Edge 14 (?), Chrome 50]\r\n // (a) default params (specifically shadowing locals),\r\n // (b) destructuring, (c) block-scoped functions,\r\n // (d) for-of (const), (e) new.target/Reflect.construct\r\n var es6fullTest =\r\n 'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' +\r\n 'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' +\r\n 'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' +\r\n 'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' +\r\n '==3}';\r\n\r\n return evalCheck('(()=>{\"use strict\";' + es6fullTest + '})()');\r\n });\r\n // ** and **= are the only new features in 'es7'\r\n addNewerLanguageTranspilationCheck('es7', function() {\r\n return evalCheck('2 ** 2 == 4');\r\n });\r\n // async functions are the only new features in 'es8'\r\n addNewerLanguageTranspilationCheck('es8', function() {\r\n return evalCheck('async () => 1, true');\r\n });\r\n addNewerLanguageTranspilationCheck('es9', function() {\r\n return evalCheck('({...rest} = {}), true');\r\n });\r\n addNewerLanguageTranspilationCheck('es_next', function() {\r\n return false; // assume it always need to transpile\r\n });\r\n return {target: transpilationTarget, map: requiresTranspilation};\r\n };\r\n\r\n\r\n /**\r\n * Determines whether the given language needs to be transpiled.\r\n * @param {string} lang\r\n * @param {string|undefined} module\r\n * @return {boolean}\r\n */\r\n goog.Transpiler.prototype.needsTranspile = function(lang, module) {\r\n if (goog.TRANSPILE == 'always') {\r\n return true;\r\n } else if (goog.TRANSPILE == 'never') {\r\n return false;\r\n } else if (!this.requiresTranspilation_) {\r\n var obj = this.createRequiresTranspilation_();\r\n this.requiresTranspilation_ = obj.map;\r\n this.transpilationTarget_ = this.transpilationTarget_ || obj.target;\r\n }\r\n if (lang in this.requiresTranspilation_) {\r\n if (this.requiresTranspilation_[lang]) {\r\n return true;\r\n } else if (\r\n goog.inHtmlDocument_() && module == 'es6' &&\r\n !('noModule' in goog.global.document.createElement('script'))) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n throw new Error('Unknown language mode: ' + lang);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Lazily retrieves the transpiler and applies it to the source.\r\n * @param {string} code JS code.\r\n * @param {string} path Path to the code.\r\n * @return {string} The transpiled code.\r\n */\r\n goog.Transpiler.prototype.transpile = function(code, path) {\r\n // TODO(johnplaisted): We should delete goog.transpile_ and just have this\r\n // function. But there's some compile error atm where goog.global is being\r\n // stripped incorrectly without this.\r\n return goog.transpile_(code, path, this.transpilationTarget_);\r\n };\r\n\r\n\r\n /** @private @final {!goog.Transpiler} */\r\n goog.transpiler_ = new goog.Transpiler();\r\n\r\n /**\r\n * Rewrites closing script tags in input to avoid ending an enclosing script\r\n * tag.\r\n *\r\n * @param {string} str\r\n * @return {string}\r\n * @private\r\n */\r\n goog.protectScriptTag_ = function(str) {\r\n return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\r\n };\r\n\r\n\r\n /**\r\n * A debug loader is responsible for downloading and executing javascript\r\n * files in an unbundled, uncompiled environment.\r\n *\r\n * This can be custimized via the setDependencyFactory method, or by\r\n * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\r\n *\r\n * @struct @constructor @final @private\r\n */\r\n goog.DebugLoader_ = function() {\r\n /** @private @const {!Object<string, !goog.Dependency>} */\r\n this.dependencies_ = {};\r\n /** @private @const {!Object<string, string>} */\r\n this.idToPath_ = {};\r\n /** @private @const {!Object<string, boolean>} */\r\n this.written_ = {};\r\n /** @private @const {!Array<!goog.Dependency>} */\r\n this.loadingDeps_ = [];\r\n /** @private {!Array<!goog.Dependency>} */\r\n this.depsToLoad_ = [];\r\n /** @private {boolean} */\r\n this.paused_ = false;\r\n /** @private {!goog.DependencyFactory} */\r\n this.factory_ = new goog.DependencyFactory(goog.transpiler_);\r\n /** @private @const {!Object<string, !Function>} */\r\n this.deferredCallbacks_ = {};\r\n /** @private @const {!Array<string>} */\r\n this.deferredQueue_ = [];\r\n };\r\n\r\n /**\r\n * @param {!Array<string>} namespaces\r\n * @param {function(): undefined} callback Function to call once all the\r\n * namespaces have loaded.\r\n */\r\n goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\r\n var cb = callback;\r\n function resolve() {\r\n if (cb) {\r\n goog.global.setTimeout(cb, 0);\r\n cb = null;\r\n }\r\n }\r\n\r\n if (!namespaces.length) {\r\n resolve();\r\n return;\r\n }\r\n\r\n var deps = [];\r\n for (var i = 0; i < namespaces.length; i++) {\r\n var path = this.getPathFromDeps_(namespaces[i]);\r\n if (!path) {\r\n throw new Error('Unregonized namespace: ' + namespaces[i]);\r\n }\r\n deps.push(this.dependencies_[path]);\r\n }\r\n\r\n var require = goog.require;\r\n var loaded = 0;\r\n for (var i = 0; i < namespaces.length; i++) {\r\n require(namespaces[i]);\r\n deps[i].onLoad(function() {\r\n if (++loaded == namespaces.length) {\r\n resolve();\r\n }\r\n });\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Loads the Closure Dependency file.\r\n *\r\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\r\n * loaded, setDependencyFactory called, and then this called. i.e. allows\r\n * custom loading of the deps file.\r\n */\r\n goog.DebugLoader_.prototype.loadClosureDeps = function() {\r\n // Circumvent addDependency, which would try to transpile deps.js if\r\n // transpile is set to always.\r\n var relPath = 'deps.js';\r\n this.depsToLoad_.push(this.factory_.createDependency(\r\n goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {},\r\n false));\r\n this.loadDeps_();\r\n };\r\n\r\n\r\n /**\r\n * Notifies the debug loader when a dependency has been requested.\r\n *\r\n * @param {string} absPathOrId Path of the dependency or goog id.\r\n * @param {boolean=} opt_force\r\n */\r\n goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\r\n var path = this.getPathFromDeps_(absPathOrId);\r\n if (path &&\r\n (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\r\n var callback = this.deferredCallbacks_[path];\r\n if (callback) {\r\n delete this.deferredCallbacks_[path];\r\n callback();\r\n }\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Sets the dependency factory, which can be used to create custom\r\n * goog.Dependency implementations to control how dependencies are loaded.\r\n *\r\n * @param {!goog.DependencyFactory} factory\r\n */\r\n goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\r\n this.factory_ = factory;\r\n };\r\n\r\n\r\n /**\r\n * Travserses the dependency graph and queues the given dependency, and all of\r\n * its transitive dependencies, for loading and then starts loading if not\r\n * paused.\r\n *\r\n * @param {string} namespace\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.load_ = function(namespace) {\r\n if (!this.getPathFromDeps_(namespace)) {\r\n var errorMessage = 'goog.require could not find: ' + namespace;\r\n\r\n goog.logToConsole_(errorMessage);\r\n throw Error(errorMessage);\r\n } else {\r\n var loader = this;\r\n\r\n var deps = [];\r\n\r\n /** @param {string} namespace */\r\n var visit = function(namespace) {\r\n var path = loader.getPathFromDeps_(namespace);\r\n\r\n if (!path) {\r\n throw new Error('Bad dependency path or symbol: ' + namespace);\r\n }\r\n\r\n if (loader.written_[path]) {\r\n return;\r\n }\r\n\r\n loader.written_[path] = true;\r\n\r\n var dep = loader.dependencies_[path];\r\n for (var i = 0; i < dep.requires.length; i++) {\r\n if (!goog.isProvided_(dep.requires[i])) {\r\n visit(dep.requires[i]);\r\n }\r\n }\r\n\r\n deps.push(dep);\r\n };\r\n\r\n visit(namespace);\r\n\r\n var wasLoading = !!this.depsToLoad_.length;\r\n this.depsToLoad_ = this.depsToLoad_.concat(deps);\r\n\r\n if (!this.paused_ && !wasLoading) {\r\n this.loadDeps_();\r\n }\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Loads any queued dependencies until they are all loaded or paused.\r\n *\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.loadDeps_ = function() {\r\n var loader = this;\r\n var paused = this.paused_;\r\n\r\n while (this.depsToLoad_.length && !paused) {\r\n (function() {\r\n var loadCallDone = false;\r\n var dep = loader.depsToLoad_.shift();\r\n\r\n var loaded = false;\r\n loader.loading_(dep);\r\n\r\n var controller = {\r\n pause: function() {\r\n if (loadCallDone) {\r\n throw new Error('Cannot call pause after the call to load.');\r\n } else {\r\n paused = true;\r\n }\r\n },\r\n resume: function() {\r\n if (loadCallDone) {\r\n loader.resume_();\r\n } else {\r\n // Some dep called pause and then resume in the same load call.\r\n // Just keep running this same loop.\r\n paused = false;\r\n }\r\n },\r\n loaded: function() {\r\n if (loaded) {\r\n throw new Error('Double call to loaded.');\r\n }\r\n\r\n loaded = true;\r\n loader.loaded_(dep);\r\n },\r\n pending: function() {\r\n // Defensive copy.\r\n var pending = [];\r\n for (var i = 0; i < loader.loadingDeps_.length; i++) {\r\n pending.push(loader.loadingDeps_[i]);\r\n }\r\n return pending;\r\n },\r\n /**\r\n * @param {goog.ModuleType} type\r\n */\r\n setModuleState: function(type) {\r\n goog.moduleLoaderState_ = {\r\n type: type,\r\n moduleName: '',\r\n declareLegacyNamespace: false\r\n };\r\n },\r\n /** @type {function(string, string, string=)} */\r\n registerEs6ModuleExports: function(\r\n path, exports, opt_closureNamespace) {\r\n if (opt_closureNamespace) {\r\n goog.loadedModules_[opt_closureNamespace] = {\r\n exports: exports,\r\n type: goog.ModuleType.ES6,\r\n moduleId: opt_closureNamespace || ''\r\n };\r\n }\r\n },\r\n /** @type {function(string, ?)} */\r\n registerGoogModuleExports: function(moduleId, exports) {\r\n goog.loadedModules_[moduleId] = {\r\n exports: exports,\r\n type: goog.ModuleType.GOOG,\r\n moduleId: moduleId\r\n };\r\n },\r\n clearModuleState: function() {\r\n goog.moduleLoaderState_ = null;\r\n },\r\n defer: function(callback) {\r\n if (loadCallDone) {\r\n throw new Error(\r\n 'Cannot register with defer after the call to load.');\r\n }\r\n loader.defer_(dep, callback);\r\n },\r\n areDepsLoaded: function() {\r\n return loader.areDepsLoaded_(dep.requires);\r\n }\r\n };\r\n\r\n try {\r\n dep.load(controller);\r\n } finally {\r\n loadCallDone = true;\r\n }\r\n })();\r\n }\r\n\r\n if (paused) {\r\n this.pause_();\r\n }\r\n };\r\n\r\n\r\n /** @private */\r\n goog.DebugLoader_.prototype.pause_ = function() {\r\n this.paused_ = true;\r\n };\r\n\r\n\r\n /** @private */\r\n goog.DebugLoader_.prototype.resume_ = function() {\r\n if (this.paused_) {\r\n this.paused_ = false;\r\n this.loadDeps_();\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Marks the given dependency as loading (load has been called but it has not\r\n * yet marked itself as finished). Useful for dependencies that want to know\r\n * what else is loading. Example: goog.modules cannot eval if there are\r\n * loading dependencies.\r\n *\r\n * @param {!goog.Dependency} dep\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.loading_ = function(dep) {\r\n this.loadingDeps_.push(dep);\r\n };\r\n\r\n\r\n /**\r\n * Marks the given dependency as having finished loading and being available\r\n * for require.\r\n *\r\n * @param {!goog.Dependency} dep\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.loaded_ = function(dep) {\r\n for (var i = 0; i < this.loadingDeps_.length; i++) {\r\n if (this.loadingDeps_[i] == dep) {\r\n this.loadingDeps_.splice(i, 1);\r\n break;\r\n }\r\n }\r\n\r\n for (var i = 0; i < this.deferredQueue_.length; i++) {\r\n if (this.deferredQueue_[i] == dep.path) {\r\n this.deferredQueue_.splice(i, 1);\r\n break;\r\n }\r\n }\r\n\r\n if (this.loadingDeps_.length == this.deferredQueue_.length &&\r\n !this.depsToLoad_.length) {\r\n // Something has asked to load these, but they may not be directly\r\n // required again later, so load them now that we know we're done loading\r\n // everything else. e.g. a goog module entry point.\r\n while (this.deferredQueue_.length) {\r\n this.requested(this.deferredQueue_.shift(), true);\r\n }\r\n }\r\n\r\n dep.loaded();\r\n };\r\n\r\n\r\n /**\r\n * @param {!Array<string>} pathsOrIds\r\n * @return {boolean}\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\r\n for (var i = 0; i < pathsOrIds.length; i++) {\r\n var path = this.getPathFromDeps_(pathsOrIds[i]);\r\n if (!path ||\r\n (!(path in this.deferredCallbacks_) &&\r\n !goog.isProvided_(pathsOrIds[i]))) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n };\r\n\r\n\r\n /**\r\n * @param {string} absPathOrId\r\n * @return {?string}\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\r\n if (absPathOrId in this.idToPath_) {\r\n return this.idToPath_[absPathOrId];\r\n } else if (absPathOrId in this.dependencies_) {\r\n return absPathOrId;\r\n } else {\r\n return null;\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @param {!goog.Dependency} dependency\r\n * @param {!Function} callback\r\n * @private\r\n */\r\n goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\r\n this.deferredCallbacks_[dependency.path] = callback;\r\n this.deferredQueue_.push(dependency.path);\r\n };\r\n\r\n\r\n /**\r\n * Interface for goog.Dependency implementations to have some control over\r\n * loading of dependencies.\r\n *\r\n * @record\r\n */\r\n goog.LoadController = function() {};\r\n\r\n\r\n /**\r\n * Tells the controller to halt loading of more dependencies.\r\n */\r\n goog.LoadController.prototype.pause = function() {};\r\n\r\n\r\n /**\r\n * Tells the controller to resume loading of more dependencies if paused.\r\n */\r\n goog.LoadController.prototype.resume = function() {};\r\n\r\n\r\n /**\r\n * Tells the controller that this dependency has finished loading.\r\n *\r\n * This causes this to be removed from pending() and any load callbacks to\r\n * fire.\r\n */\r\n goog.LoadController.prototype.loaded = function() {};\r\n\r\n\r\n /**\r\n * List of dependencies on which load has been called but which have not\r\n * called loaded on their controller. This includes the current dependency.\r\n *\r\n * @return {!Array<!goog.Dependency>}\r\n */\r\n goog.LoadController.prototype.pending = function() {};\r\n\r\n\r\n /**\r\n * Registers an object as an ES6 module's exports so that goog.modules may\r\n * require it by path.\r\n *\r\n * @param {string} path Full path of the module.\r\n * @param {?} exports\r\n * @param {string=} opt_closureNamespace Closure namespace to associate with\r\n * this module.\r\n */\r\n goog.LoadController.prototype.registerEs6ModuleExports = function(\r\n path, exports, opt_closureNamespace) {};\r\n\r\n\r\n /**\r\n * Sets the current module state.\r\n *\r\n * @param {goog.ModuleType} type Type of module.\r\n */\r\n goog.LoadController.prototype.setModuleState = function(type) {};\r\n\r\n\r\n /**\r\n * Clears the current module state.\r\n */\r\n goog.LoadController.prototype.clearModuleState = function() {};\r\n\r\n\r\n /**\r\n * Registers a callback to call once the dependency is actually requested\r\n * via goog.require + all of the immediate dependencies have been loaded or\r\n * all other files have been loaded. Allows for lazy loading until\r\n * require'd without pausing dependency loading, which is needed on old IE.\r\n *\r\n * @param {!Function} callback\r\n */\r\n goog.LoadController.prototype.defer = function(callback) {};\r\n\r\n\r\n /**\r\n * @return {boolean}\r\n */\r\n goog.LoadController.prototype.areDepsLoaded = function() {};\r\n\r\n\r\n /**\r\n * Basic super class for all dependencies Closure Library can load.\r\n *\r\n * This default implementation is designed to load untranspiled, non-module\r\n * scripts in a web broswer.\r\n *\r\n * For transpiled non-goog.module files {@see goog.TranspiledDependency}.\r\n * For goog.modules see {@see goog.GoogModuleDependency}.\r\n * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor\r\n */\r\n goog.Dependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n /** @const */\r\n this.path = path;\r\n /** @const */\r\n this.relativePath = relativePath;\r\n /** @const */\r\n this.provides = provides;\r\n /** @const */\r\n this.requires = requires;\r\n /** @const */\r\n this.loadFlags = loadFlags;\r\n /** @private {boolean} */\r\n this.loaded_ = false;\r\n /** @private {!Array<function()>} */\r\n this.loadCallbacks_ = [];\r\n };\r\n\r\n\r\n /**\r\n * @return {string} The pathname part of this dependency's path if it is a\r\n * URI.\r\n */\r\n goog.Dependency.prototype.getPathName = function() {\r\n var pathName = this.path;\r\n var protocolIndex = pathName.indexOf('://');\r\n if (protocolIndex >= 0) {\r\n pathName = pathName.substring(protocolIndex + 3);\r\n var slashIndex = pathName.indexOf('/');\r\n if (slashIndex >= 0) {\r\n pathName = pathName.substring(slashIndex + 1);\r\n }\r\n }\r\n return pathName;\r\n };\r\n\r\n\r\n /**\r\n * @param {function()} callback Callback to fire as soon as this has loaded.\r\n * @final\r\n */\r\n goog.Dependency.prototype.onLoad = function(callback) {\r\n if (this.loaded_) {\r\n callback();\r\n } else {\r\n this.loadCallbacks_.push(callback);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Marks this dependency as loaded and fires any callbacks registered with\r\n * onLoad.\r\n * @final\r\n */\r\n goog.Dependency.prototype.loaded = function() {\r\n this.loaded_ = true;\r\n var callbacks = this.loadCallbacks_;\r\n this.loadCallbacks_ = [];\r\n for (var i = 0; i < callbacks.length; i++) {\r\n callbacks[i]();\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Whether or not document.written / appended script tags should be deferred.\r\n *\r\n * @private {boolean}\r\n */\r\n goog.Dependency.defer_ = false;\r\n\r\n\r\n /**\r\n * Map of script ready / state change callbacks. Old IE cannot handle putting\r\n * these properties on goog.global.\r\n *\r\n * @private @const {!Object<string, function(?):undefined>}\r\n */\r\n goog.Dependency.callbackMap_ = {};\r\n\r\n\r\n /**\r\n * @param {function(...?):?} callback\r\n * @return {string}\r\n * @private\r\n */\r\n goog.Dependency.registerCallback_ = function(callback) {\r\n var key = Math.random().toString(32);\r\n goog.Dependency.callbackMap_[key] = callback;\r\n return key;\r\n };\r\n\r\n\r\n /**\r\n * @param {string} key\r\n * @private\r\n */\r\n goog.Dependency.unregisterCallback_ = function(key) {\r\n delete goog.Dependency.callbackMap_[key];\r\n };\r\n\r\n\r\n /**\r\n * @param {string} key\r\n * @param {...?} var_args\r\n * @private\r\n * @suppress {unusedPrivateMembers}\r\n */\r\n goog.Dependency.callback_ = function(key, var_args) {\r\n if (key in goog.Dependency.callbackMap_) {\r\n var callback = goog.Dependency.callbackMap_[key];\r\n var args = [];\r\n for (var i = 1; i < arguments.length; i++) {\r\n args.push(arguments[i]);\r\n }\r\n callback.apply(undefined, args);\r\n } else {\r\n var errorMessage = 'Callback key ' + key +\r\n ' does not exist (was base.js loaded more than once?).';\r\n throw Error(errorMessage);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Starts loading this dependency. This dependency can pause loading if it\r\n * needs to and resume it later via the controller interface.\r\n *\r\n * When this is loaded it should call controller.loaded(). Note that this will\r\n * end up calling the loaded method of this dependency; there is no need to\r\n * call it explicitly.\r\n *\r\n * @param {!goog.LoadController} controller\r\n */\r\n goog.Dependency.prototype.load = function(controller) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n if (!goog.inHtmlDocument_()) {\r\n goog.logToConsole_(\r\n 'Cannot use default debug loader outside of HTML documents.');\r\n if (this.relativePath == 'deps.js') {\r\n // Some old code is relying on base.js auto loading deps.js failing with\r\n // no error before later setting CLOSURE_IMPORT_SCRIPT.\r\n // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\r\n // CLOSURE_NO_DEPS set to true.\r\n goog.logToConsole_(\r\n 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\r\n 'or setting CLOSURE_NO_DEPS to true.');\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n\r\n // If the user tries to require a new symbol after document load,\r\n // something has gone terribly wrong. Doing a document.write would\r\n // wipe out the page. This does not apply to the CSP-compliant method\r\n // of writing script tags.\r\n if (doc.readyState == 'complete' &&\r\n !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\r\n // Certain test frameworks load base.js multiple times, which tries\r\n // to write deps.js each time. If that happens, just fail silently.\r\n // These frameworks wipe the page between each load of base.js, so this\r\n // is OK.\r\n var isDeps = /\\bdeps.js$/.test(this.path);\r\n if (isDeps) {\r\n controller.loaded();\r\n return;\r\n } else {\r\n throw Error('Cannot write \"' + this.path + '\" after document load');\r\n }\r\n }\r\n\r\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\r\n goog.isDocumentLoading_()) {\r\n var key = goog.Dependency.registerCallback_(function(script) {\r\n if (!goog.DebugLoader_.IS_OLD_IE_ || script.readyState == 'complete') {\r\n goog.Dependency.unregisterCallback_(key);\r\n controller.loaded();\r\n }\r\n });\r\n var nonceAttr = !goog.DebugLoader_.IS_OLD_IE_ && goog.getScriptNonce() ?\r\n ' nonce=\"' + goog.getScriptNonce() + '\"' :\r\n '';\r\n var event =\r\n goog.DebugLoader_.IS_OLD_IE_ ? 'onreadystatechange' : 'onload';\r\n var defer = goog.Dependency.defer_ ? 'defer' : '';\r\n var script = '<script src=\"' + this.path + '\" ' + event +\r\n '=\"goog.Dependency.callback_(\\'' + key +\r\n '\\', this)\" type=\"text/javascript\" ' + defer + nonceAttr + '><' +\r\n '/script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n } else {\r\n var scriptEl =\r\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\r\n scriptEl.defer = goog.Dependency.defer_;\r\n scriptEl.async = false;\r\n scriptEl.type = 'text/javascript';\r\n\r\n // If CSP nonces are used, propagate them to dynamically created scripts.\r\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\r\n var nonce = goog.getScriptNonce();\r\n if (nonce) {\r\n scriptEl.setAttribute('nonce', nonce);\r\n }\r\n\r\n if (goog.DebugLoader_.IS_OLD_IE_) {\r\n // Execution order is not guaranteed on old IE, halt loading and write\r\n // these scripts one at a time, after each loads.\r\n controller.pause();\r\n scriptEl.onreadystatechange = function() {\r\n if (scriptEl.readyState == 'loaded' ||\r\n scriptEl.readyState == 'complete') {\r\n controller.loaded();\r\n controller.resume();\r\n }\r\n };\r\n } else {\r\n scriptEl.onload = function() {\r\n scriptEl.onload = null;\r\n controller.loaded();\r\n };\r\n }\r\n\r\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\r\n this.path;\r\n doc.head.appendChild(scriptEl);\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides Should be an empty array.\r\n * TODO(johnplaisted) add support for adding closure namespaces to ES6\r\n * modules for interop purposes.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor\r\n * @extends {goog.Dependency}\r\n */\r\n goog.Es6ModuleDependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n goog.Es6ModuleDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n };\r\n goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\r\n\r\n\r\n /** @override */\r\n goog.Es6ModuleDependency.prototype.load = function(controller) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n if (!goog.inHtmlDocument_()) {\r\n goog.logToConsole_(\r\n 'Cannot use default debug loader outside of HTML documents.');\r\n controller.pause();\r\n return;\r\n }\r\n\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n\r\n var dep = this;\r\n\r\n // TODO(johnplaisted): Does document.writing really speed up anything? Any\r\n // difference between this and just waiting for interactive mode and then\r\n // appending?\r\n function write(src, contents) {\r\n if (contents) {\r\n var script = '<script type=\"module\" crossorigin>' + contents + '</' +\r\n 'script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n } else {\r\n var script = '<script type=\"module\" crossorigin src=\"' + src + '\"></' +\r\n 'script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n }\r\n }\r\n\r\n function append(src, contents) {\r\n var scriptEl =\r\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\r\n scriptEl.defer = true;\r\n scriptEl.async = false;\r\n scriptEl.type = 'module';\r\n scriptEl.setAttribute('crossorigin', true);\r\n\r\n // If CSP nonces are used, propagate them to dynamically created scripts.\r\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\r\n var nonce = goog.getScriptNonce();\r\n if (nonce) {\r\n scriptEl.setAttribute('nonce', nonce);\r\n }\r\n\r\n if (contents) {\r\n scriptEl.textContent = goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\r\n contents;\r\n } else {\r\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\r\n src;\r\n }\r\n\r\n doc.head.appendChild(scriptEl);\r\n }\r\n\r\n var create;\r\n\r\n if (goog.isDocumentLoading_()) {\r\n create = write;\r\n // We can ONLY call document.write if we are guaranteed that any\r\n // non-module script tags document.written after this are deferred.\r\n // Small optimization, in theory document.writing is faster.\r\n goog.Dependency.defer_ = true;\r\n } else {\r\n create = append;\r\n }\r\n\r\n // Write 4 separate tags here:\r\n // 1) Sets the module state at the correct time (just before execution).\r\n // 2) A src node for this, which just hopefully lets the browser load it a\r\n // little early (no need to parse #3).\r\n // 3) Import the module and register it.\r\n // 4) Clear the module state at the correct time. Guaranteed to run even\r\n // if there is an error in the module (#3 will not run if there is an\r\n // error in the module).\r\n var beforeKey = goog.Dependency.registerCallback_(function() {\r\n goog.Dependency.unregisterCallback_(beforeKey);\r\n controller.setModuleState(goog.ModuleType.ES6);\r\n });\r\n create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\r\n\r\n // TODO(johnplaisted): Does this really speed up anything?\r\n create(this.path, undefined);\r\n\r\n var registerKey = goog.Dependency.registerCallback_(function(exports) {\r\n goog.Dependency.unregisterCallback_(registerKey);\r\n controller.registerEs6ModuleExports(\r\n dep.path, exports, goog.moduleLoaderState_.moduleName);\r\n });\r\n create(\r\n undefined,\r\n 'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\r\n registerKey + '\", m)');\r\n\r\n var afterKey = goog.Dependency.registerCallback_(function() {\r\n goog.Dependency.unregisterCallback_(afterKey);\r\n controller.clearModuleState();\r\n controller.loaded();\r\n });\r\n create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\r\n };\r\n\r\n\r\n /**\r\n * Superclass of any dependency that needs to be loaded into memory,\r\n * transformed, and then eval'd (goog.modules and transpiled files).\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor @abstract\r\n * @extends {goog.Dependency}\r\n */\r\n goog.TransformedDependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n goog.TransformedDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n /** @private {?string} */\r\n this.contents_ = null;\r\n\r\n /**\r\n * Whether to lazily make the synchronous XHR (when goog.require'd) or make\r\n * the synchronous XHR when initially loading. On FireFox 61 there is a bug\r\n * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\r\n * it does then no other ES6 modules will load after).\r\n *\r\n * tl;dr we lazy load due to bugs on older browsers and eager load due to\r\n * bugs on newer ones.\r\n *\r\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\r\n *\r\n * @private @const {boolean}\r\n */\r\n this.lazyFetch_ = !goog.inHtmlDocument_() ||\r\n !('noModule' in goog.global.document.createElement('script'));\r\n };\r\n goog.inherits(goog.TransformedDependency, goog.Dependency);\r\n\r\n\r\n /** @override */\r\n goog.TransformedDependency.prototype.load = function(controller) {\r\n var dep = this;\r\n\r\n function fetch() {\r\n dep.contents_ = goog.loadFileSync_(dep.path);\r\n\r\n if (dep.contents_) {\r\n dep.contents_ = dep.transform(dep.contents_);\r\n if (dep.contents_) {\r\n dep.contents_ += '\\n//# sourceURL=' + dep.path;\r\n }\r\n }\r\n }\r\n\r\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\r\n fetch();\r\n if (this.contents_ &&\r\n goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\r\n this.contents_ = null;\r\n controller.loaded();\r\n } else {\r\n controller.pause();\r\n }\r\n return;\r\n }\r\n\r\n\r\n var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\r\n\r\n if (!this.lazyFetch_) {\r\n fetch();\r\n }\r\n\r\n function load() {\r\n if (dep.lazyFetch_) {\r\n fetch();\r\n }\r\n\r\n if (!dep.contents_) {\r\n // loadFileSync_ or transform are responsible. Assume they logged an\r\n // error.\r\n return;\r\n }\r\n\r\n if (isEs6) {\r\n controller.setModuleState(goog.ModuleType.ES6);\r\n }\r\n\r\n var namespace;\r\n\r\n try {\r\n var contents = dep.contents_;\r\n dep.contents_ = null;\r\n goog.globalEval(contents);\r\n if (isEs6) {\r\n namespace = goog.moduleLoaderState_.moduleName;\r\n }\r\n } finally {\r\n if (isEs6) {\r\n controller.clearModuleState();\r\n }\r\n }\r\n\r\n if (isEs6) {\r\n // Due to circular dependencies this may not be available for require\r\n // right now.\r\n goog.global['$jscomp']['require']['ensure'](\r\n [dep.getPathName()], function() {\r\n controller.registerEs6ModuleExports(\r\n dep.path,\r\n goog.global['$jscomp']['require'](dep.getPathName()),\r\n namespace);\r\n });\r\n }\r\n\r\n controller.loaded();\r\n }\r\n\r\n // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\r\n // events. If we fetched now and then document.write'd the contents the\r\n // document.write would be an eval and would execute too soon! Instead write\r\n // a script tag to fetch and eval synchronously at the correct time.\r\n function fetchInOwnScriptThenLoad() {\r\n /** @type {!HTMLDocument} */\r\n var doc = goog.global.document;\r\n\r\n var key = goog.Dependency.registerCallback_(function() {\r\n goog.Dependency.unregisterCallback_(key);\r\n load();\r\n });\r\n\r\n var script = '<script type=\"text/javascript\">' +\r\n goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\r\n '</' +\r\n 'script>';\r\n doc.write(\r\n goog.TRUSTED_TYPES_POLICY_ ?\r\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\r\n script);\r\n }\r\n\r\n // If one thing is pending it is this.\r\n var anythingElsePending = controller.pending().length > 1;\r\n\r\n // If anything else is loading we need to lazy load due to bugs in old IE.\r\n // Specifically script tags with src and script tags with contents could\r\n // execute out of order if document.write is used, so we cannot use\r\n // document.write. Do not pause here; it breaks old IE as well.\r\n var useOldIeWorkAround =\r\n anythingElsePending && goog.DebugLoader_.IS_OLD_IE_;\r\n\r\n // Additionally if we are meant to defer scripts but the page is still\r\n // loading (e.g. an ES6 module is loading) then also defer. Or if we are\r\n // meant to defer and anything else is pending then defer (those may be\r\n // scripts that did not need transformation and are just script tags with\r\n // defer set to true, and we need to evaluate after that deferred script).\r\n var needsAsyncLoading = goog.Dependency.defer_ &&\r\n (anythingElsePending || goog.isDocumentLoading_());\r\n\r\n if (useOldIeWorkAround || needsAsyncLoading) {\r\n // Note that we only defer when we have to rather than 100% of the time.\r\n // Always defering would work, but then in theory the order of\r\n // goog.require calls would then matter. We want to enforce that most of\r\n // the time the order of the require calls does not matter.\r\n controller.defer(function() {\r\n load();\r\n });\r\n return;\r\n }\r\n // TODO(johnplaisted): Externs are missing onreadystatechange for\r\n // HTMLDocument.\r\n /** @type {?} */\r\n var doc = goog.global.document;\r\n\r\n var isInternetExplorer =\r\n goog.inHtmlDocument_() && 'ActiveXObject' in goog.global;\r\n\r\n // Don't delay in any version of IE. There's bug around this that will\r\n // cause out of order script execution. This means that on older IE ES6\r\n // modules will load too early (while the document is still loading + the\r\n // dom is not available). The other option is to load too late (when the\r\n // document is complete and the onload even will never fire). This seems\r\n // to be the lesser of two evils as scripts already act like the former.\r\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\r\n !isInternetExplorer) {\r\n goog.Dependency.defer_ = true;\r\n // Transpiled ES6 modules still need to load like regular ES6 modules,\r\n // aka only after the document is interactive.\r\n controller.pause();\r\n var oldCallback = doc.onreadystatechange;\r\n doc.onreadystatechange = function() {\r\n if (doc.readyState == 'interactive') {\r\n doc.onreadystatechange = oldCallback;\r\n load();\r\n controller.resume();\r\n }\r\n if (goog.isFunction(oldCallback)) {\r\n oldCallback.apply(undefined, arguments);\r\n }\r\n };\r\n } else {\r\n // Always eval on old IE.\r\n if (goog.DebugLoader_.IS_OLD_IE_ || !goog.inHtmlDocument_() ||\r\n !goog.isDocumentLoading_()) {\r\n load();\r\n } else {\r\n fetchInOwnScriptThenLoad();\r\n }\r\n }\r\n };\r\n\r\n\r\n /**\r\n * @param {string} contents\r\n * @return {string}\r\n * @abstract\r\n */\r\n goog.TransformedDependency.prototype.transform = function(contents) {};\r\n\r\n\r\n /**\r\n * Any non-goog.module dependency which needs to be transpiled before eval.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @param {!goog.Transpiler} transpiler\r\n * @struct @constructor\r\n * @extends {goog.TransformedDependency}\r\n */\r\n goog.TranspiledDependency = function(\r\n path, relativePath, provides, requires, loadFlags, transpiler) {\r\n goog.TranspiledDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n /** @protected @const*/\r\n this.transpiler = transpiler;\r\n };\r\n goog.inherits(goog.TranspiledDependency, goog.TransformedDependency);\r\n\r\n\r\n /** @override */\r\n goog.TranspiledDependency.prototype.transform = function(contents) {\r\n // Transpile with the pathname so that ES6 modules are domain agnostic.\r\n return this.transpiler.transpile(contents, this.getPathName());\r\n };\r\n\r\n\r\n /**\r\n * An ES6 module dependency that was transpiled to a jscomp module outside\r\n * of the debug loader, e.g. server side.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @struct @constructor\r\n * @extends {goog.TransformedDependency}\r\n */\r\n goog.PreTranspiledEs6ModuleDependency = function(\r\n path, relativePath, provides, requires, loadFlags) {\r\n goog.PreTranspiledEs6ModuleDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n };\r\n goog.inherits(\r\n goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\r\n\r\n\r\n /** @override */\r\n goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\r\n contents) {\r\n return contents;\r\n };\r\n\r\n\r\n /**\r\n * A goog.module, transpiled or not. Will always perform some minimal\r\n * transformation even when not transpiled to wrap in a goog.loadModule\r\n * statement.\r\n *\r\n * @param {string} path Absolute path of this script.\r\n * @param {string} relativePath Path of this script relative to goog.basePath.\r\n * @param {!Array<string>} provides goog.provided or goog.module symbols\r\n * in this file.\r\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\r\n * this depends on.\r\n * @param {!Object<string, string>} loadFlags\r\n * @param {boolean} needsTranspile\r\n * @param {!goog.Transpiler} transpiler\r\n * @struct @constructor\r\n * @extends {goog.TransformedDependency}\r\n */\r\n goog.GoogModuleDependency = function(\r\n path, relativePath, provides, requires, loadFlags, needsTranspile,\r\n transpiler) {\r\n goog.GoogModuleDependency.base(\r\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\r\n /** @private @const */\r\n this.needsTranspile_ = needsTranspile;\r\n /** @private @const */\r\n this.transpiler_ = transpiler;\r\n };\r\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\r\n\r\n\r\n /** @override */\r\n goog.GoogModuleDependency.prototype.transform = function(contents) {\r\n if (this.needsTranspile_) {\r\n contents = this.transpiler_.transpile(contents, this.getPathName());\r\n }\r\n\r\n if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) {\r\n return '' +\r\n 'goog.loadModule(function(exports) {' +\r\n '\"use strict\";' + contents +\r\n '\\n' + // terminate any trailing single line comment.\r\n ';return exports' +\r\n '});' +\r\n '\\n//# sourceURL=' + this.path + '\\n';\r\n } else {\r\n return '' +\r\n 'goog.loadModule(' +\r\n goog.global.JSON.stringify(\r\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\r\n ');';\r\n }\r\n };\r\n\r\n\r\n /**\r\n * Whether the browser is IE9 or earlier, which needs special handling\r\n * for deferred modules.\r\n * @const @private {boolean}\r\n */\r\n goog.DebugLoader_.IS_OLD_IE_ = !!(\r\n !goog.global.atob && goog.global.document && goog.global.document['all']);\r\n\r\n\r\n /**\r\n * @param {string} relPath\r\n * @param {!Array<string>|undefined} provides\r\n * @param {!Array<string>} requires\r\n * @param {boolean|!Object<string>=} opt_loadFlags\r\n * @see goog.addDependency\r\n */\r\n goog.DebugLoader_.prototype.addDependency = function(\r\n relPath, provides, requires, opt_loadFlags) {\r\n provides = provides || [];\r\n relPath = relPath.replace(/\\\\/g, '/');\r\n var path = goog.normalizePath_(goog.basePath + relPath);\r\n if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\r\n opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\r\n }\r\n var dep = this.factory_.createDependency(\r\n path, relPath, provides, requires, opt_loadFlags,\r\n goog.transpiler_.needsTranspile(\r\n opt_loadFlags['lang'] || 'es3', opt_loadFlags['module']));\r\n this.dependencies_[path] = dep;\r\n for (var i = 0; i < provides.length; i++) {\r\n this.idToPath_[provides[i]] = path;\r\n }\r\n this.idToPath_[relPath] = path;\r\n };\r\n\r\n\r\n /**\r\n * Creates goog.Dependency instances for the debug loader to load.\r\n *\r\n * Should be overridden to have the debug loader use custom subclasses of\r\n * goog.Dependency.\r\n *\r\n * @param {!goog.Transpiler} transpiler\r\n * @struct @constructor\r\n */\r\n goog.DependencyFactory = function(transpiler) {\r\n /** @protected @const */\r\n this.transpiler = transpiler;\r\n };\r\n\r\n\r\n /**\r\n * @param {string} path Absolute path of the file.\r\n * @param {string} relativePath Path relative to closure’s base.js.\r\n * @param {!Array<string>} provides Array of provided goog.provide/module ids.\r\n * @param {!Array<string>} requires Array of required goog.provide/module /\r\n * relative ES6 module paths.\r\n * @param {!Object<string, string>} loadFlags\r\n * @param {boolean} needsTranspile True if the file needs to be transpiled\r\n * per the goog.Transpiler.\r\n * @return {!goog.Dependency}\r\n */\r\n goog.DependencyFactory.prototype.createDependency = function(\r\n path, relativePath, provides, requires, loadFlags, needsTranspile) {\r\n\r\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\r\n return new goog.GoogModuleDependency(\r\n path, relativePath, provides, requires, loadFlags, needsTranspile,\r\n this.transpiler);\r\n } else if (needsTranspile) {\r\n return new goog.TranspiledDependency(\r\n path, relativePath, provides, requires, loadFlags, this.transpiler);\r\n } else {\r\n if (loadFlags['module'] == goog.ModuleType.ES6) {\r\n if (goog.TRANSPILE == 'never' && goog.ASSUME_ES_MODULES_TRANSPILED) {\r\n return new goog.PreTranspiledEs6ModuleDependency(\r\n path, relativePath, provides, requires, loadFlags);\r\n } else {\r\n return new goog.Es6ModuleDependency(\r\n path, relativePath, provides, requires, loadFlags);\r\n }\r\n } else {\r\n return new goog.Dependency(\r\n path, relativePath, provides, requires, loadFlags);\r\n }\r\n }\r\n };\r\n\r\n\r\n /** @private @const */\r\n goog.debugLoader_ = new goog.DebugLoader_();\r\n\r\n\r\n /**\r\n * Loads the Closure Dependency file.\r\n *\r\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\r\n * loaded, setDependencyFactory called, and then this called. i.e. allows\r\n * custom loading of the deps file.\r\n */\r\n goog.loadClosureDeps = function() {\r\n goog.debugLoader_.loadClosureDeps();\r\n };\r\n\r\n\r\n /**\r\n * Sets the dependency factory, which can be used to create custom\r\n * goog.Dependency implementations to control how dependencies are loaded.\r\n *\r\n * Note: if you wish to call this function and provide your own implemnetation\r\n * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\r\n * file and all of its goog.addDependency calls will use the default factory.\r\n * You can call goog.loadClosureDeps to load the Closure dependency file\r\n * later, after your factory is injected.\r\n *\r\n * @param {!goog.DependencyFactory} factory\r\n */\r\n goog.setDependencyFactory = function(factory) {\r\n goog.debugLoader_.setDependencyFactory(factory);\r\n };\r\n\r\n\r\n if (!goog.global.CLOSURE_NO_DEPS) {\r\n goog.debugLoader_.loadClosureDeps();\r\n }\r\n\r\n\r\n /**\r\n * Bootstraps the given namespaces and calls the callback once they are\r\n * available either via goog.require. This is a replacement for using\r\n * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\r\n * in an HTML file would guarantee that the require'd namespace was available\r\n * in the next immediate script tag. With ES6 modules this no longer a\r\n * guarantee.\r\n *\r\n * @param {!Array<string>} namespaces\r\n * @param {function(): ?} callback Function to call once all the namespaces\r\n * have loaded. Always called asynchronously.\r\n */\r\n goog.bootstrap = function(namespaces, callback) {\r\n goog.debugLoader_.bootstrap(namespaces, callback);\r\n };\r\n}\r\n\r\n\r\n/**\r\n * @define {string} Trusted Types policy name. If non-empty then Closure will\r\n * use Trusted Types.\r\n */\r\ngoog.TRUSTED_TYPES_POLICY_NAME =\r\n goog.define('goog.TRUSTED_TYPES_POLICY_NAME', '');\r\n\r\n\r\n/**\r\n * Returns the parameter.\r\n * @param {string} s\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.identity_ = function(s) {\r\n return s;\r\n};\r\n\r\n\r\n/**\r\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\r\n * The policy just blesses any string as a Trusted Type. It is not visibility\r\n * restricted because anyone can also call TrustedTypes.createPolicy directly.\r\n * However, the allowed names should be restricted by a HTTP header and the\r\n * reference to the created policy should be visibility restricted.\r\n * @param {string} name\r\n * @return {?TrustedTypePolicy}\r\n * @throws {!TypeError} If called with a name which is already registered.\r\n */\r\ngoog.createTrustedTypesPolicy = function(name) {\r\n if (typeof TrustedTypes === 'undefined' || !TrustedTypes.createPolicy) {\r\n return null;\r\n }\r\n return TrustedTypes.createPolicy(name, {\r\n createHTML: goog.identity_,\r\n createScript: goog.identity_,\r\n createScriptURL: goog.identity_,\r\n createURL: goog.identity_\r\n });\r\n};\r\n\r\n\r\n/** @private @const {?TrustedTypePolicy} */\r\ngoog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\r\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\r\n null;\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Implements the disposable interface. The dispose method is used\r\n * to clean up references and resources.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.Disposable');\r\ngoog.provide('goog.dispose');\r\ngoog.provide('goog.disposeAll');\r\n\r\ngoog.require('goog.disposable.IDisposable');\r\n\r\n\r\n\r\n/**\r\n * Class that provides the basic implementation for disposable objects. If your\r\n * class holds one or more references to COM objects, DOM nodes, or other\r\n * disposable objects, it should extend this class or implement the disposable\r\n * interface (defined in goog.disposable.IDisposable).\r\n * @constructor\r\n * @implements {goog.disposable.IDisposable}\r\n */\r\ngoog.Disposable = function() {\r\n /**\r\n * If monitoring the goog.Disposable instances is enabled, stores the creation\r\n * stack trace of the Disposable instance.\r\n * @type {string|undefined}\r\n */\r\n this.creationStack;\r\n\r\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\r\n if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {\r\n this.creationStack = new Error().stack;\r\n }\r\n goog.Disposable.instances_[goog.getUid(this)] = this;\r\n }\r\n // Support sealing\r\n this.disposed_ = this.disposed_;\r\n this.onDisposeCallbacks_ = this.onDisposeCallbacks_;\r\n};\r\n\r\n\r\n/**\r\n * @enum {number} Different monitoring modes for Disposable.\r\n */\r\ngoog.Disposable.MonitoringMode = {\r\n /**\r\n * No monitoring.\r\n */\r\n OFF: 0,\r\n /**\r\n * Creating and disposing the goog.Disposable instances is monitored. All\r\n * disposable objects need to call the `goog.Disposable` base\r\n * constructor. The PERMANENT mode must be switched on before creating any\r\n * goog.Disposable instances.\r\n */\r\n PERMANENT: 1,\r\n /**\r\n * INTERACTIVE mode can be switched on and off on the fly without producing\r\n * errors. It also doesn't warn if the disposable objects don't call the\r\n * `goog.Disposable` base constructor.\r\n */\r\n INTERACTIVE: 2\r\n};\r\n\r\n\r\n/**\r\n * @define {number} The monitoring mode of the goog.Disposable\r\n * instances. Default is OFF. Switching on the monitoring is only\r\n * recommended for debugging because it has a significant impact on\r\n * performance and memory usage. If switched off, the monitoring code\r\n * compiles down to 0 bytes.\r\n */\r\ngoog.Disposable.MONITORING_MODE =\r\n goog.define('goog.Disposable.MONITORING_MODE', 0);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to attach creation stack to each created disposable\r\n * instance; This is only relevant for when MonitoringMode != OFF.\r\n */\r\ngoog.Disposable.INCLUDE_STACK_ON_CREATION =\r\n goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);\r\n\r\n\r\n/**\r\n * Maps the unique ID of every undisposed `goog.Disposable` object to\r\n * the object itself.\r\n * @type {!Object<number, !goog.Disposable>}\r\n * @private\r\n */\r\ngoog.Disposable.instances_ = {};\r\n\r\n\r\n/**\r\n * @return {!Array<!goog.Disposable>} All `goog.Disposable` objects that\r\n * haven't been disposed of.\r\n */\r\ngoog.Disposable.getUndisposedObjects = function() {\r\n var ret = [];\r\n for (var id in goog.Disposable.instances_) {\r\n if (goog.Disposable.instances_.hasOwnProperty(id)) {\r\n ret.push(goog.Disposable.instances_[Number(id)]);\r\n }\r\n }\r\n return ret;\r\n};\r\n\r\n\r\n/**\r\n * Clears the registry of undisposed objects but doesn't dispose of them.\r\n */\r\ngoog.Disposable.clearUndisposedObjects = function() {\r\n goog.Disposable.instances_ = {};\r\n};\r\n\r\n\r\n/**\r\n * Whether the object has been disposed of.\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.Disposable.prototype.disposed_ = false;\r\n\r\n\r\n/**\r\n * Callbacks to invoke when this object is disposed.\r\n * @type {Array<!Function>}\r\n * @private\r\n */\r\ngoog.Disposable.prototype.onDisposeCallbacks_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the object has been disposed of.\r\n * @override\r\n */\r\ngoog.Disposable.prototype.isDisposed = function() {\r\n return this.disposed_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the object has been disposed of.\r\n * @deprecated Use {@link #isDisposed} instead.\r\n */\r\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\r\n\r\n\r\n/**\r\n * Disposes of the object. If the object hasn't already been disposed of, calls\r\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\r\n * override {@link #disposeInternal} in order to delete references to COM\r\n * objects, DOM nodes, and other disposable objects. Reentrant.\r\n *\r\n * @return {void} Nothing.\r\n * @override\r\n */\r\ngoog.Disposable.prototype.dispose = function() {\r\n if (!this.disposed_) {\r\n // Set disposed_ to true first, in case during the chain of disposal this\r\n // gets disposed recursively.\r\n this.disposed_ = true;\r\n this.disposeInternal();\r\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\r\n var uid = goog.getUid(this);\r\n if (goog.Disposable.MONITORING_MODE ==\r\n goog.Disposable.MonitoringMode.PERMANENT &&\r\n !goog.Disposable.instances_.hasOwnProperty(uid)) {\r\n throw new Error(\r\n this + ' did not call the goog.Disposable base ' +\r\n 'constructor or was disposed of after a clearUndisposedObjects ' +\r\n 'call');\r\n }\r\n if (goog.Disposable.MONITORING_MODE !=\r\n goog.Disposable.MonitoringMode.OFF &&\r\n this.onDisposeCallbacks_ && this.onDisposeCallbacks_.length > 0) {\r\n throw new Error(\r\n this + ' did not empty its onDisposeCallbacks queue. This ' +\r\n 'probably means it overrode dispose() or disposeInternal() ' +\r\n 'without calling the superclass\\' method.');\r\n }\r\n delete goog.Disposable.instances_[uid];\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Associates a disposable object with this object so that they will be disposed\r\n * together.\r\n * @param {goog.disposable.IDisposable} disposable that will be disposed when\r\n * this object is disposed.\r\n */\r\ngoog.Disposable.prototype.registerDisposable = function(disposable) {\r\n this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));\r\n};\r\n\r\n\r\n/**\r\n * Invokes a callback function when this object is disposed. Callbacks are\r\n * invoked in the order in which they were added. If a callback is added to\r\n * an already disposed Disposable, it will be called immediately.\r\n * @param {function(this:T):?} callback The callback function.\r\n * @param {T=} opt_scope An optional scope to call the callback in.\r\n * @template T\r\n */\r\ngoog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {\r\n if (this.disposed_) {\r\n goog.isDef(opt_scope) ? callback.call(opt_scope) : callback();\r\n return;\r\n }\r\n if (!this.onDisposeCallbacks_) {\r\n this.onDisposeCallbacks_ = [];\r\n }\r\n\r\n this.onDisposeCallbacks_.push(\r\n goog.isDef(opt_scope) ? goog.bind(callback, opt_scope) : callback);\r\n};\r\n\r\n\r\n/**\r\n * Deletes or nulls out any references to COM objects, DOM nodes, or other\r\n * disposable objects. Classes that extend `goog.Disposable` should\r\n * override this method.\r\n * Not reentrant. To avoid calling it twice, it must only be called from the\r\n * subclass' `disposeInternal` method. Everywhere else the public\r\n * `dispose` method must be used.\r\n * For example:\r\n * <pre>\r\n * mypackage.MyClass = function() {\r\n * mypackage.MyClass.base(this, 'constructor');\r\n * // Constructor logic specific to MyClass.\r\n * ...\r\n * };\r\n * goog.inherits(mypackage.MyClass, goog.Disposable);\r\n *\r\n * mypackage.MyClass.prototype.disposeInternal = function() {\r\n * // Dispose logic specific to MyClass.\r\n * ...\r\n * // Call superclass's disposeInternal at the end of the subclass's, like\r\n * // in C++, to avoid hard-to-catch issues.\r\n * mypackage.MyClass.base(this, 'disposeInternal');\r\n * };\r\n * </pre>\r\n * @protected\r\n */\r\ngoog.Disposable.prototype.disposeInternal = function() {\r\n if (this.onDisposeCallbacks_) {\r\n while (this.onDisposeCallbacks_.length) {\r\n this.onDisposeCallbacks_.shift()();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns True if we can verify the object is disposed.\r\n * Calls `isDisposed` on the argument if it supports it. If obj\r\n * is not an object with an isDisposed() method, return false.\r\n * @param {*} obj The object to investigate.\r\n * @return {boolean} True if we can verify the object is disposed.\r\n */\r\ngoog.Disposable.isDisposed = function(obj) {\r\n if (obj && typeof obj.isDisposed == 'function') {\r\n return obj.isDisposed();\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Calls `dispose` on the argument if it supports it. If obj is not an\r\n * object with a dispose() method, this is a no-op.\r\n * @param {*} obj The object to dispose of.\r\n */\r\ngoog.dispose = function(obj) {\r\n if (obj && typeof obj.dispose == 'function') {\r\n obj.dispose();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls `dispose` on each member of the list that supports it. (If the\r\n * member is an ArrayLike, then `goog.disposeAll()` will be called\r\n * recursively on each of its members.) If the member is not an object with a\r\n * `dispose()` method, then it is ignored.\r\n * @param {...*} var_args The list.\r\n */\r\ngoog.disposeAll = function(var_args) {\r\n for (var i = 0, len = arguments.length; i < len; ++i) {\r\n var disposable = arguments[i];\r\n if (goog.isArrayLike(disposable)) {\r\n goog.disposeAll.apply(null, disposable);\r\n } else {\r\n goog.dispose(disposable);\r\n }\r\n }\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for manipulating arrays.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.array');\r\n\r\ngoog.require('goog.asserts');\r\n\r\n\r\n/**\r\n * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should\r\n * rely on Array.prototype functions, if available.\r\n *\r\n * The Array.prototype functions can be defined by external libraries like\r\n * Prototype and setting this flag to false forces closure to use its own\r\n * goog.array implementation.\r\n *\r\n * If your javascript can be loaded by a third party site and you are wary about\r\n * relying on the prototype functions, specify\r\n * \"--define goog.NATIVE_ARRAY_PROTOTYPES=false\" to the JSCompiler.\r\n *\r\n * Setting goog.TRUSTED_SITE to false will automatically set\r\n * NATIVE_ARRAY_PROTOTYPES to false.\r\n */\r\ngoog.NATIVE_ARRAY_PROTOTYPES =\r\n goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);\r\n\r\n\r\n/**\r\n * @define {boolean} If true, JSCompiler will use the native implementation of\r\n * array functions where appropriate (e.g., `Array#filter`) and remove the\r\n * unused pure JS implementation.\r\n */\r\ngoog.array.ASSUME_NATIVE_FUNCTIONS =\r\n goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);\r\n\r\n\r\n/**\r\n * Returns the last element in an array without removing it.\r\n * Same as goog.array.last.\r\n * @param {IArrayLike<T>|string} array The array.\r\n * @return {T} Last item in array.\r\n * @template T\r\n */\r\ngoog.array.peek = function(array) {\r\n return array[array.length - 1];\r\n};\r\n\r\n\r\n/**\r\n * Returns the last element in an array without removing it.\r\n * Same as goog.array.peek.\r\n * @param {IArrayLike<T>|string} array The array.\r\n * @return {T} Last item in array.\r\n * @template T\r\n */\r\ngoog.array.last = goog.array.peek;\r\n\r\n// NOTE(arv): Since most of the array functions are generic it allows you to\r\n// pass an array-like object. Strings have a length and are considered array-\r\n// like. However, the 'in' operator does not work on strings so we cannot just\r\n// use the array path even if the browser supports indexing into strings. We\r\n// therefore end up splitting the string.\r\n\r\n\r\n/**\r\n * Returns the index of the first element of an array with a specified value, or\r\n * -1 if the element is not present in the array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}\r\n *\r\n * @param {IArrayLike<T>|string} arr The array to be searched.\r\n * @param {T} obj The object for which we are searching.\r\n * @param {number=} opt_fromIndex The index at which to start the search. If\r\n * omitted the search starts at index 0.\r\n * @return {number} The index of the first matching array element.\r\n * @template T\r\n */\r\ngoog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\r\n function(arr, obj, opt_fromIndex) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\r\n } :\r\n function(arr, obj, opt_fromIndex) {\r\n var fromIndex = opt_fromIndex == null ?\r\n 0 :\r\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\r\n opt_fromIndex);\r\n\r\n if (goog.isString(arr)) {\r\n // Array.prototype.indexOf uses === so only strings should be found.\r\n if (!goog.isString(obj) || obj.length != 1) {\r\n return -1;\r\n }\r\n return arr.indexOf(obj, fromIndex);\r\n }\r\n\r\n for (var i = fromIndex; i < arr.length; i++) {\r\n if (i in arr && arr[i] === obj) return i;\r\n }\r\n return -1;\r\n };\r\n\r\n\r\n/**\r\n * Returns the index of the last element of an array with a specified value, or\r\n * -1 if the element is not present in the array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}\r\n *\r\n * @param {!IArrayLike<T>|string} arr The array to be searched.\r\n * @param {T} obj The object for which we are searching.\r\n * @param {?number=} opt_fromIndex The index at which to start the search. If\r\n * omitted the search starts at the end of the array.\r\n * @return {number} The index of the last matching array element.\r\n * @template T\r\n */\r\ngoog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\r\n function(arr, obj, opt_fromIndex) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n // Firefox treats undefined and null as 0 in the fromIndex argument which\r\n // leads it to always return -1\r\n var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\r\n return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);\r\n } :\r\n function(arr, obj, opt_fromIndex) {\r\n var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\r\n\r\n if (fromIndex < 0) {\r\n fromIndex = Math.max(0, arr.length + fromIndex);\r\n }\r\n\r\n if (goog.isString(arr)) {\r\n // Array.prototype.lastIndexOf uses === so only strings should be found.\r\n if (!goog.isString(obj) || obj.length != 1) {\r\n return -1;\r\n }\r\n return arr.lastIndexOf(obj, fromIndex);\r\n }\r\n\r\n for (var i = fromIndex; i >= 0; i--) {\r\n if (i in arr && arr[i] === obj) return i;\r\n }\r\n return -1;\r\n };\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array. Skips holes in the array.\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array like object over\r\n * which to iterate.\r\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\r\n * element. This function takes 3 arguments (the element, the index and the\r\n * array). The return value is ignored.\r\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\r\n * @template T,S\r\n */\r\ngoog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n Array.prototype.forEach.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2) {\r\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\r\n }\r\n }\r\n };\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array, starting from the last\r\n * element rather than the first.\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\r\n * element. This function\r\n * takes 3 arguments (the element, the index and the array). The return\r\n * value is ignored.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @template T,S\r\n */\r\ngoog.array.forEachRight = function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = l - 1; i >= 0; --i) {\r\n if (i in arr2) {\r\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array, and if the function returns\r\n * true adds the element to a new array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?):boolean} f The function to call for\r\n * every element. This function\r\n * takes 3 arguments (the element, the index and the array) and must\r\n * return a Boolean. If the return value is true the element is added to the\r\n * result array. If it is false the element is not included.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {!Array<T>} a new array in which only elements that passed the test\r\n * are present.\r\n * @template T,S\r\n */\r\ngoog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.filter.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var res = [];\r\n var resLength = 0;\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2) {\r\n var val = arr2[i]; // in case f mutates arr2\r\n if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {\r\n res[resLength++] = val;\r\n }\r\n }\r\n }\r\n return res;\r\n };\r\n\r\n\r\n/**\r\n * Calls a function for each element in an array and inserts the result into a\r\n * new array.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-map}\r\n *\r\n * @param {IArrayLike<VALUE>|string} arr Array or array like object\r\n * over which to iterate.\r\n * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call\r\n * for every element. This function takes 3 arguments (the element,\r\n * the index and the array) and should return something. The result will be\r\n * inserted into a new array.\r\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\r\n * @return {!Array<RESULT>} a new array with the results from f.\r\n * @template THIS, VALUE, RESULT\r\n */\r\ngoog.array.map = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.map.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var res = new Array(l);\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2) {\r\n res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\r\n }\r\n }\r\n return res;\r\n };\r\n\r\n\r\n/**\r\n * Passes every element of an array into a function and accumulates the result.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}\r\n *\r\n * For example:\r\n * var a = [1, 2, 3, 4];\r\n * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0);\r\n * returns 10\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {function(this:S, R, T, number, ?) : R} f The function to call for\r\n * every element. This function\r\n * takes 4 arguments (the function's previous result or the initial value,\r\n * the value of the current array element, the current array index, and the\r\n * array itself)\r\n * function(previousValue, currentValue, index, array).\r\n * @param {?} val The initial value to pass into the function on the first call.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {R} Result of evaluating f repeatedly across the values of the array.\r\n * @template T,S,R\r\n */\r\ngoog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\r\n function(arr, f, val, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n if (opt_obj) {\r\n f = goog.bind(f, opt_obj);\r\n }\r\n return Array.prototype.reduce.call(arr, f, val);\r\n } :\r\n function(arr, f, val, opt_obj) {\r\n var rval = val;\r\n goog.array.forEach(arr, function(val, index) {\r\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\r\n });\r\n return rval;\r\n };\r\n\r\n\r\n/**\r\n * Passes every element of an array into a function and accumulates the result,\r\n * starting from the last element and working towards the first.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}\r\n *\r\n * For example:\r\n * var a = ['a', 'b', 'c'];\r\n * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, '');\r\n * returns 'cba'\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, R, T, number, ?) : R} f The function to call for\r\n * every element. This function\r\n * takes 4 arguments (the function's previous result or the initial value,\r\n * the value of the current array element, the current array index, and the\r\n * array itself)\r\n * function(previousValue, currentValue, index, array).\r\n * @param {?} val The initial value to pass into the function on the first call.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {R} Object returned as a result of evaluating f repeatedly across the\r\n * values of the array.\r\n * @template T,S,R\r\n */\r\ngoog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\r\n function(arr, f, val, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n goog.asserts.assert(f != null);\r\n if (opt_obj) {\r\n f = goog.bind(f, opt_obj);\r\n }\r\n return Array.prototype.reduceRight.call(arr, f, val);\r\n } :\r\n function(arr, f, val, opt_obj) {\r\n var rval = val;\r\n goog.array.forEachRight(arr, function(val, index) {\r\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\r\n });\r\n return rval;\r\n };\r\n\r\n\r\n/**\r\n * Calls f for each element of an array. If any call returns true, some()\r\n * returns true (without checking the remaining elements). If all calls\r\n * return false, some() returns false.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-some}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\r\n * for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a boolean.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {boolean} true if any element passes the test.\r\n * @template T,S\r\n */\r\ngoog.array.some = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.some.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n\r\n\r\n/**\r\n * Call f for each element of an array. If all calls return true, every()\r\n * returns true. If any call returns false, every() returns false and\r\n * does not continue to check the remaining elements.\r\n *\r\n * See {@link http://tinyurl.com/developer-mozilla-org-array-every}\r\n *\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\r\n * for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a boolean.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within f.\r\n * @return {boolean} false if any element fails the test.\r\n * @template T,S\r\n */\r\ngoog.array.every = goog.NATIVE_ARRAY_PROTOTYPES &&\r\n (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\r\n function(arr, f, opt_obj) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.every.call(arr, f, opt_obj);\r\n } :\r\n function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n\r\n\r\n/**\r\n * Counts the array elements that fulfill the predicate, i.e. for which the\r\n * callback function returns true. Skips holes in the array.\r\n *\r\n * @param {!IArrayLike<T>|string} arr Array or array like object\r\n * over which to iterate.\r\n * @param {function(this: S, T, number, ?): boolean} f The function to call for\r\n * every element. Takes 3 arguments (the element, the index and the array).\r\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\r\n * @return {number} The number of the matching elements.\r\n * @template T,S\r\n */\r\ngoog.array.count = function(arr, f, opt_obj) {\r\n var count = 0;\r\n goog.array.forEach(arr, function(element, index, arr) {\r\n if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {\r\n ++count;\r\n }\r\n }, opt_obj);\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Search an array for the first element that satisfies a given condition and\r\n * return that element.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {T|null} The first array element that passes the test, or null if no\r\n * element is found.\r\n * @template T,S\r\n */\r\ngoog.array.find = function(arr, f, opt_obj) {\r\n var i = goog.array.findIndex(arr, f, opt_obj);\r\n return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];\r\n};\r\n\r\n\r\n/**\r\n * Search an array for the first element that satisfies a given condition and\r\n * return its index.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\r\n * every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {number} The index of the first array element that passes the test,\r\n * or -1 if no element is found.\r\n * @template T,S\r\n */\r\ngoog.array.findIndex = function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = 0; i < l; i++) {\r\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n};\r\n\r\n\r\n/**\r\n * Search an array (in reverse order) for the last element that satisfies a\r\n * given condition and return that element.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {T|null} The last array element that passes the test, or null if no\r\n * element is found.\r\n * @template T,S\r\n */\r\ngoog.array.findRight = function(arr, f, opt_obj) {\r\n var i = goog.array.findIndexRight(arr, f, opt_obj);\r\n return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i];\r\n};\r\n\r\n\r\n/**\r\n * Search an array (in reverse order) for the last element that satisfies a\r\n * given condition and return its index.\r\n * @param {IArrayLike<T>|string} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {number} The index of the last array element that passes the test,\r\n * or -1 if no element is found.\r\n * @template T,S\r\n */\r\ngoog.array.findIndexRight = function(arr, f, opt_obj) {\r\n var l = arr.length; // must be fixed during loop... see docs\r\n var arr2 = goog.isString(arr) ? arr.split('') : arr;\r\n for (var i = l - 1; i >= 0; i--) {\r\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n};\r\n\r\n\r\n/**\r\n * Whether the array contains the given object.\r\n * @param {IArrayLike<?>|string} arr The array to test for the presence of the\r\n * element.\r\n * @param {*} obj The object for which to test.\r\n * @return {boolean} true if obj is present.\r\n */\r\ngoog.array.contains = function(arr, obj) {\r\n return goog.array.indexOf(arr, obj) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * Whether the array is empty.\r\n * @param {IArrayLike<?>|string} arr The array to test.\r\n * @return {boolean} true if empty.\r\n */\r\ngoog.array.isEmpty = function(arr) {\r\n return arr.length == 0;\r\n};\r\n\r\n\r\n/**\r\n * Clears the array.\r\n * @param {IArrayLike<?>} arr Array or array like object to clear.\r\n */\r\ngoog.array.clear = function(arr) {\r\n // For non real arrays we don't have the magic length so we delete the\r\n // indices.\r\n if (!goog.isArray(arr)) {\r\n for (var i = arr.length - 1; i >= 0; i--) {\r\n delete arr[i];\r\n }\r\n }\r\n arr.length = 0;\r\n};\r\n\r\n\r\n/**\r\n * Pushes an item into an array, if it's not already in the array.\r\n * @param {Array<T>} arr Array into which to insert the item.\r\n * @param {T} obj Value to add.\r\n * @template T\r\n */\r\ngoog.array.insert = function(arr, obj) {\r\n if (!goog.array.contains(arr, obj)) {\r\n arr.push(obj);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Inserts an object at the given index of the array.\r\n * @param {IArrayLike<?>} arr The array to modify.\r\n * @param {*} obj The object to insert.\r\n * @param {number=} opt_i The index at which to insert the object. If omitted,\r\n * treated as 0. A negative index is counted from the end of the array.\r\n */\r\ngoog.array.insertAt = function(arr, obj, opt_i) {\r\n goog.array.splice(arr, opt_i, 0, obj);\r\n};\r\n\r\n\r\n/**\r\n * Inserts at the given index of the array, all elements of another array.\r\n * @param {IArrayLike<?>} arr The array to modify.\r\n * @param {IArrayLike<?>} elementsToAdd The array of elements to add.\r\n * @param {number=} opt_i The index at which to insert the object. If omitted,\r\n * treated as 0. A negative index is counted from the end of the array.\r\n */\r\ngoog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) {\r\n goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd);\r\n};\r\n\r\n\r\n/**\r\n * Inserts an object into an array before a specified object.\r\n * @param {Array<T>} arr The array to modify.\r\n * @param {T} obj The object to insert.\r\n * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2\r\n * is omitted or not found, obj is inserted at the end of the array.\r\n * @template T\r\n */\r\ngoog.array.insertBefore = function(arr, obj, opt_obj2) {\r\n var i;\r\n if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) {\r\n arr.push(obj);\r\n } else {\r\n goog.array.insertAt(arr, obj, i);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes the first occurrence of a particular value from an array.\r\n * @param {IArrayLike<T>} arr Array from which to remove\r\n * value.\r\n * @param {T} obj Object to remove.\r\n * @return {boolean} True if an element was removed.\r\n * @template T\r\n */\r\ngoog.array.remove = function(arr, obj) {\r\n var i = goog.array.indexOf(arr, obj);\r\n var rv;\r\n if ((rv = i >= 0)) {\r\n goog.array.removeAt(arr, i);\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Removes the last occurrence of a particular value from an array.\r\n * @param {!IArrayLike<T>} arr Array from which to remove value.\r\n * @param {T} obj Object to remove.\r\n * @return {boolean} True if an element was removed.\r\n * @template T\r\n */\r\ngoog.array.removeLast = function(arr, obj) {\r\n var i = goog.array.lastIndexOf(arr, obj);\r\n if (i >= 0) {\r\n goog.array.removeAt(arr, i);\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes from an array the element at index i\r\n * @param {IArrayLike<?>} arr Array or array like object from which to\r\n * remove value.\r\n * @param {number} i The index to remove.\r\n * @return {boolean} True if an element was removed.\r\n */\r\ngoog.array.removeAt = function(arr, i) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n // use generic form of splice\r\n // splice returns the removed items and if successful the length of that\r\n // will be 1\r\n return Array.prototype.splice.call(arr, i, 1).length == 1;\r\n};\r\n\r\n\r\n/**\r\n * Removes the first value that satisfies the given condition.\r\n * @param {IArrayLike<T>} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {boolean} True if an element was removed.\r\n * @template T,S\r\n */\r\ngoog.array.removeIf = function(arr, f, opt_obj) {\r\n var i = goog.array.findIndex(arr, f, opt_obj);\r\n if (i >= 0) {\r\n goog.array.removeAt(arr, i);\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes all values that satisfy the given condition.\r\n * @param {IArrayLike<T>} arr Array or array\r\n * like object over which to iterate.\r\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the element, the index and the array) and should\r\n * return a boolean.\r\n * @param {S=} opt_obj An optional \"this\" context for the function.\r\n * @return {number} The number of items removed\r\n * @template T,S\r\n */\r\ngoog.array.removeAllIf = function(arr, f, opt_obj) {\r\n var removedCount = 0;\r\n goog.array.forEachRight(arr, function(val, index) {\r\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\r\n if (goog.array.removeAt(arr, index)) {\r\n removedCount++;\r\n }\r\n }\r\n });\r\n return removedCount;\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array that is the result of joining the arguments. If arrays\r\n * are passed then their items are added, however, if non-arrays are passed they\r\n * will be added to the return array as is.\r\n *\r\n * Note that ArrayLike objects will be added as is, rather than having their\r\n * items added.\r\n *\r\n * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\r\n * goog.array.concat(0, [1, 2]) -> [0, 1, 2]\r\n * goog.array.concat([1, 2], null) -> [1, 2, null]\r\n *\r\n * There is bug in all current versions of IE (6, 7 and 8) where arrays created\r\n * in an iframe become corrupted soon (not immediately) after the iframe is\r\n * destroyed. This is common if loading data via goog.net.IframeIo, for example.\r\n * This corruption only affects the concat method which will start throwing\r\n * Catastrophic Errors (#-2147418113).\r\n *\r\n * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.\r\n *\r\n * Internally goog.array should use this, so that all methods will continue to\r\n * work on these broken array objects.\r\n *\r\n * @param {...*} var_args Items to concatenate. Arrays will have each item\r\n * added, while primitives and objects will be added as is.\r\n * @return {!Array<?>} The new resultant array.\r\n */\r\ngoog.array.concat = function(var_args) {\r\n return Array.prototype.concat.apply([], arguments);\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array that contains the contents of all the arrays passed.\r\n * @param {...!Array<T>} var_args\r\n * @return {!Array<T>}\r\n * @template T\r\n */\r\ngoog.array.join = function(var_args) {\r\n return Array.prototype.concat.apply([], arguments);\r\n};\r\n\r\n\r\n/**\r\n * Converts an object to an array.\r\n * @param {IArrayLike<T>|string} object The object to convert to an\r\n * array.\r\n * @return {!Array<T>} The object converted into an array. If object has a\r\n * length property, every property indexed with a non-negative number\r\n * less than length will be included in the result. If object does not\r\n * have a length property, an empty array will be returned.\r\n * @template T\r\n */\r\ngoog.array.toArray = function(object) {\r\n var length = object.length;\r\n\r\n // If length is not a number the following is false. This case is kept for\r\n // backwards compatibility since there are callers that pass objects that are\r\n // not array like.\r\n if (length > 0) {\r\n var rv = new Array(length);\r\n for (var i = 0; i < length; i++) {\r\n rv[i] = object[i];\r\n }\r\n return rv;\r\n }\r\n return [];\r\n};\r\n\r\n\r\n/**\r\n * Does a shallow copy of an array.\r\n * @param {IArrayLike<T>|string} arr Array or array-like object to\r\n * clone.\r\n * @return {!Array<T>} Clone of the input array.\r\n * @template T\r\n */\r\ngoog.array.clone = goog.array.toArray;\r\n\r\n\r\n/**\r\n * Extends an array with another array, element, or \"array like\" object.\r\n * This function operates 'in-place', it does not create a new Array.\r\n *\r\n * Example:\r\n * var a = [];\r\n * goog.array.extend(a, [0, 1]);\r\n * a; // [0, 1]\r\n * goog.array.extend(a, 2);\r\n * a; // [0, 1, 2]\r\n *\r\n * @param {Array<VALUE>} arr1 The array to modify.\r\n * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of\r\n * elements to add to arr1.\r\n * @template VALUE\r\n */\r\ngoog.array.extend = function(arr1, var_args) {\r\n for (var i = 1; i < arguments.length; i++) {\r\n var arr2 = arguments[i];\r\n if (goog.isArrayLike(arr2)) {\r\n var len1 = arr1.length || 0;\r\n var len2 = arr2.length || 0;\r\n arr1.length = len1 + len2;\r\n for (var j = 0; j < len2; j++) {\r\n arr1[len1 + j] = arr2[j];\r\n }\r\n } else {\r\n arr1.push(arr2);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds or removes elements from an array. This is a generic version of Array\r\n * splice. This means that it might work on other objects similar to arrays,\r\n * such as the arguments object.\r\n *\r\n * @param {IArrayLike<T>} arr The array to modify.\r\n * @param {number|undefined} index The index at which to start changing the\r\n * array. If not defined, treated as 0.\r\n * @param {number} howMany How many elements to remove (0 means no removal. A\r\n * value below 0 is treated as zero and so is any other non number. Numbers\r\n * are floored).\r\n * @param {...T} var_args Optional, additional elements to insert into the\r\n * array.\r\n * @return {!Array<T>} the removed elements.\r\n * @template T\r\n */\r\ngoog.array.splice = function(arr, index, howMany, var_args) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n return Array.prototype.splice.apply(arr, goog.array.slice(arguments, 1));\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array from a segment of an array. This is a generic version of\r\n * Array slice. This means that it might work on other objects similar to\r\n * arrays, such as the arguments object.\r\n *\r\n * @param {IArrayLike<T>|string} arr The array from\r\n * which to copy a segment.\r\n * @param {number} start The index of the first element to copy.\r\n * @param {number=} opt_end The index after the last element to copy.\r\n * @return {!Array<T>} A new array containing the specified segment of the\r\n * original array.\r\n * @template T\r\n */\r\ngoog.array.slice = function(arr, start, opt_end) {\r\n goog.asserts.assert(arr.length != null);\r\n\r\n // passing 1 arg to slice is not the same as passing 2 where the second is\r\n // null or undefined (in that case the second argument is treated as 0).\r\n // we could use slice on the arguments object and then use apply instead of\r\n // testing the length\r\n if (arguments.length <= 2) {\r\n return Array.prototype.slice.call(arr, start);\r\n } else {\r\n return Array.prototype.slice.call(arr, start, opt_end);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes all duplicates from an array (retaining only the first\r\n * occurrence of each array element). This function modifies the\r\n * array in place and doesn't change the order of the non-duplicate items.\r\n *\r\n * For objects, duplicates are identified as having the same unique ID as\r\n * defined by {@link goog.getUid}.\r\n *\r\n * Alternatively you can specify a custom hash function that returns a unique\r\n * value for each item in the array it should consider unique.\r\n *\r\n * Runtime: N,\r\n * Worstcase space: 2N (no dupes)\r\n *\r\n * @param {IArrayLike<T>} arr The array from which to remove\r\n * duplicates.\r\n * @param {Array=} opt_rv An optional array in which to return the results,\r\n * instead of performing the removal inplace. If specified, the original\r\n * array will remain unchanged.\r\n * @param {function(T):string=} opt_hashFn An optional function to use to\r\n * apply to every item in the array. This function should return a unique\r\n * value for each item in the array it should consider unique.\r\n * @template T\r\n */\r\ngoog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) {\r\n var returnArray = opt_rv || arr;\r\n var defaultHashFn = function(item) {\r\n // Prefix each type with a single character representing the type to\r\n // prevent conflicting keys (e.g. true and 'true').\r\n return goog.isObject(item) ? 'o' + goog.getUid(item) :\r\n (typeof item).charAt(0) + item;\r\n };\r\n var hashFn = opt_hashFn || defaultHashFn;\r\n\r\n var seen = {}, cursorInsert = 0, cursorRead = 0;\r\n while (cursorRead < arr.length) {\r\n var current = arr[cursorRead++];\r\n var key = hashFn(current);\r\n if (!Object.prototype.hasOwnProperty.call(seen, key)) {\r\n seen[key] = true;\r\n returnArray[cursorInsert++] = current;\r\n }\r\n }\r\n returnArray.length = cursorInsert;\r\n};\r\n\r\n\r\n/**\r\n * Searches the specified array for the specified target using the binary\r\n * search algorithm. If no opt_compareFn is specified, elements are compared\r\n * using <code>goog.array.defaultCompare</code>, which compares the elements\r\n * using the built in < and > operators. This will produce the expected\r\n * behavior for homogeneous arrays of String(s) and Number(s). The array\r\n * specified <b>must</b> be sorted in ascending order (as defined by the\r\n * comparison function). If the array is not sorted, results are undefined.\r\n * If the array contains multiple instances of the specified target value, any\r\n * of these instances may be found.\r\n *\r\n * Runtime: O(log n)\r\n *\r\n * @param {IArrayLike<VALUE>} arr The array to be searched.\r\n * @param {TARGET} target The sought value.\r\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is ordered. Should take 2 arguments to\r\n * compare, the target value and an element from your array, and return a\r\n * negative number, zero, or a positive number depending on whether the\r\n * first argument is less than, equal to, or greater than the second.\r\n * @return {number} Lowest index of the target value if found, otherwise\r\n * (-(insertion point) - 1). The insertion point is where the value should\r\n * be inserted into arr to preserve the sorted property. Return value >= 0\r\n * iff target is found.\r\n * @template TARGET, VALUE\r\n */\r\ngoog.array.binarySearch = function(arr, target, opt_compareFn) {\r\n return goog.array.binarySearch_(\r\n arr, opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */,\r\n target);\r\n};\r\n\r\n\r\n/**\r\n * Selects an index in the specified array using the binary search algorithm.\r\n * The evaluator receives an element and determines whether the desired index\r\n * is before, at, or after it. The evaluator must be consistent (formally,\r\n * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign)\r\n * must be monotonically non-increasing).\r\n *\r\n * Runtime: O(log n)\r\n *\r\n * @param {IArrayLike<VALUE>} arr The array to be searched.\r\n * @param {function(this:THIS, VALUE, number, ?): number} evaluator\r\n * Evaluator function that receives 3 arguments (the element, the index and\r\n * the array). Should return a negative number, zero, or a positive number\r\n * depending on whether the desired index is before, at, or after the\r\n * element passed to it.\r\n * @param {THIS=} opt_obj The object to be used as the value of 'this'\r\n * within evaluator.\r\n * @return {number} Index of the leftmost element matched by the evaluator, if\r\n * such exists; otherwise (-(insertion point) - 1). The insertion point is\r\n * the index of the first element for which the evaluator returns negative,\r\n * or arr.length if no such element exists. The return value is non-negative\r\n * iff a match is found.\r\n * @template THIS, VALUE\r\n */\r\ngoog.array.binarySelect = function(arr, evaluator, opt_obj) {\r\n return goog.array.binarySearch_(\r\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\r\n opt_obj);\r\n};\r\n\r\n\r\n/**\r\n * Implementation of a binary search algorithm which knows how to use both\r\n * comparison functions and evaluators. If an evaluator is provided, will call\r\n * the evaluator with the given optional data object, conforming to the\r\n * interface defined in binarySelect. Otherwise, if a comparison function is\r\n * provided, will call the comparison function against the given data object.\r\n *\r\n * This implementation purposefully does not use goog.bind or goog.partial for\r\n * performance reasons.\r\n *\r\n * Runtime: O(log n)\r\n *\r\n * @param {IArrayLike<?>} arr The array to be searched.\r\n * @param {function(?, ?, ?): number | function(?, ?): number} compareFn\r\n * Either an evaluator or a comparison function, as defined by binarySearch\r\n * and binarySelect above.\r\n * @param {boolean} isEvaluator Whether the function is an evaluator or a\r\n * comparison function.\r\n * @param {?=} opt_target If the function is a comparison function, then\r\n * this is the target to binary search for.\r\n * @param {Object=} opt_selfObj If the function is an evaluator, this is an\r\n * optional this object for the evaluator.\r\n * @return {number} Lowest index of the target value if found, otherwise\r\n * (-(insertion point) - 1). The insertion point is where the value should\r\n * be inserted into arr to preserve the sorted property. Return value >= 0\r\n * iff target is found.\r\n * @private\r\n */\r\ngoog.array.binarySearch_ = function(\r\n arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\r\n var left = 0; // inclusive\r\n var right = arr.length; // exclusive\r\n var found;\r\n while (left < right) {\r\n var middle = (left + right) >> 1;\r\n var compareResult;\r\n if (isEvaluator) {\r\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\r\n } else {\r\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\r\n // for the type of binarySearch_, which the type system can't express yet.\r\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\r\n opt_target, arr[middle]);\r\n }\r\n if (compareResult > 0) {\r\n left = middle + 1;\r\n } else {\r\n right = middle;\r\n // We are looking for the lowest index so we can't return immediately.\r\n found = !compareResult;\r\n }\r\n }\r\n // left is the index if found, or the insertion point otherwise.\r\n // ~left is a shorthand for -left - 1.\r\n return found ? left : ~left;\r\n};\r\n\r\n\r\n/**\r\n * Sorts the specified array into ascending order. If no opt_compareFn is\r\n * specified, elements are compared using\r\n * <code>goog.array.defaultCompare</code>, which compares the elements using\r\n * the built in < and > operators. This will produce the expected behavior\r\n * for homogeneous arrays of String(s) and Number(s), unlike the native sort,\r\n * but will give unpredictable results for heterogeneous lists of strings and\r\n * numbers with different numbers of digits.\r\n *\r\n * This sort is not guaranteed to be stable.\r\n *\r\n * Runtime: Same as <code>Array.prototype.sort</code>\r\n *\r\n * @param {Array<T>} arr The array to be sorted.\r\n * @param {?function(T,T):number=} opt_compareFn Optional comparison\r\n * function by which the\r\n * array is to be ordered. Should take 2 arguments to compare, and return a\r\n * negative number, zero, or a positive number depending on whether the\r\n * first argument is less than, equal to, or greater than the second.\r\n * @template T\r\n */\r\ngoog.array.sort = function(arr, opt_compareFn) {\r\n // TODO(arv): Update type annotation since null is not accepted.\r\n arr.sort(opt_compareFn || goog.array.defaultCompare);\r\n};\r\n\r\n\r\n/**\r\n * Sorts the specified array into ascending order in a stable way. If no\r\n * opt_compareFn is specified, elements are compared using\r\n * <code>goog.array.defaultCompare</code>, which compares the elements using\r\n * the built in < and > operators. This will produce the expected behavior\r\n * for homogeneous arrays of String(s) and Number(s).\r\n *\r\n * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional\r\n * O(n) overhead of copying the array twice.\r\n *\r\n * @param {Array<T>} arr The array to be sorted.\r\n * @param {?function(T, T): number=} opt_compareFn Optional comparison function\r\n * by which the array is to be ordered. Should take 2 arguments to compare,\r\n * and return a negative number, zero, or a positive number depending on\r\n * whether the first argument is less than, equal to, or greater than the\r\n * second.\r\n * @template T\r\n */\r\ngoog.array.stableSort = function(arr, opt_compareFn) {\r\n var compArr = new Array(arr.length);\r\n for (var i = 0; i < arr.length; i++) {\r\n compArr[i] = {index: i, value: arr[i]};\r\n }\r\n var valueCompareFn = opt_compareFn || goog.array.defaultCompare;\r\n function stableCompareFn(obj1, obj2) {\r\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\r\n }\r\n goog.array.sort(compArr, stableCompareFn);\r\n for (var i = 0; i < arr.length; i++) {\r\n arr[i] = compArr[i].value;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sort the specified array into ascending order based on item keys\r\n * returned by the specified key function.\r\n * If no opt_compareFn is specified, the keys are compared in ascending order\r\n * using <code>goog.array.defaultCompare</code>.\r\n *\r\n * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code>\r\n * and f(n) is runtime of the key function.\r\n *\r\n * @param {Array<T>} arr The array to be sorted.\r\n * @param {function(T): K} keyFn Function taking array element and returning\r\n * a key used for sorting this element.\r\n * @param {?function(K, K): number=} opt_compareFn Optional comparison function\r\n * by which the keys are to be ordered. Should take 2 arguments to compare,\r\n * and return a negative number, zero, or a positive number depending on\r\n * whether the first argument is less than, equal to, or greater than the\r\n * second.\r\n * @template T,K\r\n */\r\ngoog.array.sortByKey = function(arr, keyFn, opt_compareFn) {\r\n var keyCompareFn = opt_compareFn || goog.array.defaultCompare;\r\n goog.array.sort(\r\n arr, function(a, b) { return keyCompareFn(keyFn(a), keyFn(b)); });\r\n};\r\n\r\n\r\n/**\r\n * Sorts an array of objects by the specified object key and compare\r\n * function. If no compare function is provided, the key values are\r\n * compared in ascending order using <code>goog.array.defaultCompare</code>.\r\n * This won't work for keys that get renamed by the compiler. So use\r\n * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.\r\n * @param {Array<Object>} arr An array of objects to sort.\r\n * @param {string} key The object key to sort by.\r\n * @param {Function=} opt_compareFn The function to use to compare key\r\n * values.\r\n */\r\ngoog.array.sortObjectsByKey = function(arr, key, opt_compareFn) {\r\n goog.array.sortByKey(arr, function(obj) { return obj[key]; }, opt_compareFn);\r\n};\r\n\r\n\r\n/**\r\n * Tells if the array is sorted.\r\n * @param {!IArrayLike<T>} arr The array.\r\n * @param {?function(T,T):number=} opt_compareFn Function to compare the\r\n * array elements.\r\n * Should take 2 arguments to compare, and return a negative number, zero,\r\n * or a positive number depending on whether the first argument is less\r\n * than, equal to, or greater than the second.\r\n * @param {boolean=} opt_strict If true no equal elements are allowed.\r\n * @return {boolean} Whether the array is sorted.\r\n * @template T\r\n */\r\ngoog.array.isSorted = function(arr, opt_compareFn, opt_strict) {\r\n var compare = opt_compareFn || goog.array.defaultCompare;\r\n for (var i = 1; i < arr.length; i++) {\r\n var compareResult = compare(arr[i - 1], arr[i]);\r\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Compares two arrays for equality. Two arrays are considered equal if they\r\n * have the same length and their corresponding elements are equal according to\r\n * the comparison function.\r\n *\r\n * @param {IArrayLike<?>} arr1 The first array to compare.\r\n * @param {IArrayLike<?>} arr2 The second array to compare.\r\n * @param {Function=} opt_equalsFn Optional comparison function.\r\n * Should take 2 arguments to compare, and return true if the arguments\r\n * are equal. Defaults to {@link goog.array.defaultCompareEquality} which\r\n * compares the elements using the built-in '===' operator.\r\n * @return {boolean} Whether the two arrays are equal.\r\n */\r\ngoog.array.equals = function(arr1, arr2, opt_equalsFn) {\r\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\r\n arr1.length != arr2.length) {\r\n return false;\r\n }\r\n var l = arr1.length;\r\n var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality;\r\n for (var i = 0; i < l; i++) {\r\n if (!equalsFn(arr1[i], arr2[i])) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * 3-way array compare function.\r\n * @param {!IArrayLike<VALUE>} arr1 The first array to\r\n * compare.\r\n * @param {!IArrayLike<VALUE>} arr2 The second array to\r\n * compare.\r\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is to be ordered. Should take 2 arguments to\r\n * compare, and return a negative number, zero, or a positive number\r\n * depending on whether the first argument is less than, equal to, or\r\n * greater than the second.\r\n * @return {number} Negative number, zero, or a positive number depending on\r\n * whether the first argument is less than, equal to, or greater than the\r\n * second.\r\n * @template VALUE\r\n */\r\ngoog.array.compare3 = function(arr1, arr2, opt_compareFn) {\r\n var compare = opt_compareFn || goog.array.defaultCompare;\r\n var l = Math.min(arr1.length, arr2.length);\r\n for (var i = 0; i < l; i++) {\r\n var result = compare(arr1[i], arr2[i]);\r\n if (result != 0) {\r\n return result;\r\n }\r\n }\r\n return goog.array.defaultCompare(arr1.length, arr2.length);\r\n};\r\n\r\n\r\n/**\r\n * Compares its two arguments for order, using the built in < and >\r\n * operators.\r\n * @param {VALUE} a The first object to be compared.\r\n * @param {VALUE} b The second object to be compared.\r\n * @return {number} A negative number, zero, or a positive number as the first\r\n * argument is less than, equal to, or greater than the second,\r\n * respectively.\r\n * @template VALUE\r\n */\r\ngoog.array.defaultCompare = function(a, b) {\r\n return a > b ? 1 : a < b ? -1 : 0;\r\n};\r\n\r\n\r\n/**\r\n * Compares its two arguments for inverse order, using the built in < and >\r\n * operators.\r\n * @param {VALUE} a The first object to be compared.\r\n * @param {VALUE} b The second object to be compared.\r\n * @return {number} A negative number, zero, or a positive number as the first\r\n * argument is greater than, equal to, or less than the second,\r\n * respectively.\r\n * @template VALUE\r\n */\r\ngoog.array.inverseDefaultCompare = function(a, b) {\r\n return -goog.array.defaultCompare(a, b);\r\n};\r\n\r\n\r\n/**\r\n * Compares its two arguments for equality, using the built in === operator.\r\n * @param {*} a The first object to compare.\r\n * @param {*} b The second object to compare.\r\n * @return {boolean} True if the two arguments are equal, false otherwise.\r\n */\r\ngoog.array.defaultCompareEquality = function(a, b) {\r\n return a === b;\r\n};\r\n\r\n\r\n/**\r\n * Inserts a value into a sorted array. The array is not modified if the\r\n * value is already present.\r\n * @param {IArrayLike<VALUE>} array The array to modify.\r\n * @param {VALUE} value The object to insert.\r\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is ordered. Should take 2 arguments to\r\n * compare, and return a negative number, zero, or a positive number\r\n * depending on whether the first argument is less than, equal to, or\r\n * greater than the second.\r\n * @return {boolean} True if an element was inserted.\r\n * @template VALUE\r\n */\r\ngoog.array.binaryInsert = function(array, value, opt_compareFn) {\r\n var index = goog.array.binarySearch(array, value, opt_compareFn);\r\n if (index < 0) {\r\n goog.array.insertAt(array, value, -(index + 1));\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes a value from a sorted array.\r\n * @param {!IArrayLike<VALUE>} array The array to modify.\r\n * @param {VALUE} value The object to remove.\r\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\r\n * function by which the array is ordered. Should take 2 arguments to\r\n * compare, and return a negative number, zero, or a positive number\r\n * depending on whether the first argument is less than, equal to, or\r\n * greater than the second.\r\n * @return {boolean} True if an element was removed.\r\n * @template VALUE\r\n */\r\ngoog.array.binaryRemove = function(array, value, opt_compareFn) {\r\n var index = goog.array.binarySearch(array, value, opt_compareFn);\r\n return (index >= 0) ? goog.array.removeAt(array, index) : false;\r\n};\r\n\r\n\r\n/**\r\n * Splits an array into disjoint buckets according to a splitting function.\r\n * @param {IArrayLike<T>} array The array.\r\n * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to\r\n * call for every element. This takes 3 arguments (the element, the index\r\n * and the array) and must return a valid object key (a string, number,\r\n * etc), or undefined, if that object should not be placed in a bucket.\r\n * @param {S=} opt_obj The object to be used as the value of 'this' within\r\n * sorter.\r\n * @return {!Object<!Array<T>>} An object, with keys being all of the unique\r\n * return values of sorter, and values being arrays containing the items for\r\n * which the splitter returned that key.\r\n * @template T,S\r\n */\r\ngoog.array.bucket = function(array, sorter, opt_obj) {\r\n var buckets = {};\r\n\r\n for (var i = 0; i < array.length; i++) {\r\n var value = array[i];\r\n var key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\r\n if (goog.isDef(key)) {\r\n // Push the value to the right bucket, creating it if necessary.\r\n var bucket = buckets[key] || (buckets[key] = []);\r\n bucket.push(value);\r\n }\r\n }\r\n\r\n return buckets;\r\n};\r\n\r\n\r\n/**\r\n * Creates a new object built from the provided array and the key-generation\r\n * function.\r\n * @param {IArrayLike<T>} arr Array or array like object over\r\n * which to iterate whose elements will be the values in the new object.\r\n * @param {?function(this:S, T, number, ?) : string} keyFunc The function to\r\n * call for every element. This function takes 3 arguments (the element, the\r\n * index and the array) and should return a string that will be used as the\r\n * key for the element in the new object. If the function returns the same\r\n * key for more than one element, the value for that key is\r\n * implementation-defined.\r\n * @param {S=} opt_obj The object to be used as the value of 'this'\r\n * within keyFunc.\r\n * @return {!Object<T>} The new object.\r\n * @template T,S\r\n */\r\ngoog.array.toObject = function(arr, keyFunc, opt_obj) {\r\n var ret = {};\r\n goog.array.forEach(arr, function(element, index) {\r\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\r\n element;\r\n });\r\n return ret;\r\n};\r\n\r\n\r\n/**\r\n * Creates a range of numbers in an arithmetic progression.\r\n *\r\n * Range takes 1, 2, or 3 arguments:\r\n * <pre>\r\n * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]\r\n * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]\r\n * range(-2, -5, -1) produces [-2, -3, -4]\r\n * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.\r\n * </pre>\r\n *\r\n * @param {number} startOrEnd The starting value of the range if an end argument\r\n * is provided. Otherwise, the start value is 0, and this is the end value.\r\n * @param {number=} opt_end The optional end value of the range.\r\n * @param {number=} opt_step The step size between range values. Defaults to 1\r\n * if opt_step is undefined or 0.\r\n * @return {!Array<number>} An array of numbers for the requested range. May be\r\n * an empty array if adding the step would not converge toward the end\r\n * value.\r\n */\r\ngoog.array.range = function(startOrEnd, opt_end, opt_step) {\r\n var array = [];\r\n var start = 0;\r\n var end = startOrEnd;\r\n var step = opt_step || 1;\r\n if (opt_end !== undefined) {\r\n start = startOrEnd;\r\n end = opt_end;\r\n }\r\n\r\n if (step * (end - start) < 0) {\r\n // Sign mismatch: start + step will never reach the end value.\r\n return [];\r\n }\r\n\r\n if (step > 0) {\r\n for (var i = start; i < end; i += step) {\r\n array.push(i);\r\n }\r\n } else {\r\n for (var i = start; i > end; i += step) {\r\n array.push(i);\r\n }\r\n }\r\n return array;\r\n};\r\n\r\n\r\n/**\r\n * Returns an array consisting of the given value repeated N times.\r\n *\r\n * @param {VALUE} value The value to repeat.\r\n * @param {number} n The repeat count.\r\n * @return {!Array<VALUE>} An array with the repeated value.\r\n * @template VALUE\r\n */\r\ngoog.array.repeat = function(value, n) {\r\n var array = [];\r\n for (var i = 0; i < n; i++) {\r\n array[i] = value;\r\n }\r\n return array;\r\n};\r\n\r\n\r\n/**\r\n * Returns an array consisting of every argument with all arrays\r\n * expanded in-place recursively.\r\n *\r\n * @param {...*} var_args The values to flatten.\r\n * @return {!Array<?>} An array containing the flattened values.\r\n */\r\ngoog.array.flatten = function(var_args) {\r\n var CHUNK_SIZE = 8192;\r\n\r\n var result = [];\r\n for (var i = 0; i < arguments.length; i++) {\r\n var element = arguments[i];\r\n if (goog.isArray(element)) {\r\n for (var c = 0; c < element.length; c += CHUNK_SIZE) {\r\n var chunk = goog.array.slice(element, c, c + CHUNK_SIZE);\r\n var recurseResult = goog.array.flatten.apply(null, chunk);\r\n for (var r = 0; r < recurseResult.length; r++) {\r\n result.push(recurseResult[r]);\r\n }\r\n }\r\n } else {\r\n result.push(element);\r\n }\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Rotates an array in-place. After calling this method, the element at\r\n * index i will be the element previously at index (i - n) %\r\n * array.length, for all values of i between 0 and array.length - 1,\r\n * inclusive.\r\n *\r\n * For example, suppose list comprises [t, a, n, k, s]. After invoking\r\n * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].\r\n *\r\n * @param {!Array<T>} array The array to rotate.\r\n * @param {number} n The amount to rotate.\r\n * @return {!Array<T>} The array.\r\n * @template T\r\n */\r\ngoog.array.rotate = function(array, n) {\r\n goog.asserts.assert(array.length != null);\r\n\r\n if (array.length) {\r\n n %= array.length;\r\n if (n > 0) {\r\n Array.prototype.unshift.apply(array, array.splice(-n, n));\r\n } else if (n < 0) {\r\n Array.prototype.push.apply(array, array.splice(0, -n));\r\n }\r\n }\r\n return array;\r\n};\r\n\r\n\r\n/**\r\n * Moves one item of an array to a new position keeping the order of the rest\r\n * of the items. Example use case: keeping a list of JavaScript objects\r\n * synchronized with the corresponding list of DOM elements after one of the\r\n * elements has been dragged to a new position.\r\n * @param {!IArrayLike<?>} arr The array to modify.\r\n * @param {number} fromIndex Index of the item to move between 0 and\r\n * {@code arr.length - 1}.\r\n * @param {number} toIndex Target index between 0 and {@code arr.length - 1}.\r\n */\r\ngoog.array.moveItem = function(arr, fromIndex, toIndex) {\r\n goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\r\n goog.asserts.assert(toIndex >= 0 && toIndex < arr.length);\r\n // Remove 1 item at fromIndex.\r\n var removedItems = Array.prototype.splice.call(arr, fromIndex, 1);\r\n // Insert the removed item at toIndex.\r\n Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);\r\n // We don't use goog.array.insertAt and goog.array.removeAt, because they're\r\n // significantly slower than splice.\r\n};\r\n\r\n\r\n/**\r\n * Creates a new array for which the element at position i is an array of the\r\n * ith element of the provided arrays. The returned array will only be as long\r\n * as the shortest array provided; additional values are ignored. For example,\r\n * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].\r\n *\r\n * This is similar to the zip() function in Python. See {@link\r\n * http://docs.python.org/library/functions.html#zip}\r\n *\r\n * @param {...!IArrayLike<?>} var_args Arrays to be combined.\r\n * @return {!Array<!Array<?>>} A new array of arrays created from\r\n * provided arrays.\r\n */\r\ngoog.array.zip = function(var_args) {\r\n if (!arguments.length) {\r\n return [];\r\n }\r\n var result = [];\r\n var minLen = arguments[0].length;\r\n for (var i = 1; i < arguments.length; i++) {\r\n if (arguments[i].length < minLen) {\r\n minLen = arguments[i].length;\r\n }\r\n }\r\n for (var i = 0; i < minLen; i++) {\r\n var value = [];\r\n for (var j = 0; j < arguments.length; j++) {\r\n value.push(arguments[j][i]);\r\n }\r\n result.push(value);\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Shuffles the values in the specified array using the Fisher-Yates in-place\r\n * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()\r\n * and so resets the state of that random number generator. Similarly, may reset\r\n * the state of any other specified random number generator.\r\n *\r\n * Runtime: O(n)\r\n *\r\n * @param {!Array<?>} arr The array to be shuffled.\r\n * @param {function():number=} opt_randFn Optional random function to use for\r\n * shuffling.\r\n * Takes no arguments, and returns a random number on the interval [0, 1).\r\n * Defaults to Math.random() using JavaScript's built-in Math library.\r\n */\r\ngoog.array.shuffle = function(arr, opt_randFn) {\r\n var randFn = opt_randFn || Math.random;\r\n\r\n for (var i = arr.length - 1; i > 0; i--) {\r\n // Choose a random array index in [0, i] (inclusive with i).\r\n var j = Math.floor(randFn() * (i + 1));\r\n\r\n var tmp = arr[i];\r\n arr[i] = arr[j];\r\n arr[j] = tmp;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns a new array of elements from arr, based on the indexes of elements\r\n * provided by index_arr. For example, the result of index copying\r\n * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].\r\n *\r\n * @param {!IArrayLike<T>} arr The array to get a indexed copy from.\r\n * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.\r\n * @return {!Array<T>} A new array of elements from arr in index_arr order.\r\n * @template T\r\n */\r\ngoog.array.copyByIndex = function(arr, index_arr) {\r\n var result = [];\r\n goog.array.forEach(index_arr, function(index) { result.push(arr[index]); });\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Maps each element of the input array into zero or more elements of the output\r\n * array.\r\n *\r\n * @param {!IArrayLike<VALUE>|string} arr Array or array like object\r\n * over which to iterate.\r\n * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function\r\n * to call for every element. This function takes 3 arguments (the element,\r\n * the index and the array) and should return an array. The result will be\r\n * used to extend a new array.\r\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\r\n * @return {!Array<RESULT>} a new array with the concatenation of all arrays\r\n * returned from f.\r\n * @template THIS, VALUE, RESULT\r\n */\r\ngoog.array.concatMap = function(arr, f, opt_obj) {\r\n return goog.array.concat.apply([], goog.array.map(arr, f, opt_obj));\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview String functions called from Closure packages that couldn't\r\n * depend on each other. Outside Closure, use goog.string function which\r\n * delegate to these.\r\n */\r\n\r\n\r\ngoog.provide('goog.string.internal');\r\n\r\n\r\n/**\r\n * Fast prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the start of `str`.\r\n * @return {boolean} True if `str` begins with `prefix`.\r\n * @see goog.string.startsWith\r\n */\r\ngoog.string.internal.startsWith = function(str, prefix) {\r\n return str.lastIndexOf(prefix, 0) == 0;\r\n};\r\n\r\n\r\n/**\r\n * Fast suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix`.\r\n * @see goog.string.endsWith\r\n */\r\ngoog.string.internal.endsWith = function(str, suffix) {\r\n var l = str.length - suffix.length;\r\n return l >= 0 && str.indexOf(suffix, l) == l;\r\n};\r\n\r\n\r\n/**\r\n * Case-insensitive prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` begins with `prefix` (ignoring\r\n * case).\r\n * @see goog.string.caseInsensitiveStartsWith\r\n */\r\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\r\n return goog.string.internal.caseInsensitiveCompare(\r\n prefix, str.substr(0, prefix.length)) == 0;\r\n};\r\n\r\n\r\n/**\r\n * Case-insensitive suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix` (ignoring\r\n * case).\r\n * @see goog.string.caseInsensitiveEndsWith\r\n */\r\ngoog.string.internal.caseInsensitiveEndsWith = function(str, suffix) {\r\n return (\r\n goog.string.internal.caseInsensitiveCompare(\r\n suffix, str.substr(str.length - suffix.length, suffix.length)) == 0);\r\n};\r\n\r\n\r\n/**\r\n * Case-insensitive equality checker.\r\n * @param {string} str1 First string to check.\r\n * @param {string} str2 Second string to check.\r\n * @return {boolean} True if `str1` and `str2` are the same string,\r\n * ignoring case.\r\n * @see goog.string.caseInsensitiveEquals\r\n */\r\ngoog.string.internal.caseInsensitiveEquals = function(str1, str2) {\r\n return str1.toLowerCase() == str2.toLowerCase();\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is empty or contains only whitespaces.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty or whitespace only.\r\n * @see goog.string.isEmptyOrWhitespace\r\n */\r\ngoog.string.internal.isEmptyOrWhitespace = function(str) {\r\n // testing length == 0 first is actually slower in all browsers (about the\r\n // same in Opera).\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return /^[\\s\\xa0]*$/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Trims white spaces to the left and right of a string.\r\n * @param {string} str The string to trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.internal.trim =\r\n (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) {\r\n return str.trim();\r\n } : function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s\r\n // character class (as required by section 7.2 of the ECMAScript spec),\r\n // we explicitly include it in the regexp to enforce consistent\r\n // cross-browser behavior.\r\n // NOTE: We don't use String#replace because it might have side effects\r\n // causing this function to not compile to 0 bytes.\r\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(str)[1];\r\n };\r\n\r\n\r\n/**\r\n * A string comparator that ignores case.\r\n * -1 = str1 less than str2\r\n * 0 = str1 equals str2\r\n * 1 = str1 greater than str2\r\n *\r\n * @param {string} str1 The string to compare.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} The comparator result, as described above.\r\n * @see goog.string.caseInsensitiveCompare\r\n */\r\ngoog.string.internal.caseInsensitiveCompare = function(str1, str2) {\r\n var test1 = String(str1).toLowerCase();\r\n var test2 = String(str2).toLowerCase();\r\n\r\n if (test1 < test2) {\r\n return -1;\r\n } else if (test1 == test2) {\r\n return 0;\r\n } else {\r\n return 1;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Converts \\n to <br>s or <br />s.\r\n * @param {string} str The string in which to convert newlines.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} A copy of `str` with converted newlines.\r\n * @see goog.string.newLineToBr\r\n */\r\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\r\n return str.replace(/(\\r\\n|\\r|\\n)/g, opt_xml ? '<br />' : '<br>');\r\n};\r\n\r\n\r\n/**\r\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\r\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\r\n * value within double or single quotes.\r\n * @param {string} str string to be escaped.\r\n * @param {boolean=} opt_isLikelyToContainHtmlChars\r\n * @return {string} An escaped copy of `str`.\r\n * @see goog.string.htmlEscape\r\n */\r\ngoog.string.internal.htmlEscape = function(\r\n str, opt_isLikelyToContainHtmlChars) {\r\n if (opt_isLikelyToContainHtmlChars) {\r\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;')\r\n .replace(goog.string.internal.LT_RE_, '&lt;')\r\n .replace(goog.string.internal.GT_RE_, '&gt;')\r\n .replace(goog.string.internal.QUOT_RE_, '&quot;')\r\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;')\r\n .replace(goog.string.internal.NULL_RE_, '&#0;');\r\n return str;\r\n\r\n } else {\r\n // quick test helps in the case when there are no chars to replace, in\r\n // worst case this makes barely a difference to the time taken\r\n if (!goog.string.internal.ALL_RE_.test(str)) return str;\r\n\r\n // str.indexOf is faster than regex.test in this case\r\n if (str.indexOf('&') != -1) {\r\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;');\r\n }\r\n if (str.indexOf('<') != -1) {\r\n str = str.replace(goog.string.internal.LT_RE_, '&lt;');\r\n }\r\n if (str.indexOf('>') != -1) {\r\n str = str.replace(goog.string.internal.GT_RE_, '&gt;');\r\n }\r\n if (str.indexOf('\"') != -1) {\r\n str = str.replace(goog.string.internal.QUOT_RE_, '&quot;');\r\n }\r\n if (str.indexOf('\\'') != -1) {\r\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;');\r\n }\r\n if (str.indexOf('\\x00') != -1) {\r\n str = str.replace(goog.string.internal.NULL_RE_, '&#0;');\r\n }\r\n return str;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Regular expression that matches an ampersand, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.AMP_RE_ = /&/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a less than sign, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.LT_RE_ = /</g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a greater than sign, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.GT_RE_ = />/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a double quote, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.QUOT_RE_ = /\"/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches a single quote, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.SINGLE_QUOTE_RE_ = /'/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches null character, for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.NULL_RE_ = /\\x00/g;\r\n\r\n\r\n/**\r\n * Regular expression that matches any character that needs to be escaped.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.internal.ALL_RE_ = /[\\x00&<>\"']/;\r\n\r\n\r\n/**\r\n * Do escaping of whitespace to preserve spatial formatting. We use character\r\n * entity #160 to make it safer for xml.\r\n * @param {string} str The string in which to escape whitespace.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} An escaped copy of `str`.\r\n * @see goog.string.whitespaceEscape\r\n */\r\ngoog.string.internal.whitespaceEscape = function(str, opt_xml) {\r\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\r\n return goog.string.internal.newLineToBr(\r\n str.replace(/ /g, ' &#160;'), opt_xml);\r\n};\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n * @see goog.string.contains\r\n */\r\ngoog.string.internal.contains = function(str, subString) {\r\n return str.indexOf(subString) != -1;\r\n};\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring, ignoring case.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n * @see goog.string.caseInsensitiveContains\r\n */\r\ngoog.string.internal.caseInsensitiveContains = function(str, subString) {\r\n return goog.string.internal.contains(\r\n str.toLowerCase(), subString.toLowerCase());\r\n};\r\n\r\n\r\n/**\r\n * Compares two version numbers.\r\n *\r\n * @param {string|number} version1 Version of first item.\r\n * @param {string|number} version2 Version of second item.\r\n *\r\n * @return {number} 1 if `version1` is higher.\r\n * 0 if arguments are equal.\r\n * -1 if `version2` is higher.\r\n * @see goog.string.compareVersions\r\n */\r\ngoog.string.internal.compareVersions = function(version1, version2) {\r\n var order = 0;\r\n // Trim leading and trailing whitespace and split the versions into\r\n // subversions.\r\n var v1Subs = goog.string.internal.trim(String(version1)).split('.');\r\n var v2Subs = goog.string.internal.trim(String(version2)).split('.');\r\n var subCount = Math.max(v1Subs.length, v2Subs.length);\r\n\r\n // Iterate over the subversions, as long as they appear to be equivalent.\r\n for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\r\n var v1Sub = v1Subs[subIdx] || '';\r\n var v2Sub = v2Subs[subIdx] || '';\r\n\r\n do {\r\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\r\n // Two different RegExp objects are use to make it clear the code\r\n // is side-effect free\r\n var v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\r\n var v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\r\n // Break if there are no more matches.\r\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\r\n break;\r\n }\r\n\r\n // Parse the numeric part of the subversion. A missing number is\r\n // equivalent to 0.\r\n var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\r\n var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\r\n\r\n // Compare the subversion components. The number has the highest\r\n // precedence. Next, if the numbers are equal, a subversion without any\r\n // qualifier is always higher than a subversion with any qualifier. Next,\r\n // the qualifiers are compared as strings.\r\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\r\n goog.string.internal.compareElements_(\r\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\r\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\r\n // Stop as soon as an inequality is discovered.\r\n\r\n v1Sub = v1Comp[3];\r\n v2Sub = v2Comp[3];\r\n } while (order == 0);\r\n }\r\n\r\n return order;\r\n};\r\n\r\n\r\n/**\r\n * Compares elements of a version number.\r\n *\r\n * @param {string|number|boolean} left An element from a version number.\r\n * @param {string|number|boolean} right An element from a version number.\r\n *\r\n * @return {number} 1 if `left` is higher.\r\n * 0 if arguments are equal.\r\n * -1 if `right` is higher.\r\n * @private\r\n */\r\ngoog.string.internal.compareElements_ = function(left, right) {\r\n if (left < right) {\r\n return -1;\r\n } else if (left > right) {\r\n return 1;\r\n }\r\n return 0;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities used by goog.labs.userAgent tools. These functions\r\n * should not be used outside of goog.labs.userAgent.*.\r\n *\r\n * @author nnaze@google.com (Nathan Naze)\r\n */\r\n\r\ngoog.provide('goog.labs.userAgent.util');\r\n\r\ngoog.require('goog.string.internal');\r\n\r\n\r\n/**\r\n * Gets the native userAgent string from navigator if it exists.\r\n * If navigator or navigator.userAgent string is missing, returns an empty\r\n * string.\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.labs.userAgent.util.getNativeUserAgentString_ = function() {\r\n var navigator = goog.labs.userAgent.util.getNavigator_();\r\n if (navigator) {\r\n var userAgent = navigator.userAgent;\r\n if (userAgent) {\r\n return userAgent;\r\n }\r\n }\r\n return '';\r\n};\r\n\r\n\r\n/**\r\n * Getter for the native navigator.\r\n * This is a separate function so it can be stubbed out in testing.\r\n * @return {Navigator}\r\n * @private\r\n */\r\ngoog.labs.userAgent.util.getNavigator_ = function() {\r\n return goog.global.navigator;\r\n};\r\n\r\n\r\n/**\r\n * A possible override for applications which wish to not check\r\n * navigator.userAgent but use a specified value for detection instead.\r\n * @private {string}\r\n */\r\ngoog.labs.userAgent.util.userAgent_ =\r\n goog.labs.userAgent.util.getNativeUserAgentString_();\r\n\r\n\r\n/**\r\n * Applications may override browser detection on the built in\r\n * navigator.userAgent object by setting this string. Set to null to use the\r\n * browser object instead.\r\n * @param {?string=} opt_userAgent The User-Agent override.\r\n */\r\ngoog.labs.userAgent.util.setUserAgent = function(opt_userAgent) {\r\n goog.labs.userAgent.util.userAgent_ =\r\n opt_userAgent || goog.labs.userAgent.util.getNativeUserAgentString_();\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The user agent string.\r\n */\r\ngoog.labs.userAgent.util.getUserAgent = function() {\r\n return goog.labs.userAgent.util.userAgent_;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} str\r\n * @return {boolean} Whether the user agent contains the given string.\r\n */\r\ngoog.labs.userAgent.util.matchUserAgent = function(str) {\r\n var userAgent = goog.labs.userAgent.util.getUserAgent();\r\n return goog.string.internal.contains(userAgent, str);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} str\r\n * @return {boolean} Whether the user agent contains the given string, ignoring\r\n * case.\r\n */\r\ngoog.labs.userAgent.util.matchUserAgentIgnoreCase = function(str) {\r\n var userAgent = goog.labs.userAgent.util.getUserAgent();\r\n return goog.string.internal.caseInsensitiveContains(userAgent, str);\r\n};\r\n\r\n\r\n/**\r\n * Parses the user agent into tuples for each section.\r\n * @param {string} userAgent\r\n * @return {!Array<!Array<string>>} Tuples of key, version, and the contents\r\n * of the parenthetical.\r\n */\r\ngoog.labs.userAgent.util.extractVersionTuples = function(userAgent) {\r\n // Matches each section of a user agent string.\r\n // Example UA:\r\n // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)\r\n // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\r\n // This has three version tuples: Mozilla, AppleWebKit, and Mobile.\r\n\r\n var versionRegExp = new RegExp(\r\n // Key. Note that a key may have a space.\r\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\r\n '(\\\\w[\\\\w ]+)' +\r\n\r\n '/' + // slash\r\n '([^\\\\s]+)' + // version (i.e. '5.0b')\r\n '\\\\s*' + // whitespace\r\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\r\n 'g');\r\n\r\n var data = [];\r\n var match;\r\n\r\n // Iterate and collect the version tuples. Each iteration will be the\r\n // next regex match.\r\n while (match = versionRegExp.exec(userAgent)) {\r\n data.push([\r\n match[1], // key\r\n match[2], // value\r\n // || undefined as this is not undefined in IE7 and IE8\r\n match[3] || undefined // info\r\n ]);\r\n }\r\n\r\n return data;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for manipulating objects/maps/hashes.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\ngoog.provide('goog.object');\r\n\r\n\r\n/**\r\n * Whether two values are not observably distinguishable. This\r\n * correctly detects that 0 is not the same as -0 and two NaNs are\r\n * practically equivalent.\r\n *\r\n * The implementation is as suggested by harmony:egal proposal.\r\n *\r\n * @param {*} v The first value to compare.\r\n * @param {*} v2 The second value to compare.\r\n * @return {boolean} Whether two values are not observably distinguishable.\r\n * @see http://wiki.ecmascript.org/doku.php?id=harmony:egal\r\n */\r\ngoog.object.is = function(v, v2) {\r\n if (v === v2) {\r\n // 0 === -0, but they are not identical.\r\n // We need the cast because the compiler requires that v2 is a\r\n // number (although 1/v2 works with non-number). We cast to ? to\r\n // stop the compiler from type-checking this statement.\r\n return v !== 0 || 1 / v === 1 / /** @type {?} */ (v2);\r\n }\r\n\r\n // NaN is non-reflexive: NaN !== NaN, although they are identical.\r\n return v !== v && v2 !== v2;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash.\r\n *\r\n * @param {Object<K,V>} obj The object over which to iterate.\r\n * @param {function(this:T,V,?,Object<K,V>):?} f The function to call\r\n * for every element. This function takes 3 arguments (the value, the\r\n * key and the object) and the return value is ignored.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @template T,K,V\r\n */\r\ngoog.object.forEach = function(obj, f, opt_obj) {\r\n for (var key in obj) {\r\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash. If that call returns\r\n * true, adds the element to a new object.\r\n *\r\n * @param {Object<K,V>} obj The object over which to iterate.\r\n * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call\r\n * for every element. This\r\n * function takes 3 arguments (the value, the key and the object)\r\n * and should return a boolean. If the return value is true the\r\n * element is added to the result object. If it is false the\r\n * element is not included.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {!Object<K,V>} a new object in which only elements that passed the\r\n * test are present.\r\n * @template T,K,V\r\n */\r\ngoog.object.filter = function(obj, f, opt_obj) {\r\n var res = {};\r\n for (var key in obj) {\r\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\r\n res[key] = obj[key];\r\n }\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * For every element in an object/map/hash calls a function and inserts the\r\n * result into a new object.\r\n *\r\n * @param {Object<K,V>} obj The object over which to iterate.\r\n * @param {function(this:T,V,?,Object<K,V>):R} f The function to call\r\n * for every element. This function\r\n * takes 3 arguments (the value, the key and the object)\r\n * and should return something. The result will be inserted\r\n * into a new object.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {!Object<K,R>} a new object with the results from f.\r\n * @template T,K,V,R\r\n */\r\ngoog.object.map = function(obj, f, opt_obj) {\r\n var res = {};\r\n for (var key in obj) {\r\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash. If any\r\n * call returns true, returns true (without checking the rest). If\r\n * all calls return false, returns false.\r\n *\r\n * @param {Object<K,V>} obj The object to check.\r\n * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to\r\n * call for every element. This function\r\n * takes 3 arguments (the value, the key and the object) and should\r\n * return a boolean.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {boolean} true if any element passes the test.\r\n * @template T,K,V\r\n */\r\ngoog.object.some = function(obj, f, opt_obj) {\r\n for (var key in obj) {\r\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each element in an object/map/hash. If\r\n * all calls return true, returns true. If any call returns false, returns\r\n * false at this point and does not continue to check the remaining elements.\r\n *\r\n * @param {Object<K,V>} obj The object to check.\r\n * @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to\r\n * call for every element. This function\r\n * takes 3 arguments (the value, the key and the object) and should\r\n * return a boolean.\r\n * @param {T=} opt_obj This is used as the 'this' object within f.\r\n * @return {boolean} false if any element fails the test.\r\n * @template T,K,V\r\n */\r\ngoog.object.every = function(obj, f, opt_obj) {\r\n for (var key in obj) {\r\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of key-value pairs in the object map.\r\n *\r\n * @param {Object} obj The object for which to get the number of key-value\r\n * pairs.\r\n * @return {number} The number of key-value pairs in the object map.\r\n */\r\ngoog.object.getCount = function(obj) {\r\n var rv = 0;\r\n for (var key in obj) {\r\n rv++;\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Returns one key from the object map, if any exists.\r\n * For map literals the returned key will be the first one in most of the\r\n * browsers (a know exception is Konqueror).\r\n *\r\n * @param {Object} obj The object to pick a key from.\r\n * @return {string|undefined} The key or undefined if the object is empty.\r\n */\r\ngoog.object.getAnyKey = function(obj) {\r\n for (var key in obj) {\r\n return key;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns one value from the object map, if any exists.\r\n * For map literals the returned value will be the first one in most of the\r\n * browsers (a know exception is Konqueror).\r\n *\r\n * @param {Object<K,V>} obj The object to pick a value from.\r\n * @return {V|undefined} The value or undefined if the object is empty.\r\n * @template K,V\r\n */\r\ngoog.object.getAnyValue = function(obj) {\r\n for (var key in obj) {\r\n return obj[key];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/hash/map contains the given object as a value.\r\n * An alias for goog.object.containsValue(obj, val).\r\n *\r\n * @param {Object<K,V>} obj The object in which to look for val.\r\n * @param {V} val The object for which to check.\r\n * @return {boolean} true if val is present.\r\n * @template K,V\r\n */\r\ngoog.object.contains = function(obj, val) {\r\n return goog.object.containsValue(obj, val);\r\n};\r\n\r\n\r\n/**\r\n * Returns the values of the object/map/hash.\r\n *\r\n * @param {Object<K,V>} obj The object from which to get the values.\r\n * @return {!Array<V>} The values in the object/map/hash.\r\n * @template K,V\r\n */\r\ngoog.object.getValues = function(obj) {\r\n var res = [];\r\n var i = 0;\r\n for (var key in obj) {\r\n res[i++] = obj[key];\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * Returns the keys of the object/map/hash.\r\n *\r\n * @param {Object} obj The object from which to get the keys.\r\n * @return {!Array<string>} Array of property keys.\r\n */\r\ngoog.object.getKeys = function(obj) {\r\n var res = [];\r\n var i = 0;\r\n for (var key in obj) {\r\n res[i++] = key;\r\n }\r\n return res;\r\n};\r\n\r\n\r\n/**\r\n * Get a value from an object multiple levels deep. This is useful for\r\n * pulling values from deeply nested objects, such as JSON responses.\r\n * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)\r\n *\r\n * @param {!Object} obj An object to get the value from. Can be array-like.\r\n * @param {...(string|number|!IArrayLike<number|string>)}\r\n * var_args A number of keys\r\n * (as strings, or numbers, for array-like objects). Can also be\r\n * specified as a single array of keys.\r\n * @return {*} The resulting value. If, at any point, the value for a key\r\n * in the current object is null or undefined, returns undefined.\r\n */\r\ngoog.object.getValueByKeys = function(obj, var_args) {\r\n var isArrayLike = goog.isArrayLike(var_args);\r\n var keys = isArrayLike ?\r\n /** @type {!IArrayLike<number|string>} */ (var_args) :\r\n arguments;\r\n\r\n // Start with the 2nd parameter for the variable parameters syntax.\r\n for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) {\r\n if (obj == null) return undefined;\r\n obj = obj[keys[i]];\r\n }\r\n\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/map/hash contains the given key.\r\n *\r\n * @param {Object} obj The object in which to look for key.\r\n * @param {?} key The key for which to check.\r\n * @return {boolean} true If the map contains the key.\r\n */\r\ngoog.object.containsKey = function(obj, key) {\r\n return obj !== null && key in obj;\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/map/hash contains the given value. This is O(n).\r\n *\r\n * @param {Object<K,V>} obj The object in which to look for val.\r\n * @param {V} val The value for which to check.\r\n * @return {boolean} true If the map contains the value.\r\n * @template K,V\r\n */\r\ngoog.object.containsValue = function(obj, val) {\r\n for (var key in obj) {\r\n if (obj[key] == val) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Searches an object for an element that satisfies the given condition and\r\n * returns its key.\r\n * @param {Object<K,V>} obj The object to search in.\r\n * @param {function(this:T,V,string,Object<K,V>):boolean} f The\r\n * function to call for every element. Takes 3 arguments (the value,\r\n * the key and the object) and should return a boolean.\r\n * @param {T=} opt_this An optional \"this\" context for the function.\r\n * @return {string|undefined} The key of an element for which the function\r\n * returns true or undefined if no such element is found.\r\n * @template T,K,V\r\n */\r\ngoog.object.findKey = function(obj, f, opt_this) {\r\n for (var key in obj) {\r\n if (f.call(/** @type {?} */ (opt_this), obj[key], key, obj)) {\r\n return key;\r\n }\r\n }\r\n return undefined;\r\n};\r\n\r\n\r\n/**\r\n * Searches an object for an element that satisfies the given condition and\r\n * returns its value.\r\n * @param {Object<K,V>} obj The object to search in.\r\n * @param {function(this:T,V,string,Object<K,V>):boolean} f The function\r\n * to call for every element. Takes 3 arguments (the value, the key\r\n * and the object) and should return a boolean.\r\n * @param {T=} opt_this An optional \"this\" context for the function.\r\n * @return {V} The value of an element for which the function returns true or\r\n * undefined if no such element is found.\r\n * @template T,K,V\r\n */\r\ngoog.object.findValue = function(obj, f, opt_this) {\r\n var key = goog.object.findKey(obj, f, opt_this);\r\n return key && obj[key];\r\n};\r\n\r\n\r\n/**\r\n * Whether the object/map/hash is empty.\r\n *\r\n * @param {Object} obj The object to test.\r\n * @return {boolean} true if obj is empty.\r\n */\r\ngoog.object.isEmpty = function(obj) {\r\n for (var key in obj) {\r\n return false;\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Removes all key value pairs from the object/map/hash.\r\n *\r\n * @param {Object} obj The object to clear.\r\n */\r\ngoog.object.clear = function(obj) {\r\n for (var i in obj) {\r\n delete obj[i];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes a key-value pair based on the key.\r\n *\r\n * @param {Object} obj The object from which to remove the key.\r\n * @param {?} key The key to remove.\r\n * @return {boolean} Whether an element was removed.\r\n */\r\ngoog.object.remove = function(obj, key) {\r\n var rv;\r\n if (rv = key in /** @type {!Object} */ (obj)) {\r\n delete obj[key];\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the object. Throws an exception if the key is\r\n * already in use. Use set if you want to change an existing pair.\r\n *\r\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {V} val The value to add.\r\n * @template K,V\r\n */\r\ngoog.object.add = function(obj, key, val) {\r\n if (obj !== null && key in obj) {\r\n throw new Error('The object already contains the key \"' + key + '\"');\r\n }\r\n goog.object.set(obj, key, val);\r\n};\r\n\r\n\r\n/**\r\n * Returns the value for the given key.\r\n *\r\n * @param {Object<K,V>} obj The object from which to get the value.\r\n * @param {string} key The key for which to get the value.\r\n * @param {R=} opt_val The value to return if no item is found for the given\r\n * key (default is undefined).\r\n * @return {V|R|undefined} The value for the given key.\r\n * @template K,V,R\r\n */\r\ngoog.object.get = function(obj, key, opt_val) {\r\n if (obj !== null && key in obj) {\r\n return obj[key];\r\n }\r\n return opt_val;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the object/map/hash.\r\n *\r\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {V} value The value to add.\r\n * @template K,V\r\n */\r\ngoog.object.set = function(obj, key, value) {\r\n obj[key] = value;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\r\n *\r\n * @param {Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {V} value The value to add if the key wasn't present.\r\n * @return {V} The value of the entry at the end of the function.\r\n * @template K,V\r\n */\r\ngoog.object.setIfUndefined = function(obj, key, value) {\r\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\r\n};\r\n\r\n\r\n/**\r\n * Sets a key and value to an object if the key is not set. The value will be\r\n * the return value of the given function. If the key already exists, the\r\n * object will not be changed and the function will not be called (the function\r\n * will be lazily evaluated -- only called if necessary).\r\n *\r\n * This function is particularly useful when used with an `Object` which is\r\n * acting as a cache.\r\n *\r\n * @param {!Object<K,V>} obj The object to which to add the key-value pair.\r\n * @param {string} key The key to add.\r\n * @param {function():V} f The value to add if the key wasn't present.\r\n * @return {V} The value of the entry at the end of the function.\r\n * @template K,V\r\n */\r\ngoog.object.setWithReturnValueIfNotSet = function(obj, key, f) {\r\n if (key in obj) {\r\n return obj[key];\r\n }\r\n\r\n var val = f();\r\n obj[key] = val;\r\n return val;\r\n};\r\n\r\n\r\n/**\r\n * Compares two objects for equality using === on the values.\r\n *\r\n * @param {!Object<K,V>} a\r\n * @param {!Object<K,V>} b\r\n * @return {boolean}\r\n * @template K,V\r\n */\r\ngoog.object.equals = function(a, b) {\r\n for (var k in a) {\r\n if (!(k in b) || a[k] !== b[k]) {\r\n return false;\r\n }\r\n }\r\n for (var k in b) {\r\n if (!(k in a)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Returns a shallow clone of the object.\r\n *\r\n * @param {Object<K,V>} obj Object to clone.\r\n * @return {!Object<K,V>} Clone of the input object.\r\n * @template K,V\r\n */\r\ngoog.object.clone = function(obj) {\r\n // We cannot use the prototype trick because a lot of methods depend on where\r\n // the actual key is set.\r\n\r\n var res = {};\r\n for (var key in obj) {\r\n res[key] = obj[key];\r\n }\r\n return res;\r\n // We could also use goog.mixin but I wanted this to be independent from that.\r\n};\r\n\r\n\r\n/**\r\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\r\n * arrays will be cloned recursively.\r\n *\r\n * WARNINGS:\r\n * <code>goog.object.unsafeClone</code> does not detect reference loops. Objects\r\n * that refer to themselves will cause infinite recursion.\r\n *\r\n * <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and\r\n * copies UIDs created by <code>getUid</code> into cloned results.\r\n *\r\n * @param {T} obj The value to clone.\r\n * @return {T} A clone of the input value.\r\n * @template T\r\n */\r\ngoog.object.unsafeClone = function(obj) {\r\n var type = goog.typeOf(obj);\r\n if (type == 'object' || type == 'array') {\r\n if (goog.isFunction(obj.clone)) {\r\n return obj.clone();\r\n }\r\n var clone = type == 'array' ? [] : {};\r\n for (var key in obj) {\r\n clone[key] = goog.object.unsafeClone(obj[key]);\r\n }\r\n return clone;\r\n }\r\n\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * Returns a new object in which all the keys and values are interchanged\r\n * (keys become values and values become keys). If multiple keys map to the\r\n * same value, the chosen transposed value is implementation-dependent.\r\n *\r\n * @param {Object} obj The object to transpose.\r\n * @return {!Object} The transposed object.\r\n */\r\ngoog.object.transpose = function(obj) {\r\n var transposed = {};\r\n for (var key in obj) {\r\n transposed[obj[key]] = key;\r\n }\r\n return transposed;\r\n};\r\n\r\n\r\n/**\r\n * The names of the fields that are defined on Object.prototype.\r\n * @type {Array<string>}\r\n * @private\r\n */\r\ngoog.object.PROTOTYPE_FIELDS_ = [\r\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\r\n 'toLocaleString', 'toString', 'valueOf'\r\n];\r\n\r\n\r\n/**\r\n * Extends an object with another object.\r\n * This operates 'in-place'; it does not create a new Object.\r\n *\r\n * Example:\r\n * var o = {};\r\n * goog.object.extend(o, {a: 0, b: 1});\r\n * o; // {a: 0, b: 1}\r\n * goog.object.extend(o, {b: 2, c: 3});\r\n * o; // {a: 0, b: 2, c: 3}\r\n *\r\n * @param {Object} target The object to modify. Existing properties will be\r\n * overwritten if they are also present in one of the objects in\r\n * `var_args`.\r\n * @param {...(Object|null|undefined)} var_args The objects from which values\r\n * will be copied.\r\n */\r\ngoog.object.extend = function(target, var_args) {\r\n var key, source;\r\n for (var i = 1; i < arguments.length; i++) {\r\n source = arguments[i];\r\n for (key in source) {\r\n target[key] = source[key];\r\n }\r\n\r\n // For IE the for-in-loop does not contain any properties that are not\r\n // enumerable on the prototype object (for example isPrototypeOf from\r\n // Object.prototype) and it will also not include 'replace' on objects that\r\n // extend String and change 'replace' (not that it is common for anyone to\r\n // extend anything except Object).\r\n\r\n for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) {\r\n key = goog.object.PROTOTYPE_FIELDS_[j];\r\n if (Object.prototype.hasOwnProperty.call(source, key)) {\r\n target[key] = source[key];\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Creates a new object built from the key-value pairs provided as arguments.\r\n * @param {...*} var_args If only one argument is provided and it is an array\r\n * then this is used as the arguments, otherwise even arguments are used as\r\n * the property names and odd arguments are used as the property values.\r\n * @return {!Object} The new object.\r\n * @throws {Error} If there are uneven number of arguments or there is only one\r\n * non array argument.\r\n */\r\ngoog.object.create = function(var_args) {\r\n var argLength = arguments.length;\r\n if (argLength == 1 && goog.isArray(arguments[0])) {\r\n return goog.object.create.apply(null, arguments[0]);\r\n }\r\n\r\n if (argLength % 2) {\r\n throw new Error('Uneven number of arguments');\r\n }\r\n\r\n var rv = {};\r\n for (var i = 0; i < argLength; i += 2) {\r\n rv[arguments[i]] = arguments[i + 1];\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Creates a new object where the property names come from the arguments but\r\n * the value is always set to true\r\n * @param {...*} var_args If only one argument is provided and it is an array\r\n * then this is used as the arguments, otherwise the arguments are used\r\n * as the property names.\r\n * @return {!Object} The new object.\r\n */\r\ngoog.object.createSet = function(var_args) {\r\n var argLength = arguments.length;\r\n if (argLength == 1 && goog.isArray(arguments[0])) {\r\n return goog.object.createSet.apply(null, arguments[0]);\r\n }\r\n\r\n var rv = {};\r\n for (var i = 0; i < argLength; i++) {\r\n rv[arguments[i]] = true;\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Creates an immutable view of the underlying object, if the browser\r\n * supports immutable objects.\r\n *\r\n * In default mode, writes to this view will fail silently. In strict mode,\r\n * they will throw an error.\r\n *\r\n * @param {!Object<K,V>} obj An object.\r\n * @return {!Object<K,V>} An immutable view of that object, or the\r\n * original object if this browser does not support immutables.\r\n * @template K,V\r\n */\r\ngoog.object.createImmutableView = function(obj) {\r\n var result = obj;\r\n if (Object.isFrozen && !Object.isFrozen(obj)) {\r\n result = Object.create(obj);\r\n Object.freeze(result);\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * @param {!Object} obj An object.\r\n * @return {boolean} Whether this is an immutable view of the object.\r\n */\r\ngoog.object.isImmutableView = function(obj) {\r\n return !!Object.isFrozen && Object.isFrozen(obj);\r\n};\r\n\r\n\r\n/**\r\n * Get all properties names on a given Object regardless of enumerability.\r\n *\r\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\r\n * `Object.getPrototypeOf` then this is equivalent to using\r\n * `goog.object.getKeys`\r\n *\r\n * @param {?Object} obj The object to get the properties of.\r\n * @param {boolean=} opt_includeObjectPrototype Whether properties defined on\r\n * `Object.prototype` should be included in the result.\r\n * @param {boolean=} opt_includeFunctionPrototype Whether properties defined on\r\n * `Function.prototype` should be included in the result.\r\n * @return {!Array<string>}\r\n * @public\r\n */\r\ngoog.object.getAllPropertyNames = function(\r\n obj, opt_includeObjectPrototype, opt_includeFunctionPrototype) {\r\n if (!obj) {\r\n return [];\r\n }\r\n\r\n // Naively use a for..in loop to get the property names if the browser doesn't\r\n // support any other APIs for getting it.\r\n if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\r\n return goog.object.getKeys(obj);\r\n }\r\n\r\n var visitedSet = {};\r\n\r\n // Traverse the prototype chain and add all properties to the visited set.\r\n var proto = obj;\r\n while (proto &&\r\n (proto !== Object.prototype || !!opt_includeObjectPrototype) &&\r\n (proto !== Function.prototype || !!opt_includeFunctionPrototype)) {\r\n var names = Object.getOwnPropertyNames(proto);\r\n for (var i = 0; i < names.length; i++) {\r\n visitedSet[names[i]] = true;\r\n }\r\n proto = Object.getPrototypeOf(proto);\r\n }\r\n\r\n return goog.object.getKeys(visitedSet);\r\n};\r\n","// Copyright 2009 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Useful compiler idioms.\r\n *\r\n * @author johnlenz@google.com (John Lenz)\r\n */\r\n\r\ngoog.provide('goog.reflect');\r\n\r\n\r\n/**\r\n * Syntax for object literal casts.\r\n * @see http://go/jscompiler-renaming\r\n * @see https://goo.gl/CRs09P\r\n *\r\n * Use this if you have an object literal whose keys need to have the same names\r\n * as the properties of some class even after they are renamed by the compiler.\r\n *\r\n * @param {!Function} type Type to cast to.\r\n * @param {Object} object Object literal to cast.\r\n * @return {Object} The object literal.\r\n */\r\ngoog.reflect.object = function(type, object) {\r\n return object;\r\n};\r\n\r\n/**\r\n * Syntax for renaming property strings.\r\n * @see http://go/jscompiler-renaming\r\n * @see https://goo.gl/CRs09P\r\n *\r\n * Use this if you have an need to access a property as a string, but want\r\n * to also have the property renamed by the compiler. In contrast to\r\n * goog.reflect.object, this method takes an instance of an object.\r\n *\r\n * Properties must be simple names (not qualified names).\r\n *\r\n * @param {string} prop Name of the property\r\n * @param {!Object} object Instance of the object whose type will be used\r\n * for renaming\r\n * @return {string} The renamed property.\r\n */\r\ngoog.reflect.objectProperty = function(prop, object) {\r\n return prop;\r\n};\r\n\r\n/**\r\n * To assert to the compiler that an operation is needed when it would\r\n * otherwise be stripped. For example:\r\n * <code>\r\n * // Force a layout\r\n * goog.reflect.sinkValue(dialog.offsetHeight);\r\n * </code>\r\n * @param {T} x\r\n * @return {T}\r\n * @template T\r\n */\r\ngoog.reflect.sinkValue = function(x) {\r\n goog.reflect.sinkValue[' '](x);\r\n return x;\r\n};\r\n\r\n\r\n/**\r\n * The compiler should optimize this function away iff no one ever uses\r\n * goog.reflect.sinkValue.\r\n */\r\ngoog.reflect.sinkValue[' '] = goog.nullFunction;\r\n\r\n\r\n/**\r\n * Check if a property can be accessed without throwing an exception.\r\n * @param {Object} obj The owner of the property.\r\n * @param {string} prop The property name.\r\n * @return {boolean} Whether the property is accessible. Will also return true\r\n * if obj is null.\r\n */\r\ngoog.reflect.canAccessProperty = function(obj, prop) {\r\n\r\n try {\r\n goog.reflect.sinkValue(obj[prop]);\r\n return true;\r\n } catch (e) {\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Retrieves a value from a cache given a key. The compiler provides special\r\n * consideration for this call such that it is generally considered side-effect\r\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\r\n * then the entire call is considered to have side-effects.\r\n *\r\n * Conventionally storing the value on the cache would be considered a\r\n * side-effect and preclude unused calls from being pruned, ie. even if\r\n * the value was never used, it would still always be stored in the cache.\r\n *\r\n * Providing a side-effect free `valueFn` and `opt_keyFn`\r\n * allows unused calls to `goog.reflect.cache` to be pruned.\r\n *\r\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\r\n * @param {?} key The key to lookup in the cache. If it is not string or number\r\n * then a `opt_keyFn` should be provided. The key is also used as the\r\n * parameter to the `valueFn`.\r\n * @param {function(?):V} valueFn The value provider to use to calculate the\r\n * value to store in the cache. This function should be side-effect free\r\n * to take advantage of the optimization.\r\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\r\n * map key. This should be used if the given key is not a string or number.\r\n * If not provided then the given key is used. This function should be\r\n * side-effect free to take advantage of the optimization.\r\n * @return {V} The cached or calculated value.\r\n * @template K\r\n * @template V\r\n */\r\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\r\n var storedKey = opt_keyFn ? opt_keyFn(key) : key;\r\n\r\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\r\n return cacheObj[storedKey];\r\n }\r\n\r\n return (cacheObj[storedKey] = valueFn(key));\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Rendering engine detection.\r\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\r\n * For information on the browser brand (such as Safari versus Chrome), see\r\n * goog.userAgent.product.\r\n * @author arv@google.com (Erik Arvidsson)\r\n * @see ../demos/useragent.html\r\n */\r\n\r\ngoog.provide('goog.userAgent');\r\n\r\ngoog.require('goog.labs.userAgent.browser');\r\ngoog.require('goog.labs.userAgent.engine');\r\ngoog.require('goog.labs.userAgent.platform');\r\ngoog.require('goog.labs.userAgent.util');\r\ngoog.require('goog.reflect');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is IE.\r\n */\r\ngoog.userAgent.ASSUME_IE = goog.define('goog.userAgent.ASSUME_IE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is EDGE.\r\n */\r\ngoog.userAgent.ASSUME_EDGE = goog.define('goog.userAgent.ASSUME_EDGE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is GECKO.\r\n */\r\ngoog.userAgent.ASSUME_GECKO = goog.define('goog.userAgent.ASSUME_GECKO', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.\r\n */\r\ngoog.userAgent.ASSUME_WEBKIT =\r\n goog.define('goog.userAgent.ASSUME_WEBKIT', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is a\r\n * mobile device running WebKit e.g. iPhone or Android.\r\n */\r\ngoog.userAgent.ASSUME_MOBILE_WEBKIT =\r\n goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether we know at compile-time that the browser is OPERA.\r\n */\r\ngoog.userAgent.ASSUME_OPERA = goog.define('goog.userAgent.ASSUME_OPERA', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the\r\n * `goog.userAgent.isVersionOrHigher`\r\n * function will return true for any version.\r\n */\r\ngoog.userAgent.ASSUME_ANY_VERSION =\r\n goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);\r\n\r\n\r\n/**\r\n * Whether we know the browser engine at compile-time.\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||\r\n goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||\r\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||\r\n goog.userAgent.ASSUME_OPERA;\r\n\r\n\r\n/**\r\n * Returns the userAgent string for the current browser.\r\n *\r\n * @return {string} The userAgent string.\r\n */\r\ngoog.userAgent.getUserAgentString = function() {\r\n return goog.labs.userAgent.util.getUserAgent();\r\n};\r\n\r\n\r\n/**\r\n * @return {?Navigator} The native navigator object.\r\n */\r\ngoog.userAgent.getNavigatorTyped = function() {\r\n // Need a local navigator reference instead of using the global one,\r\n // to avoid the rare case where they reference different objects.\r\n // (in a WorkerPool, for example).\r\n return goog.global['navigator'] || null;\r\n};\r\n\r\n\r\n/**\r\n * TODO(nnaze): Change type to \"Navigator\" and update compilation targets.\r\n * @return {?Object} The native navigator object.\r\n */\r\ngoog.userAgent.getNavigator = function() {\r\n return goog.userAgent.getNavigatorTyped();\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is Opera.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_OPERA :\r\n goog.labs.userAgent.browser.isOpera();\r\n\r\n\r\n/**\r\n * Whether the user agent is Internet Explorer.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_IE :\r\n goog.labs.userAgent.browser.isIE();\r\n\r\n\r\n/**\r\n * Whether the user agent is Microsoft Edge.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_EDGE :\r\n goog.labs.userAgent.engine.isEdge();\r\n\r\n\r\n/**\r\n * Whether the user agent is MS Internet Explorer or MS Edge.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;\r\n\r\n\r\n/**\r\n * Whether the user agent is Gecko. Gecko is the rendering engine used by\r\n * Mozilla, Firefox, and others.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_GECKO :\r\n goog.labs.userAgent.engine.isGecko();\r\n\r\n\r\n/**\r\n * Whether the user agent is WebKit. WebKit is the rendering engine that\r\n * Safari, Android and others use.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?\r\n goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :\r\n goog.labs.userAgent.engine.isWebKit();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a mobile device.\r\n *\r\n * This is a separate function so that the logic can be tested.\r\n *\r\n * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().\r\n *\r\n * @return {boolean} Whether the user agent is running on a mobile device.\r\n * @private\r\n */\r\ngoog.userAgent.isMobile_ = function() {\r\n return goog.userAgent.WEBKIT &&\r\n goog.labs.userAgent.util.matchUserAgent('Mobile');\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a mobile device.\r\n *\r\n * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent\r\n * is promoted as the gecko/webkit logic is likely inaccurate.\r\n *\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.MOBILE =\r\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();\r\n\r\n\r\n/**\r\n * Used while transitioning code to use WEBKIT instead.\r\n * @type {boolean}\r\n * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.\r\n * TODO(nicksantos): Delete this from goog.userAgent.\r\n */\r\ngoog.userAgent.SAFARI = goog.userAgent.WEBKIT;\r\n\r\n\r\n/**\r\n * @return {string} the platform (operating system) the user agent is running\r\n * on. Default to empty string because navigator.platform may not be defined\r\n * (on Rhino, for example).\r\n * @private\r\n */\r\ngoog.userAgent.determinePlatform_ = function() {\r\n var navigator = goog.userAgent.getNavigatorTyped();\r\n return navigator && navigator.platform || '';\r\n};\r\n\r\n\r\n/**\r\n * The platform (operating system) the user agent is running on. Default to\r\n * empty string because navigator.platform may not be defined (on Rhino, for\r\n * example).\r\n * @type {string}\r\n */\r\ngoog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a Macintosh operating\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_MAC = goog.define('goog.userAgent.ASSUME_MAC', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a Windows operating\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_WINDOWS =\r\n goog.define('goog.userAgent.ASSUME_WINDOWS', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a Linux operating\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_LINUX = goog.define('goog.userAgent.ASSUME_LINUX', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on a X11 windowing\r\n * system.\r\n */\r\ngoog.userAgent.ASSUME_X11 = goog.define('goog.userAgent.ASSUME_X11', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on Android.\r\n */\r\ngoog.userAgent.ASSUME_ANDROID =\r\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on an iPhone.\r\n */\r\ngoog.userAgent.ASSUME_IPHONE =\r\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on an iPad.\r\n */\r\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on an iPod.\r\n */\r\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on KaiOS.\r\n */\r\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\r\n\r\n/**\r\n * @define {boolean} Whether the user agent is running on Go2Phone.\r\n */\r\ngoog.userAgent.ASSUME_GO2PHONE =\r\n goog.define('goog.userAgent.ASSUME_GO2PHONE', false);\r\n\r\n\r\n/**\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\r\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\r\n goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||\r\n goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\r\n goog.userAgent.ASSUME_IPOD;\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a Macintosh operating system.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_MAC :\r\n goog.labs.userAgent.platform.isMacintosh();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a Windows operating system.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_WINDOWS :\r\n goog.labs.userAgent.platform.isWindows();\r\n\r\n\r\n/**\r\n * Whether the user agent is Linux per the legacy behavior of\r\n * goog.userAgent.LINUX, which considered ChromeOS to also be\r\n * Linux.\r\n * @return {boolean}\r\n * @private\r\n */\r\ngoog.userAgent.isLegacyLinux_ = function() {\r\n return goog.labs.userAgent.platform.isLinux() ||\r\n goog.labs.userAgent.platform.isChromeOS();\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a Linux operating system.\r\n *\r\n * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,\r\n * while goog.labs.userAgent.platform considers ChromeOS and\r\n * Linux to be different OSes.\r\n *\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_LINUX :\r\n goog.userAgent.isLegacyLinux_();\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user agent is an X11 windowing system.\r\n * @private\r\n */\r\ngoog.userAgent.isX11_ = function() {\r\n var navigator = goog.userAgent.getNavigatorTyped();\r\n return !!navigator &&\r\n goog.string.contains(navigator['appVersion'] || '', 'X11');\r\n};\r\n\r\n\r\n/**\r\n * Whether the user agent is running on a X11 windowing system.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_X11 :\r\n goog.userAgent.isX11_();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on Android.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_ANDROID :\r\n goog.labs.userAgent.platform.isAndroid();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on an iPhone.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_IPHONE :\r\n goog.labs.userAgent.platform.isIphone();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on an iPad.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_IPAD :\r\n goog.labs.userAgent.platform.isIpad();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on an iPod.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_IPOD :\r\n goog.labs.userAgent.platform.isIpod();\r\n\r\n\r\n/**\r\n * Whether the user agent is running on iOS.\r\n * @type {boolean}\r\n */\r\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\r\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\r\n goog.userAgent.ASSUME_IPOD) :\r\n goog.labs.userAgent.platform.isIos();\r\n\r\n/**\r\n * Whether the user agent is running on KaiOS.\r\n */\r\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_KAIOS :\r\n goog.labs.userAgent.platform.isKaiOS();\r\n\r\n/**\r\n * Whether the user agent is running on Go2Phone.\r\n */\r\ngoog.userAgent.GO2PHONE = goog.userAgent.PLATFORM_KNOWN_ ?\r\n goog.userAgent.ASSUME_GO2PHONE :\r\n goog.labs.userAgent.platform.isGo2Phone();\r\n\r\n\r\n/**\r\n * @return {string} The string that describes the version number of the user\r\n * agent.\r\n * @private\r\n */\r\ngoog.userAgent.determineVersion_ = function() {\r\n // All browsers have different ways to detect the version and they all have\r\n // different naming schemes.\r\n // version is a string rather than a number because it may contain 'b', 'a',\r\n // and so on.\r\n var version = '';\r\n var arr = goog.userAgent.getVersionRegexResult_();\r\n if (arr) {\r\n version = arr ? arr[1] : '';\r\n }\r\n\r\n if (goog.userAgent.IE) {\r\n // IE9 can be in document mode 9 but be reporting an inconsistent user agent\r\n // version. If it is identifying as a version lower than 9 we take the\r\n // documentMode as the version instead. IE8 has similar behavior.\r\n // It is recommended to set the X-UA-Compatible header to ensure that IE9\r\n // uses documentMode 9.\r\n var docMode = goog.userAgent.getDocumentMode_();\r\n if (docMode != null && docMode > parseFloat(version)) {\r\n return String(docMode);\r\n }\r\n }\r\n\r\n return version;\r\n};\r\n\r\n\r\n/**\r\n * @return {?IArrayLike<string>|undefined} The version regex matches from\r\n * parsing the user\r\n * agent string. These regex statements must be executed inline so they can\r\n * be compiled out by the closure compiler with the rest of the useragent\r\n * detection logic when ASSUME_* is specified.\r\n * @private\r\n */\r\ngoog.userAgent.getVersionRegexResult_ = function() {\r\n var userAgent = goog.userAgent.getUserAgentString();\r\n if (goog.userAgent.GECKO) {\r\n return /rv\\:([^\\);]+)(\\)|;)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.EDGE) {\r\n return /Edge\\/([\\d\\.]+)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.IE) {\r\n return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.WEBKIT) {\r\n // WebKit/125.4\r\n return /WebKit\\/(\\S+)/.exec(userAgent);\r\n }\r\n if (goog.userAgent.OPERA) {\r\n // If none of the above browsers were detected but the browser is Opera, the\r\n // only string that is of interest is 'Version/<number>'.\r\n return /(?:Version)[ \\/]?(\\S+)/.exec(userAgent);\r\n }\r\n return undefined;\r\n};\r\n\r\n\r\n/**\r\n * @return {number|undefined} Returns the document mode (for testing).\r\n * @private\r\n */\r\ngoog.userAgent.getDocumentMode_ = function() {\r\n // NOTE(user): goog.userAgent may be used in context where there is no DOM.\r\n var doc = goog.global['document'];\r\n return doc ? doc['documentMode'] : undefined;\r\n};\r\n\r\n\r\n/**\r\n * The version of the user agent. This is a string because it might contain\r\n * 'b' (as in beta) as well as multiple dots.\r\n * @type {string}\r\n */\r\ngoog.userAgent.VERSION = goog.userAgent.determineVersion_();\r\n\r\n\r\n/**\r\n * Compares two version numbers.\r\n *\r\n * @param {string} v1 Version of first item.\r\n * @param {string} v2 Version of second item.\r\n *\r\n * @return {number} 1 if first argument is higher\r\n * 0 if arguments are equal\r\n * -1 if second argument is higher.\r\n * @deprecated Use goog.string.compareVersions.\r\n */\r\ngoog.userAgent.compare = function(v1, v2) {\r\n return goog.string.compareVersions(v1, v2);\r\n};\r\n\r\n\r\n/**\r\n * Cache for {@link goog.userAgent.isVersionOrHigher}.\r\n * Calls to compareVersions are surprisingly expensive and, as a browser's\r\n * version number is unlikely to change during a session, we cache the results.\r\n * @const\r\n * @private\r\n */\r\ngoog.userAgent.isVersionOrHigherCache_ = {};\r\n\r\n\r\n/**\r\n * Whether the user agent version is higher or the same as the given version.\r\n * NOTE: When checking the version numbers for Firefox and Safari, be sure to\r\n * use the engine's version, not the browser's version number. For example,\r\n * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.\r\n * Opera and Internet Explorer versions match the product release number.<br>\r\n * @see <a href=\"http://en.wikipedia.org/wiki/Safari_version_history\">\r\n * Webkit</a>\r\n * @see <a href=\"http://en.wikipedia.org/wiki/Gecko_engine\">Gecko</a>\r\n *\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the user agent version is higher or the same as\r\n * the given version.\r\n */\r\ngoog.userAgent.isVersionOrHigher = function(version) {\r\n return goog.userAgent.ASSUME_ANY_VERSION ||\r\n goog.reflect.cache(\r\n goog.userAgent.isVersionOrHigherCache_, version, function() {\r\n return goog.string.compareVersions(\r\n goog.userAgent.VERSION, version) >= 0;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Deprecated alias to `goog.userAgent.isVersionOrHigher`.\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the user agent version is higher or the same as\r\n * the given version.\r\n * @deprecated Use goog.userAgent.isVersionOrHigher().\r\n */\r\ngoog.userAgent.isVersion = goog.userAgent.isVersionOrHigher;\r\n\r\n\r\n/**\r\n * Whether the IE effective document mode is higher or the same as the given\r\n * document mode version.\r\n * NOTE: Only for IE, return false for another browser.\r\n *\r\n * @param {number} documentMode The document mode version to check.\r\n * @return {boolean} Whether the IE effective document mode is higher or the\r\n * same as the given version.\r\n */\r\ngoog.userAgent.isDocumentModeOrHigher = function(documentMode) {\r\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\r\n};\r\n\r\n\r\n/**\r\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\r\n * @param {number} version The version to check.\r\n * @return {boolean} Whether the IE effective document mode is higher or the\r\n * same as the given version.\r\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\r\n */\r\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\r\n\r\n\r\n/**\r\n * For IE version < 7, documentMode is undefined, so attempt to use the\r\n * CSS1Compat property to see if we are in standards mode. If we are in\r\n * standards mode, treat the browser version as the document mode. Otherwise,\r\n * IE is emulating version 5.\r\n * @type {number|undefined}\r\n * @const\r\n */\r\ngoog.userAgent.DOCUMENT_MODE = (function() {\r\n var doc = goog.global['document'];\r\n var mode = goog.userAgent.getDocumentMode_();\r\n if (!doc || !goog.userAgent.IE) {\r\n return undefined;\r\n }\r\n return mode || (doc['compatMode'] == 'CSS1Compat' ?\r\n parseInt(goog.userAgent.VERSION, 10) :\r\n 5);\r\n})();\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Closure user agent detection (Browser).\r\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\r\n * For more information on rendering engine, platform, or device see the other\r\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\r\n * goog.labs.userAgent.device respectively.)\r\n *\r\n * @author martone@google.com (Andy Martone)\r\n */\r\n\r\ngoog.provide('goog.labs.userAgent.browser');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.labs.userAgent.util');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string.internal');\r\n\r\n\r\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\r\n// functions.\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium\r\n * based Opera (Opera 15+) is detected as Chrome to avoid unnecessary\r\n * special casing.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchOpera_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Opera');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is IE.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchIE_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Trident') ||\r\n goog.labs.userAgent.util.matchUserAgent('MSIE');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Edge.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchEdge_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Edge');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Firefox.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchFirefox_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Firefox') ||\r\n goog.labs.userAgent.util.matchUserAgent('FxiOS');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Safari.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchSafari_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Safari') &&\r\n !(goog.labs.userAgent.browser.matchChrome_() ||\r\n goog.labs.userAgent.browser.matchCoast_() ||\r\n goog.labs.userAgent.browser.matchOpera_() ||\r\n goog.labs.userAgent.browser.matchEdge_() ||\r\n goog.labs.userAgent.browser.matchFirefox_() ||\r\n goog.labs.userAgent.browser.isSilk() ||\r\n goog.labs.userAgent.util.matchUserAgent('Android'));\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\r\n * iOS browser).\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchCoast_ = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Coast');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is iOS Webview.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchIosWebview_ = function() {\r\n // iOS Webview does not show up as Chrome or Safari. Also check for Opera's\r\n // WebKit-based iOS browser, Coast.\r\n return (goog.labs.userAgent.util.matchUserAgent('iPad') ||\r\n goog.labs.userAgent.util.matchUserAgent('iPhone')) &&\r\n !goog.labs.userAgent.browser.matchSafari_() &&\r\n !goog.labs.userAgent.browser.matchChrome_() &&\r\n !goog.labs.userAgent.browser.matchCoast_() &&\r\n !goog.labs.userAgent.browser.matchFirefox_() &&\r\n goog.labs.userAgent.util.matchUserAgent('AppleWebKit');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Chrome.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchChrome_ = function() {\r\n return (goog.labs.userAgent.util.matchUserAgent('Chrome') ||\r\n goog.labs.userAgent.util.matchUserAgent('CriOS')) &&\r\n !goog.labs.userAgent.browser.matchEdge_();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is the Android browser.\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.matchAndroidBrowser_ = function() {\r\n // Android can appear in the user agent string for Chrome on Android.\r\n // This is not the Android standalone browser if it does.\r\n return goog.labs.userAgent.util.matchUserAgent('Android') &&\r\n !(goog.labs.userAgent.browser.isChrome() ||\r\n goog.labs.userAgent.browser.isFirefox() ||\r\n goog.labs.userAgent.browser.isOpera() ||\r\n goog.labs.userAgent.browser.isSilk());\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Opera.\r\n */\r\ngoog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is IE.\r\n */\r\ngoog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Edge.\r\n */\r\ngoog.labs.userAgent.browser.isEdge = goog.labs.userAgent.browser.matchEdge_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Firefox.\r\n */\r\ngoog.labs.userAgent.browser.isFirefox =\r\n goog.labs.userAgent.browser.matchFirefox_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Safari.\r\n */\r\ngoog.labs.userAgent.browser.isSafari = goog.labs.userAgent.browser.matchSafari_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\r\n * iOS browser).\r\n */\r\ngoog.labs.userAgent.browser.isCoast = goog.labs.userAgent.browser.matchCoast_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is iOS Webview.\r\n */\r\ngoog.labs.userAgent.browser.isIosWebview =\r\n goog.labs.userAgent.browser.matchIosWebview_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is Chrome.\r\n */\r\ngoog.labs.userAgent.browser.isChrome = goog.labs.userAgent.browser.matchChrome_;\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user's browser is the Android browser.\r\n */\r\ngoog.labs.userAgent.browser.isAndroidBrowser =\r\n goog.labs.userAgent.browser.matchAndroidBrowser_;\r\n\r\n\r\n/**\r\n * For more information, see:\r\n * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html\r\n * @return {boolean} Whether the user's browser is Silk.\r\n */\r\ngoog.labs.userAgent.browser.isSilk = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Silk');\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The browser version or empty string if version cannot be\r\n * determined. Note that for Internet Explorer, this returns the version of\r\n * the browser, not the version of the rendering engine. (IE 8 in\r\n * compatibility mode will return 8.0 rather than 7.0. To determine the\r\n * rendering engine version, look at document.documentMode instead. See\r\n * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more\r\n * details.)\r\n */\r\ngoog.labs.userAgent.browser.getVersion = function() {\r\n var userAgentString = goog.labs.userAgent.util.getUserAgent();\r\n // Special case IE since IE's version is inside the parenthesis and\r\n // without the '/'.\r\n if (goog.labs.userAgent.browser.isIE()) {\r\n return goog.labs.userAgent.browser.getIEVersion_(userAgentString);\r\n }\r\n\r\n var versionTuples =\r\n goog.labs.userAgent.util.extractVersionTuples(userAgentString);\r\n\r\n // Construct a map for easy lookup.\r\n var versionMap = {};\r\n goog.array.forEach(versionTuples, function(tuple) {\r\n // Note that the tuple is of length three, but we only care about the\r\n // first two.\r\n var key = tuple[0];\r\n var value = tuple[1];\r\n versionMap[key] = value;\r\n });\r\n\r\n var versionMapHasKey = goog.partial(goog.object.containsKey, versionMap);\r\n\r\n // Gives the value with the first key it finds, otherwise empty string.\r\n function lookUpValueWithKeys(keys) {\r\n var key = goog.array.find(keys, versionMapHasKey);\r\n return versionMap[key] || '';\r\n }\r\n\r\n // Check Opera before Chrome since Opera 15+ has \"Chrome\" in the string.\r\n // See\r\n // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond\r\n if (goog.labs.userAgent.browser.isOpera()) {\r\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\" first.\r\n // Opera uses 'OPR' for more recent UAs.\r\n return lookUpValueWithKeys(['Version', 'Opera']);\r\n }\r\n\r\n // Check Edge before Chrome since it has Chrome in the string.\r\n if (goog.labs.userAgent.browser.isEdge()) {\r\n return lookUpValueWithKeys(['Edge']);\r\n }\r\n\r\n if (goog.labs.userAgent.browser.isChrome()) {\r\n return lookUpValueWithKeys(['Chrome', 'CriOS']);\r\n }\r\n\r\n // Usually products browser versions are in the third tuple after \"Mozilla\"\r\n // and the engine.\r\n var tuple = versionTuples[2];\r\n return tuple && tuple[1] || '';\r\n};\r\n\r\n\r\n/**\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the browser version is higher or the same as the\r\n * given version.\r\n */\r\ngoog.labs.userAgent.browser.isVersionOrHigher = function(version) {\r\n return goog.string.internal.compareVersions(\r\n goog.labs.userAgent.browser.getVersion(), version) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * Determines IE version. More information:\r\n * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString\r\n * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx\r\n * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx\r\n * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx\r\n *\r\n * @param {string} userAgent the User-Agent.\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.labs.userAgent.browser.getIEVersion_ = function(userAgent) {\r\n // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade\r\n // bug. Example UA:\r\n // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)\r\n // like Gecko.\r\n // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.\r\n var rv = /rv: *([\\d\\.]*)/.exec(userAgent);\r\n if (rv && rv[1]) {\r\n return rv[1];\r\n }\r\n\r\n var version = '';\r\n var msie = /MSIE +([\\d\\.]+)/.exec(userAgent);\r\n if (msie && msie[1]) {\r\n // IE in compatibility mode usually identifies itself as MSIE 7.0; in this\r\n // case, use the Trident version to determine the version of IE. For more\r\n // details, see the links above.\r\n var tridentVersion = /Trident\\/(\\d.\\d)/.exec(userAgent);\r\n if (msie[1] == '7.0') {\r\n if (tridentVersion && tridentVersion[1]) {\r\n switch (tridentVersion[1]) {\r\n case '4.0':\r\n version = '8.0';\r\n break;\r\n case '5.0':\r\n version = '9.0';\r\n break;\r\n case '6.0':\r\n version = '10.0';\r\n break;\r\n case '7.0':\r\n version = '11.0';\r\n break;\r\n }\r\n } else {\r\n version = '7.0';\r\n }\r\n } else {\r\n version = msie[1];\r\n }\r\n }\r\n return version;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Closure user agent detection.\r\n * @see http://en.wikipedia.org/wiki/User_agent\r\n * For more information on browser brand, platform, or device see the other\r\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\r\n *\r\n */\r\n\r\ngoog.provide('goog.labs.userAgent.engine');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.labs.userAgent.util');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Presto.\r\n */\r\ngoog.labs.userAgent.engine.isPresto = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Presto');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Trident.\r\n */\r\ngoog.labs.userAgent.engine.isTrident = function() {\r\n // IE only started including the Trident token in IE8.\r\n return goog.labs.userAgent.util.matchUserAgent('Trident') ||\r\n goog.labs.userAgent.util.matchUserAgent('MSIE');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Edge.\r\n */\r\ngoog.labs.userAgent.engine.isEdge = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Edge');\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is WebKit.\r\n */\r\ngoog.labs.userAgent.engine.isWebKit = function() {\r\n return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') &&\r\n !goog.labs.userAgent.engine.isEdge();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the rendering engine is Gecko.\r\n */\r\ngoog.labs.userAgent.engine.isGecko = function() {\r\n return goog.labs.userAgent.util.matchUserAgent('Gecko') &&\r\n !goog.labs.userAgent.engine.isWebKit() &&\r\n !goog.labs.userAgent.engine.isTrident() &&\r\n !goog.labs.userAgent.engine.isEdge();\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The rendering engine's version or empty string if version\r\n * can't be determined.\r\n */\r\ngoog.labs.userAgent.engine.getVersion = function() {\r\n var userAgentString = goog.labs.userAgent.util.getUserAgent();\r\n if (userAgentString) {\r\n var tuples = goog.labs.userAgent.util.extractVersionTuples(userAgentString);\r\n\r\n var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples);\r\n if (engineTuple) {\r\n // In Gecko, the version string is either in the browser info or the\r\n // Firefox version. See Gecko user agent string reference:\r\n // http://goo.gl/mULqa\r\n if (engineTuple[0] == 'Gecko') {\r\n return goog.labs.userAgent.engine.getVersionForKey_(tuples, 'Firefox');\r\n }\r\n\r\n return engineTuple[1];\r\n }\r\n\r\n // MSIE has only one version identifier, and the Trident version is\r\n // specified in the parenthetical. IE Edge is covered in the engine tuple\r\n // detection.\r\n var browserTuple = tuples[0];\r\n var info;\r\n if (browserTuple && (info = browserTuple[2])) {\r\n var match = /Trident\\/([^\\s;]+)/.exec(info);\r\n if (match) {\r\n return match[1];\r\n }\r\n }\r\n }\r\n return '';\r\n};\r\n\r\n\r\n/**\r\n * @param {!Array<!Array<string>>} tuples Extracted version tuples.\r\n * @return {!Array<string>|undefined} The engine tuple or undefined if not\r\n * found.\r\n * @private\r\n */\r\ngoog.labs.userAgent.engine.getEngineTuple_ = function(tuples) {\r\n if (!goog.labs.userAgent.engine.isEdge()) {\r\n return tuples[1];\r\n }\r\n for (var i = 0; i < tuples.length; i++) {\r\n var tuple = tuples[i];\r\n if (tuple[0] == 'Edge') {\r\n return tuple;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {string|number} version The version to check.\r\n * @return {boolean} Whether the rendering engine version is higher or the same\r\n * as the given version.\r\n */\r\ngoog.labs.userAgent.engine.isVersionOrHigher = function(version) {\r\n return goog.string.compareVersions(\r\n goog.labs.userAgent.engine.getVersion(), version) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * @param {!Array<!Array<string>>} tuples Version tuples.\r\n * @param {string} key The key to look for.\r\n * @return {string} The version string of the given key, if present.\r\n * Otherwise, the empty string.\r\n * @private\r\n */\r\ngoog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) {\r\n // TODO(nnaze): Move to util if useful elsewhere.\r\n\r\n var pair = goog.array.find(tuples, function(pair) { return key == pair[0]; });\r\n\r\n return pair && pair[1] || '';\r\n};\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Browser capability checks for the events package.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.events.BrowserFeature');\r\n\r\ngoog.require('goog.userAgent');\r\ngoog.scope(function() {\r\n\r\n\r\n\r\n/**\r\n * Enum of browser capabilities.\r\n * @enum {boolean}\r\n */\r\ngoog.events.BrowserFeature = {\r\n /**\r\n * Whether the button attribute of the event is W3C compliant. False in\r\n * Internet Explorer prior to version 9; document-version dependent.\r\n */\r\n HAS_W3C_BUTTON:\r\n !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),\r\n\r\n /**\r\n * Whether the browser supports full W3C event model.\r\n */\r\n HAS_W3C_EVENT_SUPPORT:\r\n !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(9),\r\n\r\n /**\r\n * To prevent default in IE7-8 for certain keydown events we need set the\r\n * keyCode to -1.\r\n */\r\n SET_KEY_CODE_TO_PREVENT_DEFAULT:\r\n goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),\r\n\r\n /**\r\n * Whether the `navigator.onLine` property is supported.\r\n */\r\n HAS_NAVIGATOR_ONLINE_PROPERTY:\r\n !goog.userAgent.WEBKIT || goog.userAgent.isVersionOrHigher('528'),\r\n\r\n /**\r\n * Whether HTML5 network online/offline events are supported.\r\n */\r\n HAS_HTML5_NETWORK_EVENT_SUPPORT:\r\n goog.userAgent.GECKO && goog.userAgent.isVersionOrHigher('1.9b') ||\r\n goog.userAgent.IE && goog.userAgent.isVersionOrHigher('8') ||\r\n goog.userAgent.OPERA && goog.userAgent.isVersionOrHigher('9.5') ||\r\n goog.userAgent.WEBKIT && goog.userAgent.isVersionOrHigher('528'),\r\n\r\n /**\r\n * Whether HTML5 network events fire on document.body, or otherwise the\r\n * window.\r\n */\r\n HTML5_NETWORK_EVENTS_FIRE_ON_BODY:\r\n goog.userAgent.GECKO && !goog.userAgent.isVersionOrHigher('8') ||\r\n goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9'),\r\n\r\n /**\r\n * Whether touch is enabled in the browser.\r\n */\r\n TOUCH_ENABLED:\r\n ('ontouchstart' in goog.global ||\r\n !!(goog.global['document'] && document.documentElement &&\r\n 'ontouchstart' in document.documentElement) ||\r\n // IE10 uses non-standard touch events, so it has a different check.\r\n !!(goog.global['navigator'] &&\r\n (goog.global['navigator']['maxTouchPoints'] ||\r\n goog.global['navigator']['msMaxTouchPoints']))),\r\n\r\n /**\r\n * Whether addEventListener supports W3C standard pointer events.\r\n * http://www.w3.org/TR/pointerevents/\r\n */\r\n POINTER_EVENTS: ('PointerEvent' in goog.global),\r\n\r\n /**\r\n * Whether addEventListener supports MSPointer events (only used in IE10).\r\n * http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\r\n * http://msdn.microsoft.com/library/hh673557(v=vs.85).aspx\r\n */\r\n MSPOINTER_EVENTS:\r\n ('MSPointerEvent' in goog.global &&\r\n !!(goog.global['navigator'] &&\r\n goog.global['navigator']['msPointerEnabled'])),\r\n\r\n /**\r\n * Whether addEventListener supports {passive: true}.\r\n * https://developers.google.com/web/updates/2016/06/passive-event-listeners\r\n */\r\n PASSIVE_EVENTS: purify(function() {\r\n // If we're in a web worker or other custom environment, we can't tell.\r\n if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8\r\n return false;\r\n }\r\n\r\n var passive = false;\r\n var options = Object.defineProperty({}, 'passive', {\r\n get: function() {\r\n passive = true;\r\n }\r\n });\r\n try {\r\n goog.global.addEventListener('test', goog.nullFunction, options);\r\n goog.global.removeEventListener('test', goog.nullFunction, options);\r\n } catch (e) {\r\n }\r\n\r\n return passive;\r\n })\r\n};\r\n\r\n\r\n/**\r\n * Tricks Closure Compiler into believing that a function is pure. The compiler\r\n * assumes that any `valueOf` function is pure, without analyzing its contents.\r\n *\r\n * @param {function(): T} fn\r\n * @return {T}\r\n * @template T\r\n */\r\nfunction purify(fn) {\r\n return ({valueOf: fn}).valueOf();\r\n}\r\n}); // goog.scope\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A base class for event objects.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.events.Event');\r\ngoog.provide('goog.events.EventLike');\r\n\r\n/**\r\n * goog.events.Event no longer depends on goog.Disposable. Keep requiring\r\n * goog.Disposable here to not break projects which assume this dependency.\r\n * @suppress {extraRequire}\r\n */\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.events.EventId');\r\n\r\n\r\n/**\r\n * A typedef for event like objects that are dispatchable via the\r\n * goog.events.dispatchEvent function. strings are treated as the type for a\r\n * goog.events.Event. Objects are treated as an extension of a new\r\n * goog.events.Event with the type property of the object being used as the type\r\n * of the Event.\r\n * @typedef {string|Object|goog.events.Event|goog.events.EventId}\r\n */\r\ngoog.events.EventLike;\r\n\r\n\r\n\r\n/**\r\n * A base class for event objects, so that they can support preventDefault and\r\n * stopPropagation.\r\n *\r\n * @suppress {underscore} Several properties on this class are technically\r\n * public, but referencing these properties outside this package is strongly\r\n * discouraged.\r\n *\r\n * @param {string|!goog.events.EventId} type Event Type.\r\n * @param {Object=} opt_target Reference to the object that is the target of\r\n * this event. It has to implement the `EventTarget` interface\r\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\r\n * @constructor\r\n */\r\ngoog.events.Event = function(type, opt_target) {\r\n /**\r\n * Event type.\r\n * @type {string}\r\n */\r\n this.type = type instanceof goog.events.EventId ? String(type) : type;\r\n\r\n /**\r\n * TODO(tbreisacher): The type should probably be\r\n * EventTarget|goog.events.EventTarget.\r\n *\r\n * Target of the event.\r\n * @type {Object|undefined}\r\n */\r\n this.target = opt_target;\r\n\r\n /**\r\n * Object that had the listener attached.\r\n * @type {Object|undefined}\r\n */\r\n this.currentTarget = this.target;\r\n\r\n /**\r\n * Whether to cancel the event in internal capture/bubble processing for IE.\r\n * @type {boolean}\r\n * @public\r\n */\r\n this.propagationStopped_ = false;\r\n\r\n /**\r\n * Whether the default action has been prevented.\r\n * This is a property to match the W3C specification at\r\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\r\n * #events-event-type-defaultPrevented}.\r\n * Must be treated as read-only outside the class.\r\n * @type {boolean}\r\n */\r\n this.defaultPrevented = false;\r\n\r\n /**\r\n * Return value for in internal capture/bubble processing for IE.\r\n * @type {boolean}\r\n * @public\r\n */\r\n this.returnValue_ = true;\r\n};\r\n\r\n\r\n/**\r\n * Stops event propagation.\r\n */\r\ngoog.events.Event.prototype.stopPropagation = function() {\r\n this.propagationStopped_ = true;\r\n};\r\n\r\n\r\n/**\r\n * Prevents the default action, for example a link redirecting to a url.\r\n */\r\ngoog.events.Event.prototype.preventDefault = function() {\r\n this.defaultPrevented = true;\r\n this.returnValue_ = false;\r\n};\r\n\r\n\r\n/**\r\n * Stops the propagation of the event. It is equivalent to\r\n * `e.stopPropagation()`, but can be used as the callback argument of\r\n * {@link goog.events.listen} without declaring another function.\r\n * @param {!goog.events.Event} e An event.\r\n */\r\ngoog.events.Event.stopPropagation = function(e) {\r\n e.stopPropagation();\r\n};\r\n\r\n\r\n/**\r\n * Prevents the default action. It is equivalent to\r\n * `e.preventDefault()`, but can be used as the callback argument of\r\n * {@link goog.events.listen} without declaring another function.\r\n * @param {!goog.events.Event} e An event.\r\n */\r\ngoog.events.Event.preventDefault = function(e) {\r\n e.preventDefault();\r\n};\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A patched, standardized event object for browser events.\r\n *\r\n * <pre>\r\n * The patched event object contains the following members:\r\n * - type {string} Event type, e.g. 'click'\r\n * - target {Object} The element that actually triggered the event\r\n * - currentTarget {Object} The element the listener is attached to\r\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\r\n * - offsetX {number} X-coordinate relative to target\r\n * - offsetY {number} Y-coordinate relative to target\r\n * - clientX {number} X-coordinate relative to viewport\r\n * - clientY {number} Y-coordinate relative to viewport\r\n * - screenX {number} X-coordinate relative to the edge of the screen\r\n * - screenY {number} Y-coordinate relative to the edge of the screen\r\n * - button {number} Mouse button. Use isButton() to test.\r\n * - keyCode {number} Key-code\r\n * - ctrlKey {boolean} Was ctrl key depressed\r\n * - altKey {boolean} Was alt key depressed\r\n * - shiftKey {boolean} Was shift key depressed\r\n * - metaKey {boolean} Was meta key depressed\r\n * - pointerId {number} Pointer ID\r\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\r\n * - defaultPrevented {boolean} Whether the default action has been prevented\r\n * - state {Object} History state object\r\n *\r\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\r\n * key and character code use {@link goog.events.KeyHandler}.\r\n * </pre>\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\ngoog.provide('goog.events.BrowserEvent');\r\ngoog.provide('goog.events.BrowserEvent.MouseButton');\r\ngoog.provide('goog.events.BrowserEvent.PointerType');\r\n\r\ngoog.require('goog.debug');\r\ngoog.require('goog.events.BrowserFeature');\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.EventType');\r\ngoog.require('goog.reflect');\r\ngoog.require('goog.userAgent');\r\n\r\n/**\r\n * @define {boolean} If true, use the layerX and layerY properties of a native\r\n * browser event over the offsetX and offsetY properties, which cause expensive\r\n * reflow. If layerX or layerY is not defined, offsetX and offsetY will be used\r\n * as usual.\r\n */\r\ngoog.events.USE_LAYER_XY_AS_OFFSET_XY =\r\n goog.define('goog.events.USE_LAYER_XY_AS_OFFSET_XY', false);\r\n\r\n/**\r\n * Accepts a browser event object and creates a patched, cross browser event\r\n * object.\r\n * The content of this object will not be initialized if no event object is\r\n * provided. If this is the case, init() needs to be invoked separately.\r\n * @param {Event=} opt_e Browser event object.\r\n * @param {EventTarget=} opt_currentTarget Current target for event.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\ngoog.events.BrowserEvent = function(opt_e, opt_currentTarget) {\r\n goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');\r\n\r\n /**\r\n * Target that fired the event.\r\n * @override\r\n * @type {?Node}\r\n */\r\n this.target = null;\r\n\r\n /**\r\n * Node that had the listener attached.\r\n * @override\r\n * @type {?Node|undefined}\r\n */\r\n this.currentTarget = null;\r\n\r\n /**\r\n * For mouseover and mouseout events, the related object for the event.\r\n * @type {?Node}\r\n */\r\n this.relatedTarget = null;\r\n\r\n /**\r\n * X-coordinate relative to target.\r\n * @type {number}\r\n */\r\n this.offsetX = 0;\r\n\r\n /**\r\n * Y-coordinate relative to target.\r\n * @type {number}\r\n */\r\n this.offsetY = 0;\r\n\r\n /**\r\n * X-coordinate relative to the window.\r\n * @type {number}\r\n */\r\n this.clientX = 0;\r\n\r\n /**\r\n * Y-coordinate relative to the window.\r\n * @type {number}\r\n */\r\n this.clientY = 0;\r\n\r\n /**\r\n * X-coordinate relative to the monitor.\r\n * @type {number}\r\n */\r\n this.screenX = 0;\r\n\r\n /**\r\n * Y-coordinate relative to the monitor.\r\n * @type {number}\r\n */\r\n this.screenY = 0;\r\n\r\n /**\r\n * Which mouse button was pressed.\r\n * @type {number}\r\n */\r\n this.button = 0;\r\n\r\n /**\r\n * Key of key press.\r\n * @type {string}\r\n */\r\n this.key = '';\r\n\r\n /**\r\n * Keycode of key press.\r\n * @type {number}\r\n */\r\n this.keyCode = 0;\r\n\r\n /**\r\n * Keycode of key press.\r\n * @type {number}\r\n */\r\n this.charCode = 0;\r\n\r\n /**\r\n * Whether control was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.ctrlKey = false;\r\n\r\n /**\r\n * Whether alt was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.altKey = false;\r\n\r\n /**\r\n * Whether shift was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.shiftKey = false;\r\n\r\n /**\r\n * Whether the meta key was pressed at time of event.\r\n * @type {boolean}\r\n */\r\n this.metaKey = false;\r\n\r\n /**\r\n * History state object, only set for PopState events where it's a copy of the\r\n * state object provided to pushState or replaceState.\r\n * @type {?Object}\r\n */\r\n this.state = null;\r\n\r\n /**\r\n * Whether the default platform modifier key was pressed at time of event.\r\n * (This is control for all platforms except Mac, where it's Meta.)\r\n * @type {boolean}\r\n */\r\n this.platformModifierKey = false;\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.pointerId = 0;\r\n\r\n /**\r\n * @type {string}\r\n */\r\n this.pointerType = '';\r\n\r\n /**\r\n * The browser event object.\r\n * @private {?Event}\r\n */\r\n this.event_ = null;\r\n\r\n if (opt_e) {\r\n this.init(opt_e, opt_currentTarget);\r\n }\r\n};\r\ngoog.inherits(goog.events.BrowserEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Normalized button constants for the mouse.\r\n * @enum {number}\r\n */\r\ngoog.events.BrowserEvent.MouseButton = {\r\n LEFT: 0,\r\n MIDDLE: 1,\r\n RIGHT: 2\r\n};\r\n\r\n\r\n/**\r\n * Normalized pointer type constants for pointer events.\r\n * @enum {string}\r\n */\r\ngoog.events.BrowserEvent.PointerType = {\r\n MOUSE: 'mouse',\r\n PEN: 'pen',\r\n TOUCH: 'touch'\r\n};\r\n\r\n\r\n/**\r\n * Static data for mapping mouse buttons.\r\n * @type {!Array<number>}\r\n * @deprecated Use `goog.events.BrowserEvent.IE_BUTTON_MAP` instead.\r\n */\r\ngoog.events.BrowserEvent.IEButtonMap = goog.debug.freeze([\r\n 1, // LEFT\r\n 4, // MIDDLE\r\n 2 // RIGHT\r\n]);\r\n\r\n\r\n/**\r\n * Static data for mapping mouse buttons.\r\n * @const {!Array<number>}\r\n */\r\ngoog.events.BrowserEvent.IE_BUTTON_MAP = goog.events.BrowserEvent.IEButtonMap;\r\n\r\n\r\n/**\r\n * Static data for mapping MSPointerEvent types to PointerEvent types.\r\n * @const {!Object<number, goog.events.BrowserEvent.PointerType>}\r\n */\r\ngoog.events.BrowserEvent.IE_POINTER_TYPE_MAP = goog.debug.freeze({\r\n 2: goog.events.BrowserEvent.PointerType.TOUCH,\r\n 3: goog.events.BrowserEvent.PointerType.PEN,\r\n 4: goog.events.BrowserEvent.PointerType.MOUSE\r\n});\r\n\r\n\r\n/**\r\n * Accepts a browser event object and creates a patched, cross browser event\r\n * object.\r\n * @param {Event} e Browser event object.\r\n * @param {EventTarget=} opt_currentTarget Current target for event.\r\n */\r\ngoog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {\r\n var type = this.type = e.type;\r\n\r\n /**\r\n * On touch devices use the first \"changed touch\" as the relevant touch.\r\n * @type {?Touch}\r\n */\r\n var relevantTouch =\r\n e.changedTouches && e.changedTouches.length ? e.changedTouches[0] : null;\r\n\r\n // TODO(nicksantos): Change this.target to type EventTarget.\r\n this.target = /** @type {Node} */ (e.target) || e.srcElement;\r\n\r\n // TODO(nicksantos): Change this.currentTarget to type EventTarget.\r\n this.currentTarget = /** @type {Node} */ (opt_currentTarget);\r\n\r\n var relatedTarget = /** @type {Node} */ (e.relatedTarget);\r\n if (relatedTarget) {\r\n // There's a bug in FireFox where sometimes, relatedTarget will be a\r\n // chrome element, and accessing any property of it will get a permission\r\n // denied exception. See:\r\n // https://bugzilla.mozilla.org/show_bug.cgi?id=497780\r\n if (goog.userAgent.GECKO) {\r\n if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {\r\n relatedTarget = null;\r\n }\r\n }\r\n } else if (type == goog.events.EventType.MOUSEOVER) {\r\n relatedTarget = e.fromElement;\r\n } else if (type == goog.events.EventType.MOUSEOUT) {\r\n relatedTarget = e.toElement;\r\n }\r\n\r\n this.relatedTarget = relatedTarget;\r\n\r\n if (relevantTouch) {\r\n this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :\r\n relevantTouch.pageX;\r\n this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :\r\n relevantTouch.pageY;\r\n this.screenX = relevantTouch.screenX || 0;\r\n this.screenY = relevantTouch.screenY || 0;\r\n } else {\r\n if (goog.events.USE_LAYER_XY_AS_OFFSET_XY) {\r\n this.offsetX = (e.layerX !== undefined) ? e.layerX : e.offsetX;\r\n this.offsetY = (e.layerY !== undefined) ? e.layerY : e.offsetY;\r\n } else {\r\n // Webkit emits a lame warning whenever layerX/layerY is accessed.\r\n // http://code.google.com/p/chromium/issues/detail?id=101733\r\n this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?\r\n e.offsetX :\r\n e.layerX;\r\n this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?\r\n e.offsetY :\r\n e.layerY;\r\n }\r\n this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;\r\n this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;\r\n this.screenX = e.screenX || 0;\r\n this.screenY = e.screenY || 0;\r\n }\r\n\r\n this.button = e.button;\r\n\r\n this.keyCode = e.keyCode || 0;\r\n this.key = e.key || '';\r\n this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);\r\n this.ctrlKey = e.ctrlKey;\r\n this.altKey = e.altKey;\r\n this.shiftKey = e.shiftKey;\r\n this.metaKey = e.metaKey;\r\n this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;\r\n this.pointerId = e.pointerId || 0;\r\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\r\n this.state = e.state;\r\n this.event_ = e;\r\n if (e.defaultPrevented) {\r\n this.preventDefault();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Tests to see which button was pressed during the event. This is really only\r\n * useful in IE and Gecko browsers. And in IE, it's only useful for\r\n * mousedown/mouseup events, because click only fires for the left mouse button.\r\n *\r\n * Safari 2 only reports the left button being clicked, and uses the value '1'\r\n * instead of 0. Opera only reports a mousedown event for the middle button, and\r\n * no mouse events for the right button. Opera has default behavior for left and\r\n * middle click that can only be overridden via a configuration setting.\r\n *\r\n * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.\r\n *\r\n * @param {goog.events.BrowserEvent.MouseButton} button The button\r\n * to test for.\r\n * @return {boolean} True if button was pressed.\r\n */\r\ngoog.events.BrowserEvent.prototype.isButton = function(button) {\r\n if (!goog.events.BrowserFeature.HAS_W3C_BUTTON) {\r\n if (this.type == 'click') {\r\n return button == goog.events.BrowserEvent.MouseButton.LEFT;\r\n } else {\r\n return !!(\r\n this.event_.button & goog.events.BrowserEvent.IE_BUTTON_MAP[button]);\r\n }\r\n } else {\r\n return this.event_.button == button;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Whether this has an \"action\"-producing mouse button.\r\n *\r\n * By definition, this includes left-click on windows/linux, and left-click\r\n * without the ctrl key on Macs.\r\n *\r\n * @return {boolean} The result.\r\n */\r\ngoog.events.BrowserEvent.prototype.isMouseActionButton = function() {\r\n // Webkit does not ctrl+click to be a right-click, so we\r\n // normalize it to behave like Gecko and Opera.\r\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\r\n !(goog.userAgent.WEBKIT && goog.userAgent.MAC && this.ctrlKey);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\r\n goog.events.BrowserEvent.superClass_.stopPropagation.call(this);\r\n if (this.event_.stopPropagation) {\r\n this.event_.stopPropagation();\r\n } else {\r\n this.event_.cancelBubble = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\ngoog.events.BrowserEvent.prototype.preventDefault = function() {\r\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\r\n var be = this.event_;\r\n if (!be.preventDefault) {\r\n be.returnValue = false;\r\n if (goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT) {\r\n\r\n try {\r\n // Most keys can be prevented using returnValue. Some special keys\r\n // require setting the keyCode to -1 as well:\r\n //\r\n // In IE7:\r\n // F3, F5, F10, F11, Ctrl+P, Crtl+O, Ctrl+F (these are taken from IE6)\r\n //\r\n // In IE8:\r\n // Ctrl+P, Crtl+O, Ctrl+F (F1-F12 cannot be stopped through the event)\r\n //\r\n // We therefore do this for all function keys as well as when Ctrl key\r\n // is pressed.\r\n var VK_F1 = 112;\r\n var VK_F12 = 123;\r\n if (be.ctrlKey || be.keyCode >= VK_F1 && be.keyCode <= VK_F12) {\r\n be.keyCode = -1;\r\n }\r\n } catch (ex) {\r\n // IE throws an 'access denied' exception when trying to change\r\n // keyCode in some situations (e.g. srcElement is input[type=file],\r\n // or srcElement is an anchor tag rewritten by parent's innerHTML).\r\n // Do nothing in this case.\r\n }\r\n }\r\n } else {\r\n be.preventDefault();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {Event} The underlying browser event object.\r\n */\r\ngoog.events.BrowserEvent.prototype.getBrowserEvent = function() {\r\n return this.event_;\r\n};\r\n\r\n\r\n/**\r\n * Extracts the pointer type from the given event.\r\n * @param {!Event} e\r\n * @return {string} The pointer type, e.g. 'mouse', 'pen', or 'touch'.\r\n * @private\r\n */\r\ngoog.events.BrowserEvent.getPointerType_ = function(e) {\r\n if (goog.isString(e.pointerType)) {\r\n return e.pointerType;\r\n }\r\n // IE10 uses integer codes for pointer type.\r\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\r\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\r\n};\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Event Types.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.events.EventType');\r\ngoog.provide('goog.events.MouseAsMouseEventType');\r\ngoog.provide('goog.events.MouseEvents');\r\ngoog.provide('goog.events.PointerAsMouseEventType');\r\ngoog.provide('goog.events.PointerAsTouchEventType');\r\ngoog.provide('goog.events.PointerFallbackEventType');\r\ngoog.provide('goog.events.PointerTouchFallbackEventType');\r\n\r\ngoog.require('goog.events.BrowserFeature');\r\ngoog.require('goog.userAgent');\r\n\r\n\r\n/**\r\n * Returns a prefixed event name for the current browser.\r\n * @param {string} eventName The name of the event.\r\n * @return {string} The prefixed event name.\r\n * @suppress {missingRequire|missingProvide}\r\n * @private\r\n */\r\ngoog.events.getVendorPrefixedName_ = function(eventName) {\r\n return goog.userAgent.WEBKIT ?\r\n 'webkit' + eventName :\r\n (goog.userAgent.OPERA ? 'o' + eventName.toLowerCase() :\r\n eventName.toLowerCase());\r\n};\r\n\r\n\r\n/**\r\n * Constants for event names.\r\n * @enum {string}\r\n */\r\ngoog.events.EventType = {\r\n // Mouse events\r\n CLICK: 'click',\r\n RIGHTCLICK: 'rightclick',\r\n DBLCLICK: 'dblclick',\r\n AUXCLICK: 'auxclick',\r\n MOUSEDOWN: 'mousedown',\r\n MOUSEUP: 'mouseup',\r\n MOUSEOVER: 'mouseover',\r\n MOUSEOUT: 'mouseout',\r\n MOUSEMOVE: 'mousemove',\r\n MOUSEENTER: 'mouseenter',\r\n MOUSELEAVE: 'mouseleave',\r\n\r\n // Non-existent event; will never fire. This exists as a mouse counterpart to\r\n // POINTERCANCEL.\r\n MOUSECANCEL: 'mousecancel',\r\n\r\n // Selection events.\r\n // https://www.w3.org/TR/selection-api/\r\n SELECTIONCHANGE: 'selectionchange',\r\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\r\n\r\n // Wheel events\r\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\r\n WHEEL: 'wheel',\r\n\r\n // Key events\r\n KEYPRESS: 'keypress',\r\n KEYDOWN: 'keydown',\r\n KEYUP: 'keyup',\r\n\r\n // Focus\r\n BLUR: 'blur',\r\n FOCUS: 'focus',\r\n DEACTIVATE: 'deactivate', // IE only\r\n FOCUSIN: 'focusin',\r\n FOCUSOUT: 'focusout',\r\n\r\n // Forms\r\n CHANGE: 'change',\r\n RESET: 'reset',\r\n SELECT: 'select',\r\n SUBMIT: 'submit',\r\n INPUT: 'input',\r\n PROPERTYCHANGE: 'propertychange', // IE only\r\n\r\n // Drag and drop\r\n DRAGSTART: 'dragstart',\r\n DRAG: 'drag',\r\n DRAGENTER: 'dragenter',\r\n DRAGOVER: 'dragover',\r\n DRAGLEAVE: 'dragleave',\r\n DROP: 'drop',\r\n DRAGEND: 'dragend',\r\n\r\n // Touch events\r\n // Note that other touch events exist, but we should follow the W3C list here.\r\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\r\n TOUCHSTART: 'touchstart',\r\n TOUCHMOVE: 'touchmove',\r\n TOUCHEND: 'touchend',\r\n TOUCHCANCEL: 'touchcancel',\r\n\r\n // Misc\r\n BEFOREUNLOAD: 'beforeunload',\r\n CONSOLEMESSAGE: 'consolemessage',\r\n CONTEXTMENU: 'contextmenu',\r\n DEVICECHANGE: 'devicechange',\r\n DEVICEMOTION: 'devicemotion',\r\n DEVICEORIENTATION: 'deviceorientation',\r\n DOMCONTENTLOADED: 'DOMContentLoaded',\r\n ERROR: 'error',\r\n HELP: 'help',\r\n LOAD: 'load',\r\n LOSECAPTURE: 'losecapture',\r\n ORIENTATIONCHANGE: 'orientationchange',\r\n READYSTATECHANGE: 'readystatechange',\r\n RESIZE: 'resize',\r\n SCROLL: 'scroll',\r\n UNLOAD: 'unload',\r\n\r\n // Media events\r\n CANPLAY: 'canplay',\r\n CANPLAYTHROUGH: 'canplaythrough',\r\n DURATIONCHANGE: 'durationchange',\r\n EMPTIED: 'emptied',\r\n ENDED: 'ended',\r\n LOADEDDATA: 'loadeddata',\r\n LOADEDMETADATA: 'loadedmetadata',\r\n PAUSE: 'pause',\r\n PLAY: 'play',\r\n PLAYING: 'playing',\r\n RATECHANGE: 'ratechange',\r\n SEEKED: 'seeked',\r\n SEEKING: 'seeking',\r\n STALLED: 'stalled',\r\n SUSPEND: 'suspend',\r\n TIMEUPDATE: 'timeupdate',\r\n VOLUMECHANGE: 'volumechange',\r\n WAITING: 'waiting',\r\n\r\n // Media Source Extensions events\r\n // https://www.w3.org/TR/media-source/#mediasource-events\r\n SOURCEOPEN: 'sourceopen',\r\n SOURCEENDED: 'sourceended',\r\n SOURCECLOSED: 'sourceclosed',\r\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\r\n ABORT: 'abort',\r\n UPDATE: 'update',\r\n UPDATESTART: 'updatestart',\r\n UPDATEEND: 'updateend',\r\n\r\n // HTML 5 History events\r\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\r\n HASHCHANGE: 'hashchange',\r\n PAGEHIDE: 'pagehide',\r\n PAGESHOW: 'pageshow',\r\n POPSTATE: 'popstate',\r\n\r\n // Copy and Paste\r\n // Support is limited. Make sure it works on your favorite browser\r\n // before using.\r\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\r\n COPY: 'copy',\r\n PASTE: 'paste',\r\n CUT: 'cut',\r\n BEFORECOPY: 'beforecopy',\r\n BEFORECUT: 'beforecut',\r\n BEFOREPASTE: 'beforepaste',\r\n\r\n // HTML5 online/offline events.\r\n // http://www.w3.org/TR/offline-webapps/#related\r\n ONLINE: 'online',\r\n OFFLINE: 'offline',\r\n\r\n // HTML 5 worker events\r\n MESSAGE: 'message',\r\n CONNECT: 'connect',\r\n\r\n // Service Worker Events - ServiceWorkerGlobalScope context\r\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\r\n // Note: message event defined in worker events section\r\n INSTALL: 'install',\r\n ACTIVATE: 'activate',\r\n FETCH: 'fetch',\r\n FOREIGNFETCH: 'foreignfetch',\r\n MESSAGEERROR: 'messageerror',\r\n\r\n // Service Worker Events - Document context\r\n // See https://w3c.github.io/ServiceWorker/#document-context-events\r\n STATECHANGE: 'statechange',\r\n UPDATEFOUND: 'updatefound',\r\n CONTROLLERCHANGE: 'controllerchange',\r\n\r\n // CSS animation events.\r\n /** @suppress {missingRequire} */\r\n ANIMATIONSTART: goog.events.getVendorPrefixedName_('AnimationStart'),\r\n /** @suppress {missingRequire} */\r\n ANIMATIONEND: goog.events.getVendorPrefixedName_('AnimationEnd'),\r\n /** @suppress {missingRequire} */\r\n ANIMATIONITERATION: goog.events.getVendorPrefixedName_('AnimationIteration'),\r\n\r\n // CSS transition events. Based on the browser support described at:\r\n // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility\r\n /** @suppress {missingRequire} */\r\n TRANSITIONEND: goog.events.getVendorPrefixedName_('TransitionEnd'),\r\n\r\n // W3C Pointer Events\r\n // http://www.w3.org/TR/pointerevents/\r\n POINTERDOWN: 'pointerdown',\r\n POINTERUP: 'pointerup',\r\n POINTERCANCEL: 'pointercancel',\r\n POINTERMOVE: 'pointermove',\r\n POINTEROVER: 'pointerover',\r\n POINTEROUT: 'pointerout',\r\n POINTERENTER: 'pointerenter',\r\n POINTERLEAVE: 'pointerleave',\r\n GOTPOINTERCAPTURE: 'gotpointercapture',\r\n LOSTPOINTERCAPTURE: 'lostpointercapture',\r\n\r\n // IE specific events.\r\n // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\r\n // Note: these events will be supplanted in IE11.\r\n MSGESTURECHANGE: 'MSGestureChange',\r\n MSGESTUREEND: 'MSGestureEnd',\r\n MSGESTUREHOLD: 'MSGestureHold',\r\n MSGESTURESTART: 'MSGestureStart',\r\n MSGESTURETAP: 'MSGestureTap',\r\n MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',\r\n MSINERTIASTART: 'MSInertiaStart',\r\n MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',\r\n MSPOINTERCANCEL: 'MSPointerCancel',\r\n MSPOINTERDOWN: 'MSPointerDown',\r\n MSPOINTERENTER: 'MSPointerEnter',\r\n MSPOINTERHOVER: 'MSPointerHover',\r\n MSPOINTERLEAVE: 'MSPointerLeave',\r\n MSPOINTERMOVE: 'MSPointerMove',\r\n MSPOINTEROUT: 'MSPointerOut',\r\n MSPOINTEROVER: 'MSPointerOver',\r\n MSPOINTERUP: 'MSPointerUp',\r\n\r\n // Native IMEs/input tools events.\r\n TEXT: 'text',\r\n // The textInput event is supported in IE9+, but only in lower case. All other\r\n // browsers use the camel-case event name.\r\n TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',\r\n COMPOSITIONSTART: 'compositionstart',\r\n COMPOSITIONUPDATE: 'compositionupdate',\r\n COMPOSITIONEND: 'compositionend',\r\n\r\n // The beforeinput event is initially only supported in Safari. See\r\n // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome\r\n // implementation tracking.\r\n BEFOREINPUT: 'beforeinput',\r\n\r\n // Webview tag events\r\n // See https://developer.chrome.com/apps/tags/webview\r\n EXIT: 'exit',\r\n LOADABORT: 'loadabort',\r\n LOADCOMMIT: 'loadcommit',\r\n LOADREDIRECT: 'loadredirect',\r\n LOADSTART: 'loadstart',\r\n LOADSTOP: 'loadstop',\r\n RESPONSIVE: 'responsive',\r\n SIZECHANGED: 'sizechanged',\r\n UNRESPONSIVE: 'unresponsive',\r\n\r\n // HTML5 Page Visibility API. See details at\r\n // `goog.labs.dom.PageVisibilityMonitor`.\r\n VISIBILITYCHANGE: 'visibilitychange',\r\n\r\n // LocalStorage event.\r\n STORAGE: 'storage',\r\n\r\n // DOM Level 2 mutation events (deprecated).\r\n DOMSUBTREEMODIFIED: 'DOMSubtreeModified',\r\n DOMNODEINSERTED: 'DOMNodeInserted',\r\n DOMNODEREMOVED: 'DOMNodeRemoved',\r\n DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',\r\n DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',\r\n DOMATTRMODIFIED: 'DOMAttrModified',\r\n DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',\r\n\r\n // Print events.\r\n BEFOREPRINT: 'beforeprint',\r\n AFTERPRINT: 'afterprint',\r\n\r\n // Web app manifest events.\r\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\r\n APPINSTALLED: 'appinstalled'\r\n};\r\n\r\n\r\n/**\r\n * Returns one of the given pointer fallback event names in order of preference:\r\n * 1. pointerEventName\r\n * 2. msPointerEventName\r\n * 3. fallbackEventName\r\n * @param {string} pointerEventName\r\n * @param {string} msPointerEventName\r\n * @param {string} fallbackEventName\r\n * @return {string} The supported pointer or fallback (mouse or touch) event\r\n * name.\r\n * @private\r\n */\r\ngoog.events.getPointerFallbackEventName_ = function(\r\n pointerEventName, msPointerEventName, fallbackEventName) {\r\n if (goog.events.BrowserFeature.POINTER_EVENTS) {\r\n return pointerEventName;\r\n }\r\n if (goog.events.BrowserFeature.MSPOINTER_EVENTS) {\r\n return msPointerEventName;\r\n }\r\n return fallbackEventName;\r\n};\r\n\r\n\r\n/**\r\n * Constants for pointer event names that fall back to corresponding mouse event\r\n * names on unsupported platforms. These are intended to be drop-in replacements\r\n * for corresponding values in `goog.events.EventType`.\r\n * @enum {string}\r\n */\r\ngoog.events.PointerFallbackEventType = {\r\n POINTERDOWN: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\r\n goog.events.EventType.MOUSEDOWN),\r\n POINTERUP: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\r\n goog.events.EventType.MOUSEUP),\r\n POINTERCANCEL: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERCANCEL,\r\n goog.events.EventType.MSPOINTERCANCEL,\r\n // When falling back to mouse events, there is no MOUSECANCEL equivalent\r\n // of POINTERCANCEL. In this case POINTERUP already falls back to MOUSEUP\r\n // which represents both UP and CANCEL. POINTERCANCEL does not fall back\r\n // to MOUSEUP to prevent listening twice on the same event.\r\n goog.events.EventType.MOUSECANCEL),\r\n POINTERMOVE: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\r\n goog.events.EventType.MOUSEMOVE),\r\n POINTEROVER: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTEROVER, goog.events.EventType.MSPOINTEROVER,\r\n goog.events.EventType.MOUSEOVER),\r\n POINTEROUT: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTEROUT, goog.events.EventType.MSPOINTEROUT,\r\n goog.events.EventType.MOUSEOUT),\r\n POINTERENTER: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERENTER, goog.events.EventType.MSPOINTERENTER,\r\n goog.events.EventType.MOUSEENTER),\r\n POINTERLEAVE: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERLEAVE, goog.events.EventType.MSPOINTERLEAVE,\r\n goog.events.EventType.MOUSELEAVE)\r\n};\r\n\r\n\r\n/**\r\n * Constants for pointer event names that fall back to corresponding touch event\r\n * names on unsupported platforms. These are intended to be drop-in replacements\r\n * for corresponding values in `goog.events.EventType`.\r\n * @enum {string}\r\n */\r\ngoog.events.PointerTouchFallbackEventType = {\r\n POINTERDOWN: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\r\n goog.events.EventType.TOUCHSTART),\r\n POINTERUP: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\r\n goog.events.EventType.TOUCHEND),\r\n POINTERCANCEL: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERCANCEL,\r\n goog.events.EventType.MSPOINTERCANCEL, goog.events.EventType.TOUCHCANCEL),\r\n POINTERMOVE: goog.events.getPointerFallbackEventName_(\r\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\r\n goog.events.EventType.TOUCHMOVE)\r\n};\r\n\r\n\r\n/**\r\n * Mapping of mouse event names to underlying browser event names.\r\n * @typedef {{\r\n * MOUSEDOWN: string,\r\n * MOUSEUP: string,\r\n * MOUSECANCEL:string,\r\n * MOUSEMOVE:string,\r\n * MOUSEOVER:string,\r\n * MOUSEOUT:string,\r\n * MOUSEENTER:string,\r\n * MOUSELEAVE: string,\r\n * }}\r\n */\r\ngoog.events.MouseEvents;\r\n\r\n\r\n/**\r\n * An alias for `goog.events.EventType.MOUSE*` event types that is overridden by\r\n * corresponding `POINTER*` event types.\r\n * @const {!goog.events.MouseEvents}\r\n */\r\ngoog.events.PointerAsMouseEventType = {\r\n MOUSEDOWN: goog.events.PointerFallbackEventType.POINTERDOWN,\r\n MOUSEUP: goog.events.PointerFallbackEventType.POINTERUP,\r\n MOUSECANCEL: goog.events.PointerFallbackEventType.POINTERCANCEL,\r\n MOUSEMOVE: goog.events.PointerFallbackEventType.POINTERMOVE,\r\n MOUSEOVER: goog.events.PointerFallbackEventType.POINTEROVER,\r\n MOUSEOUT: goog.events.PointerFallbackEventType.POINTEROUT,\r\n MOUSEENTER: goog.events.PointerFallbackEventType.POINTERENTER,\r\n MOUSELEAVE: goog.events.PointerFallbackEventType.POINTERLEAVE\r\n};\r\n\r\n\r\n/**\r\n * An alias for `goog.events.EventType.MOUSE*` event types that continue to use\r\n * mouse events.\r\n * @const {!goog.events.MouseEvents}\r\n */\r\ngoog.events.MouseAsMouseEventType = {\r\n MOUSEDOWN: goog.events.EventType.MOUSEDOWN,\r\n MOUSEUP: goog.events.EventType.MOUSEUP,\r\n MOUSECANCEL: goog.events.EventType.MOUSECANCEL,\r\n MOUSEMOVE: goog.events.EventType.MOUSEMOVE,\r\n MOUSEOVER: goog.events.EventType.MOUSEOVER,\r\n MOUSEOUT: goog.events.EventType.MOUSEOUT,\r\n MOUSEENTER: goog.events.EventType.MOUSEENTER,\r\n MOUSELEAVE: goog.events.EventType.MOUSELEAVE\r\n};\r\n\r\n\r\n/**\r\n * An alias for `goog.events.EventType.TOUCH*` event types that is overridden by\r\n * corresponding `POINTER*` event types.\r\n * @enum {string}\r\n */\r\ngoog.events.PointerAsTouchEventType = {\r\n TOUCHCANCEL: goog.events.PointerTouchFallbackEventType.POINTERCANCEL,\r\n TOUCHEND: goog.events.PointerTouchFallbackEventType.POINTERUP,\r\n TOUCHMOVE: goog.events.PointerTouchFallbackEventType.POINTERMOVE,\r\n TOUCHSTART: goog.events.PointerTouchFallbackEventType.POINTERDOWN\r\n};\r\n","// Copyright 2012 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview An interface for a listenable JavaScript object.\r\n * @author chrishenry@google.com (Chris Henry)\r\n */\r\n\r\ngoog.provide('goog.events.Listenable');\r\ngoog.provide('goog.events.ListenableKey');\r\n\r\n/** @suppress {extraRequire} */\r\ngoog.require('goog.events.EventId');\r\n\r\ngoog.forwardDeclare('goog.events.EventLike');\r\ngoog.forwardDeclare('goog.events.EventTarget');\r\n\r\n\r\n\r\n/**\r\n * A listenable interface. A listenable is an object with the ability\r\n * to dispatch/broadcast events to \"event listeners\" registered via\r\n * listen/listenOnce.\r\n *\r\n * The interface allows for an event propagation mechanism similar\r\n * to one offered by native browser event targets, such as\r\n * capture/bubble mechanism, stopping propagation, and preventing\r\n * default actions. Capture/bubble mechanism depends on the ancestor\r\n * tree constructed via `#getParentEventTarget`; this tree\r\n * must be directed acyclic graph. The meaning of default action(s)\r\n * in preventDefault is specific to a particular use case.\r\n *\r\n * Implementations that do not support capture/bubble or can not have\r\n * a parent listenable can simply not implement any ability to set the\r\n * parent listenable (and have `#getParentEventTarget` return\r\n * null).\r\n *\r\n * Implementation of this class can be used with or independently from\r\n * goog.events.\r\n *\r\n * Implementation must call `#addImplementation(implClass)`.\r\n *\r\n * @interface\r\n * @see goog.events\r\n * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html\r\n */\r\ngoog.events.Listenable = function() {};\r\n\r\n\r\n/**\r\n * An expando property to indicate that an object implements\r\n * goog.events.Listenable.\r\n *\r\n * See addImplementation/isImplementedBy.\r\n *\r\n * @type {string}\r\n * @const\r\n */\r\ngoog.events.Listenable.IMPLEMENTED_BY_PROP =\r\n 'closure_listenable_' + ((Math.random() * 1e6) | 0);\r\n\r\n\r\n/**\r\n * Marks a given class (constructor) as an implementation of\r\n * Listenable, so that we can query that fact at runtime. The class\r\n * must have already implemented the interface.\r\n * @param {function(new:goog.events.Listenable,...)} cls The class constructor.\r\n * The corresponding class must have already implemented the interface.\r\n */\r\ngoog.events.Listenable.addImplementation = function(cls) {\r\n cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;\r\n};\r\n\r\n\r\n/**\r\n * @param {Object} obj The object to check.\r\n * @return {boolean} Whether a given instance implements Listenable. The\r\n * class/superclass of the instance must call addImplementation.\r\n */\r\ngoog.events.Listenable.isImplementedBy = function(obj) {\r\n return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener. A listener can only be added once to an\r\n * object and if it is added again the key for the listener is\r\n * returned. Note that if the existing listener is a one-off listener\r\n * (registered via listenOnce), it will no longer be a one-off\r\n * listener after a call to listen().\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\r\n * method.\r\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\r\n * (defaults to false).\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {!goog.events.ListenableKey} Unique key for the listener.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.listen;\r\n\r\n\r\n/**\r\n * Adds an event listener that is removed automatically after the\r\n * listener fired once.\r\n *\r\n * If an existing listener already exists, listenOnce will do\r\n * nothing. In particular, if the listener was previously registered\r\n * via listen(), listenOnce() will not turn the listener into a\r\n * one-off listener. Similarly, if there is already an existing\r\n * one-off listener, listenOnce does not modify the listeners (it is\r\n * still a once listener).\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\r\n * method.\r\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\r\n * (defaults to false).\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {!goog.events.ListenableKey} Unique key for the listener.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.listenOnce;\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen() or listenOnce().\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\r\n * method.\r\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\r\n * (defaults to false).\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\r\n * the listener.\r\n * @return {boolean} Whether any listener was removed.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.unlisten;\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen() by the key\r\n * returned by listen().\r\n *\r\n * @param {!goog.events.ListenableKey} key The key returned by\r\n * listen() or listenOnce().\r\n * @return {boolean} Whether any listener was removed.\r\n */\r\ngoog.events.Listenable.prototype.unlistenByKey;\r\n\r\n\r\n/**\r\n * Dispatches an event (or event like object) and calls all listeners\r\n * listening for events of this type. The type of the event is decided by the\r\n * type property on the event object.\r\n *\r\n * If any of the listeners returns false OR calls preventDefault then this\r\n * function will return false. If one of the capture listeners calls\r\n * stopPropagation, then the bubble listeners won't fire.\r\n *\r\n * @param {goog.events.EventLike} e Event object.\r\n * @return {boolean} If anyone called preventDefault on the event object (or\r\n * if any of the listeners returns false) this will also return false.\r\n */\r\ngoog.events.Listenable.prototype.dispatchEvent;\r\n\r\n\r\n/**\r\n * Removes all listeners from this listenable. If type is specified,\r\n * it will only remove listeners of the particular type. otherwise all\r\n * registered listeners will be removed.\r\n *\r\n * @param {string=} opt_type Type of event to remove, default is to\r\n * remove all types.\r\n * @return {number} Number of listeners removed.\r\n */\r\ngoog.events.Listenable.prototype.removeAllListeners;\r\n\r\n\r\n/**\r\n * Returns the parent of this event target to use for capture/bubble\r\n * mechanism.\r\n *\r\n * NOTE(chrishenry): The name reflects the original implementation of\r\n * custom event target (`goog.events.EventTarget`). We decided\r\n * that changing the name is not worth it.\r\n *\r\n * @return {goog.events.Listenable} The parent EventTarget or null if\r\n * there is no parent.\r\n */\r\ngoog.events.Listenable.prototype.getParentEventTarget;\r\n\r\n\r\n/**\r\n * Fires all registered listeners in this listenable for the given\r\n * type and capture mode, passing them the given eventObject. This\r\n * does not perform actual capture/bubble. Only implementors of the\r\n * interface should be using this.\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\r\n * listeners to fire.\r\n * @param {boolean} capture The capture mode of the listeners to fire.\r\n * @param {EVENTOBJ} eventObject The event object to fire.\r\n * @return {boolean} Whether all listeners succeeded without\r\n * attempting to prevent default behavior. If any listener returns\r\n * false or called goog.events.Event#preventDefault, this returns\r\n * false.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.fireListeners;\r\n\r\n\r\n/**\r\n * Gets all listeners in this listenable for the given type and\r\n * capture mode.\r\n *\r\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\r\n * @param {boolean} capture The capture mode of the listeners to fire.\r\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\r\n * listeners.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.getListeners;\r\n\r\n\r\n/**\r\n * Gets the goog.events.ListenableKey for the event or null if no such\r\n * listener is in use.\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\r\n * without the 'on' prefix.\r\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\r\n * listener function to get.\r\n * @param {boolean} capture Whether the listener is a capturing listener.\r\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {goog.events.ListenableKey} the found listener or null if not found.\r\n * @template SCOPE,EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.getListener;\r\n\r\n\r\n/**\r\n * Whether there is any active listeners matching the specified\r\n * signature. If either the type or capture parameters are\r\n * unspecified, the function will match on the remaining criteria.\r\n *\r\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\r\n * @param {boolean=} opt_capture Whether to check for capture or bubble\r\n * listeners.\r\n * @return {boolean} Whether there is any active listeners matching\r\n * the requested type and/or capture phase.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.Listenable.prototype.hasListener;\r\n\r\n\r\n\r\n/**\r\n * An interface that describes a single registered listener.\r\n * @interface\r\n */\r\ngoog.events.ListenableKey = function() {};\r\n\r\n\r\n/**\r\n * Counter used to create a unique key\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.events.ListenableKey.counter_ = 0;\r\n\r\n\r\n/**\r\n * Reserves a key to be used for ListenableKey#key field.\r\n * @return {number} A number to be used to fill ListenableKey#key\r\n * field.\r\n */\r\ngoog.events.ListenableKey.reserveKey = function() {\r\n return ++goog.events.ListenableKey.counter_;\r\n};\r\n\r\n\r\n/**\r\n * The source event target.\r\n * @type {Object|goog.events.Listenable|goog.events.EventTarget}\r\n */\r\ngoog.events.ListenableKey.prototype.src;\r\n\r\n\r\n/**\r\n * The event type the listener is listening to.\r\n * @type {string}\r\n */\r\ngoog.events.ListenableKey.prototype.type;\r\n\r\n\r\n/**\r\n * The listener function.\r\n * @type {function(?):?|{handleEvent:function(?):?}|null}\r\n */\r\ngoog.events.ListenableKey.prototype.listener;\r\n\r\n\r\n/**\r\n * Whether the listener works on capture phase.\r\n * @type {boolean}\r\n */\r\ngoog.events.ListenableKey.prototype.capture;\r\n\r\n\r\n/**\r\n * The 'this' object for the listener function's scope.\r\n * @type {Object|undefined}\r\n */\r\ngoog.events.ListenableKey.prototype.handler;\r\n\r\n\r\n/**\r\n * A globally unique number to identify the key.\r\n * @type {number}\r\n */\r\ngoog.events.ListenableKey.prototype.key;\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Listener object.\r\n * @see ../demos/events.html\r\n */\r\n\r\ngoog.provide('goog.events.Listener');\r\n\r\ngoog.require('goog.events.ListenableKey');\r\n\r\n\r\n\r\n/**\r\n * Simple class that stores information about a listener\r\n * @param {function(?):?} listener Callback function.\r\n * @param {Function} proxy Wrapper for the listener that patches the event.\r\n * @param {EventTarget|goog.events.Listenable} src Source object for\r\n * the event.\r\n * @param {string} type Event type.\r\n * @param {boolean} capture Whether in capture or bubble phase.\r\n * @param {Object=} opt_handler Object in whose context to execute the callback.\r\n * @implements {goog.events.ListenableKey}\r\n * @constructor\r\n */\r\ngoog.events.Listener = function(\r\n listener, proxy, src, type, capture, opt_handler) {\r\n if (goog.events.Listener.ENABLE_MONITORING) {\r\n this.creationStack = new Error().stack;\r\n }\r\n\r\n /** @override */\r\n this.listener = listener;\r\n\r\n /**\r\n * A wrapper over the original listener. This is used solely to\r\n * handle native browser events (it is used to simulate the capture\r\n * phase and to patch the event object).\r\n * @type {Function}\r\n */\r\n this.proxy = proxy;\r\n\r\n /**\r\n * Object or node that callback is listening to\r\n * @type {EventTarget|goog.events.Listenable}\r\n */\r\n this.src = src;\r\n\r\n /**\r\n * The event type.\r\n * @const {string}\r\n */\r\n this.type = type;\r\n\r\n /**\r\n * Whether the listener is being called in the capture or bubble phase\r\n * @const {boolean}\r\n */\r\n this.capture = !!capture;\r\n\r\n /**\r\n * Optional object whose context to execute the listener in\r\n * @type {Object|undefined}\r\n */\r\n this.handler = opt_handler;\r\n\r\n /**\r\n * The key of the listener.\r\n * @const {number}\r\n * @override\r\n */\r\n this.key = goog.events.ListenableKey.reserveKey();\r\n\r\n /**\r\n * Whether to remove the listener after it has been called.\r\n * @type {boolean}\r\n */\r\n this.callOnce = false;\r\n\r\n /**\r\n * Whether the listener has been removed.\r\n * @type {boolean}\r\n */\r\n this.removed = false;\r\n};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to enable the monitoring of the\r\n * goog.events.Listener instances. Switching on the monitoring is only\r\n * recommended for debugging because it has a significant impact on\r\n * performance and memory usage. If switched off, the monitoring code\r\n * compiles down to 0 bytes.\r\n */\r\ngoog.events.Listener.ENABLE_MONITORING =\r\n goog.define('goog.events.Listener.ENABLE_MONITORING', false);\r\n\r\n\r\n/**\r\n * If monitoring the goog.events.Listener instances is enabled, stores the\r\n * creation stack trace of the Disposable instance.\r\n * @type {string}\r\n */\r\ngoog.events.Listener.prototype.creationStack;\r\n\r\n\r\n/**\r\n * Marks this listener as removed. This also remove references held by\r\n * this listener object (such as listener and event source).\r\n */\r\ngoog.events.Listener.prototype.markAsRemoved = function() {\r\n this.removed = true;\r\n this.listener = null;\r\n this.proxy = null;\r\n this.src = null;\r\n this.handler = null;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A map of listeners that provides utility functions to\r\n * deal with listeners on an event target. Used by\r\n * `goog.events.EventTarget`.\r\n *\r\n * WARNING: Do not use this class from outside goog.events package.\r\n */\r\n\r\ngoog.provide('goog.events.ListenerMap');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.events.Listener');\r\ngoog.require('goog.object');\r\n\r\n\r\n\r\n/**\r\n * Creates a new listener map.\r\n * @param {EventTarget|goog.events.Listenable} src The src object.\r\n * @constructor\r\n * @final\r\n */\r\ngoog.events.ListenerMap = function(src) {\r\n /** @type {EventTarget|goog.events.Listenable} */\r\n this.src = src;\r\n\r\n /**\r\n * Maps of event type to an array of listeners.\r\n * @type {!Object<string, !Array<!goog.events.Listener>>}\r\n */\r\n this.listeners = {};\r\n\r\n /**\r\n * The count of types in this map that have registered listeners.\r\n * @private {number}\r\n */\r\n this.typeCount_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The count of event types in this map that actually\r\n * have registered listeners.\r\n */\r\ngoog.events.ListenerMap.prototype.getTypeCount = function() {\r\n return this.typeCount_;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} Total number of registered listeners.\r\n */\r\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\r\n var count = 0;\r\n for (var type in this.listeners) {\r\n count += this.listeners[type].length;\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener. A listener can only be added once to an\r\n * object and if it is added again the key for the listener is\r\n * returned.\r\n *\r\n * Note that a one-off listener will not change an existing listener,\r\n * if any. On the other hand a normal listener will change existing\r\n * one-off listener to become a normal listener.\r\n *\r\n * @param {string|!goog.events.EventId} type The listener event type.\r\n * @param {!Function} listener This listener callback method.\r\n * @param {boolean} callOnce Whether the listener is a one-off\r\n * listener.\r\n * @param {boolean=} opt_useCapture The capture mode of the listener.\r\n * @param {Object=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {!goog.events.ListenableKey} Unique key for the listener.\r\n */\r\ngoog.events.ListenerMap.prototype.add = function(\r\n type, listener, callOnce, opt_useCapture, opt_listenerScope) {\r\n var typeStr = type.toString();\r\n var listenerArray = this.listeners[typeStr];\r\n if (!listenerArray) {\r\n listenerArray = this.listeners[typeStr] = [];\r\n this.typeCount_++;\r\n }\r\n\r\n var listenerObj;\r\n var index = goog.events.ListenerMap.findListenerIndex_(\r\n listenerArray, listener, opt_useCapture, opt_listenerScope);\r\n if (index > -1) {\r\n listenerObj = listenerArray[index];\r\n if (!callOnce) {\r\n // Ensure that, if there is an existing callOnce listener, it is no\r\n // longer a callOnce listener.\r\n listenerObj.callOnce = false;\r\n }\r\n } else {\r\n listenerObj = new goog.events.Listener(\r\n listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);\r\n listenerObj.callOnce = callOnce;\r\n listenerArray.push(listenerObj);\r\n }\r\n return listenerObj;\r\n};\r\n\r\n\r\n/**\r\n * Removes a matching listener.\r\n * @param {string|!goog.events.EventId} type The listener event type.\r\n * @param {!Function} listener This listener callback method.\r\n * @param {boolean=} opt_useCapture The capture mode of the listener.\r\n * @param {Object=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {boolean} Whether any listener was removed.\r\n */\r\ngoog.events.ListenerMap.prototype.remove = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n var typeStr = type.toString();\r\n if (!(typeStr in this.listeners)) {\r\n return false;\r\n }\r\n\r\n var listenerArray = this.listeners[typeStr];\r\n var index = goog.events.ListenerMap.findListenerIndex_(\r\n listenerArray, listener, opt_useCapture, opt_listenerScope);\r\n if (index > -1) {\r\n var listenerObj = listenerArray[index];\r\n listenerObj.markAsRemoved();\r\n goog.array.removeAt(listenerArray, index);\r\n if (listenerArray.length == 0) {\r\n delete this.listeners[typeStr];\r\n this.typeCount_--;\r\n }\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes the given listener object.\r\n * @param {!goog.events.ListenableKey} listener The listener to remove.\r\n * @return {boolean} Whether the listener is removed.\r\n */\r\ngoog.events.ListenerMap.prototype.removeByKey = function(listener) {\r\n var type = listener.type;\r\n if (!(type in this.listeners)) {\r\n return false;\r\n }\r\n\r\n var removed = goog.array.remove(this.listeners[type], listener);\r\n if (removed) {\r\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\r\n if (this.listeners[type].length == 0) {\r\n delete this.listeners[type];\r\n this.typeCount_--;\r\n }\r\n }\r\n return removed;\r\n};\r\n\r\n\r\n/**\r\n * Removes all listeners from this map. If opt_type is provided, only\r\n * listeners that match the given type are removed.\r\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\r\n * @return {number} Number of listeners removed.\r\n */\r\ngoog.events.ListenerMap.prototype.removeAll = function(opt_type) {\r\n var typeStr = opt_type && opt_type.toString();\r\n var count = 0;\r\n for (var type in this.listeners) {\r\n if (!typeStr || type == typeStr) {\r\n var listenerArray = this.listeners[type];\r\n for (var i = 0; i < listenerArray.length; i++) {\r\n ++count;\r\n listenerArray[i].markAsRemoved();\r\n }\r\n delete this.listeners[type];\r\n this.typeCount_--;\r\n }\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Gets all listeners that match the given type and capture mode. The\r\n * returned array is a copy (but the listener objects are not).\r\n * @param {string|!goog.events.EventId} type The type of the listeners\r\n * to retrieve.\r\n * @param {boolean} capture The capture mode of the listeners to retrieve.\r\n * @return {!Array<!goog.events.ListenableKey>} An array of matching\r\n * listeners.\r\n */\r\ngoog.events.ListenerMap.prototype.getListeners = function(type, capture) {\r\n var listenerArray = this.listeners[type.toString()];\r\n var rv = [];\r\n if (listenerArray) {\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n var listenerObj = listenerArray[i];\r\n if (listenerObj.capture == capture) {\r\n rv.push(listenerObj);\r\n }\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Gets the goog.events.ListenableKey for the event or null if no such\r\n * listener is in use.\r\n *\r\n * @param {string|!goog.events.EventId} type The type of the listener\r\n * to retrieve.\r\n * @param {!Function} listener The listener function to get.\r\n * @param {boolean} capture Whether the listener is a capturing listener.\r\n * @param {Object=} opt_listenerScope Object in whose scope to call the\r\n * listener.\r\n * @return {goog.events.ListenableKey} the found listener or null if not found.\r\n */\r\ngoog.events.ListenerMap.prototype.getListener = function(\r\n type, listener, capture, opt_listenerScope) {\r\n var listenerArray = this.listeners[type.toString()];\r\n var i = -1;\r\n if (listenerArray) {\r\n i = goog.events.ListenerMap.findListenerIndex_(\r\n listenerArray, listener, capture, opt_listenerScope);\r\n }\r\n return i > -1 ? listenerArray[i] : null;\r\n};\r\n\r\n\r\n/**\r\n * Whether there is a matching listener. If either the type or capture\r\n * parameters are unspecified, the function will match on the\r\n * remaining criteria.\r\n *\r\n * @param {string|!goog.events.EventId=} opt_type The type of the listener.\r\n * @param {boolean=} opt_capture The capture mode of the listener.\r\n * @return {boolean} Whether there is an active listener matching\r\n * the requested type and/or capture phase.\r\n */\r\ngoog.events.ListenerMap.prototype.hasListener = function(\r\n opt_type, opt_capture) {\r\n var hasType = goog.isDef(opt_type);\r\n var typeStr = hasType ? opt_type.toString() : '';\r\n var hasCapture = goog.isDef(opt_capture);\r\n\r\n return goog.object.some(this.listeners, function(listenerArray, type) {\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n if ((!hasType || listenerArray[i].type == typeStr) &&\r\n (!hasCapture || listenerArray[i].capture == opt_capture)) {\r\n return true;\r\n }\r\n }\r\n\r\n return false;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Finds the index of a matching goog.events.Listener in the given\r\n * listenerArray.\r\n * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.\r\n * @param {!Function} listener The listener function.\r\n * @param {boolean=} opt_useCapture The capture flag for the listener.\r\n * @param {Object=} opt_listenerScope The listener scope.\r\n * @return {number} The index of the matching listener within the\r\n * listenerArray.\r\n * @private\r\n */\r\ngoog.events.ListenerMap.findListenerIndex_ = function(\r\n listenerArray, listener, opt_useCapture, opt_listenerScope) {\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n var listenerObj = listenerArray[i];\r\n if (!listenerObj.removed && listenerObj.listener == listener &&\r\n listenerObj.capture == !!opt_useCapture &&\r\n listenerObj.handler == opt_listenerScope) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n};\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview An event manager for both native browser event\r\n * targets and custom JavaScript event targets\r\n * (`goog.events.Listenable`). This provides an abstraction\r\n * over browsers' event systems.\r\n *\r\n * It also provides a simulation of W3C event model's capture phase in\r\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\r\n * interact well with listeners registered directly on the elements\r\n * (bypassing goog.events) or even with listeners registered via\r\n * goog.events in a separate JS binary. In these cases, we provide\r\n * no ordering guarantees.\r\n *\r\n * The listeners will receive a \"patched\" event object. Such event object\r\n * contains normalized values for certain event properties that differs in\r\n * different browsers.\r\n *\r\n * Example usage:\r\n * <pre>\r\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\r\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\r\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\r\n * goog.events.removeAll(myNode);\r\n * </pre>\r\n *\r\n * in IE and event object patching]\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * @see ../demos/events.html\r\n * @see ../demos/event-propagation.html\r\n * @see ../demos/stopevent.html\r\n */\r\n\r\n// IMPLEMENTATION NOTES:\r\n// goog.events stores an auxiliary data structure on each EventTarget\r\n// source being listened on. This allows us to take advantage of GC,\r\n// having the data structure GC'd when the EventTarget is GC'd. This\r\n// GC behavior is equivalent to using W3C DOM Events directly.\r\n\r\ngoog.provide('goog.events');\r\ngoog.provide('goog.events.CaptureSimulationMode');\r\ngoog.provide('goog.events.Key');\r\ngoog.provide('goog.events.ListenableType');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.debug.entryPointRegistry');\r\ngoog.require('goog.events.BrowserEvent');\r\ngoog.require('goog.events.BrowserFeature');\r\ngoog.require('goog.events.Listenable');\r\ngoog.require('goog.events.ListenerMap');\r\n\r\ngoog.forwardDeclare('goog.debug.ErrorHandler');\r\ngoog.forwardDeclare('goog.events.EventWrapper');\r\n\r\n\r\n/**\r\n * @typedef {number|goog.events.ListenableKey}\r\n */\r\ngoog.events.Key;\r\n\r\n\r\n/**\r\n * @typedef {EventTarget|goog.events.Listenable}\r\n */\r\ngoog.events.ListenableType;\r\n\r\n\r\n/**\r\n * Property name on a native event target for the listener map\r\n * associated with the event target.\r\n * @private @const {string}\r\n */\r\ngoog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);\r\n\r\n\r\n/**\r\n * String used to prepend to IE event types.\r\n * @const\r\n * @private\r\n */\r\ngoog.events.onString_ = 'on';\r\n\r\n\r\n/**\r\n * Map of computed \"on<eventname>\" strings for IE event types. Caching\r\n * this removes an extra object allocation in goog.events.listen which\r\n * improves IE6 performance.\r\n * @const\r\n * @dict\r\n * @private\r\n */\r\ngoog.events.onStringMap_ = {};\r\n\r\n\r\n/**\r\n * @enum {number} Different capture simulation mode for IE8-.\r\n */\r\ngoog.events.CaptureSimulationMode = {\r\n /**\r\n * Does not perform capture simulation. Will asserts in IE8- when you\r\n * add capture listeners.\r\n */\r\n OFF_AND_FAIL: 0,\r\n\r\n /**\r\n * Does not perform capture simulation, silently ignore capture\r\n * listeners.\r\n */\r\n OFF_AND_SILENT: 1,\r\n\r\n /**\r\n * Performs capture simulation.\r\n */\r\n ON: 2\r\n};\r\n\r\n\r\n/**\r\n * @define {number} The capture simulation mode for IE8-. By default,\r\n * this is ON.\r\n */\r\ngoog.events.CAPTURE_SIMULATION_MODE =\r\n goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);\r\n\r\n\r\n/**\r\n * Estimated count of total native listeners.\r\n * @private {number}\r\n */\r\ngoog.events.listenerCountEstimate_ = 0;\r\n\r\n\r\n/**\r\n * Adds an event listener for a specific event on a native event\r\n * target (such as a DOM element) or an object that has implemented\r\n * {@link goog.events.Listenable}. A listener can only be added once\r\n * to an object and if it is added again the key for the listener is\r\n * returned. Note that if the existing listener is a one-off listener\r\n * (registered via listenOnce), it will no longer be a one-off\r\n * listener after a call to listen().\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The node to listen\r\n * to events on.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\r\n * listener Callback method, or an object with a handleEvent function.\r\n * WARNING: passing an Object is now softly deprecated.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {T=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.Key} Unique key for the listener.\r\n * @template T,EVENTOBJ\r\n */\r\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\r\n if (opt_options && opt_options.once) {\r\n return goog.events.listenOnce(\r\n src, type, listener, opt_options, opt_handler);\r\n }\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\r\n }\r\n return null;\r\n }\r\n\r\n listener = goog.events.wrapListener(listener);\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n return src.listen(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n } else {\r\n return goog.events.listen_(\r\n /** @type {!EventTarget} */ (src), type, listener,\r\n /* callOnce */ false, opt_options, opt_handler);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener for a specific event on a native event\r\n * target. A listener can only be added once to an object and if it\r\n * is added again the key for the listener is returned.\r\n *\r\n * Note that a one-off listener will not change an existing listener,\r\n * if any. On the other hand a normal listener will change existing\r\n * one-off listener to become a normal listener.\r\n *\r\n * @param {EventTarget} src The node to listen to events on.\r\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\r\n * @param {!Function} listener Callback function.\r\n * @param {boolean} callOnce Whether the listener is a one-off\r\n * listener or otherwise.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.ListenableKey} Unique key for the listener.\r\n * @template EVENTOBJ\r\n * @private\r\n */\r\ngoog.events.listen_ = function(\r\n src, type, listener, callOnce, opt_options, opt_handler) {\r\n if (!type) {\r\n throw new Error('Invalid event type');\r\n }\r\n\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n if (capture && !goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {\r\n if (goog.events.CAPTURE_SIMULATION_MODE ==\r\n goog.events.CaptureSimulationMode.OFF_AND_FAIL) {\r\n goog.asserts.fail('Can not register capture listener in IE8-.');\r\n return null;\r\n } else if (\r\n goog.events.CAPTURE_SIMULATION_MODE ==\r\n goog.events.CaptureSimulationMode.OFF_AND_SILENT) {\r\n return null;\r\n }\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(src);\r\n if (!listenerMap) {\r\n src[goog.events.LISTENER_MAP_PROP_] = listenerMap =\r\n new goog.events.ListenerMap(src);\r\n }\r\n\r\n var listenerObj = /** @type {goog.events.Listener} */ (\r\n listenerMap.add(type, listener, callOnce, capture, opt_handler));\r\n\r\n // If the listenerObj already has a proxy, it has been set up\r\n // previously. We simply return.\r\n if (listenerObj.proxy) {\r\n return listenerObj;\r\n }\r\n\r\n var proxy = goog.events.getProxy();\r\n listenerObj.proxy = proxy;\r\n\r\n proxy.src = src;\r\n proxy.listener = listenerObj;\r\n\r\n // Attach the proxy through the browser's API\r\n if (src.addEventListener) {\r\n // Don't pass an object as `capture` if the browser doesn't support that.\r\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\r\n opt_options = capture;\r\n }\r\n // Don't break tests that expect a boolean.\r\n if (opt_options === undefined) opt_options = false;\r\n src.addEventListener(type.toString(), proxy, opt_options);\r\n } else if (src.attachEvent) {\r\n // The else if above used to be an unconditional else. It would call\r\n // exception on IE11, spoiling the day of some callers. The previous\r\n // incarnation of this code, from 2007, indicates that it replaced an\r\n // earlier still version that caused excess allocations on IE6.\r\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\r\n } else if (src.addListener && src.removeListener) {\r\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\r\n // Safari, there is no global for the MediaQueryList constructor, so we just\r\n // check whether the object \"looks like\" MediaQueryList.\r\n goog.asserts.assert(\r\n type === 'change', 'MediaQueryList only has a change event');\r\n src.addListener(proxy);\r\n } else {\r\n throw new Error('addEventListener and attachEvent are unavailable.');\r\n }\r\n\r\n goog.events.listenerCountEstimate_++;\r\n return listenerObj;\r\n};\r\n\r\n\r\n/**\r\n * Helper function for returning a proxy function.\r\n * @return {!Function} A new or reused function object.\r\n */\r\ngoog.events.getProxy = function() {\r\n var proxyCallbackFunction = goog.events.handleBrowserEvent_;\r\n // Use a local var f to prevent one allocation.\r\n var f =\r\n goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT ? function(eventObject) {\r\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\r\n } : function(eventObject) {\r\n var v = proxyCallbackFunction.call(f.src, f.listener, eventObject);\r\n // NOTE(chrishenry): In IE, we hack in a capture phase. However, if\r\n // there is inline event handler which tries to prevent default (for\r\n // example <a href=\"...\" onclick=\"return false\">...</a>) in a\r\n // descendant element, the prevent default will be overridden\r\n // by this listener if this listener were to return true. Hence, we\r\n // return undefined.\r\n if (!v) return v;\r\n };\r\n return f;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener for a specific event on a native event\r\n * target (such as a DOM element) or an object that has implemented\r\n * {@link goog.events.Listenable}. After the event has fired the event\r\n * listener is removed from the target.\r\n *\r\n * If an existing listener already exists, listenOnce will do\r\n * nothing. In particular, if the listener was previously registered\r\n * via listen(), listenOnce() will not turn the listener into a\r\n * one-off listener. Similarly, if there is already an existing\r\n * one-off listener, listenOnce does not modify the listeners (it is\r\n * still a once listener).\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The node to listen\r\n * to events on.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\r\n * listener Callback method.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {T=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.Key} Unique key for the listener.\r\n * @template T,EVENTOBJ\r\n */\r\ngoog.events.listenOnce = function(\r\n src, type, listener, opt_options, opt_handler) {\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\r\n }\r\n return null;\r\n }\r\n\r\n listener = goog.events.wrapListener(listener);\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n return src.listenOnce(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n } else {\r\n return goog.events.listen_(\r\n /** @type {!EventTarget} */ (src), type, listener,\r\n /* callOnce */ true, opt_options, opt_handler);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.Listenable}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target to\r\n * listen to events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\r\n * Callback method, or an object with a handleEvent function.\r\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\r\n * false).\r\n * @param {T=} opt_handler Element in whose scope to call the listener.\r\n * @template T\r\n */\r\ngoog.events.listenWithWrapper = function(\r\n src, wrapper, listener, opt_capt, opt_handler) {\r\n wrapper.listen(src, listener, opt_capt, opt_handler);\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen().\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target to stop\r\n * listening to events on.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types to unlisten to.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to remove.\r\n * @param {(boolean|!EventListenerOptions)=} opt_options\r\n * whether the listener is fired during the capture or bubble phase of the\r\n * event.\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n * @return {?boolean} indicating whether the listener was there to remove.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\r\n }\r\n return null;\r\n }\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n\r\n listener = goog.events.wrapListener(listener);\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n return src.unlisten(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n }\r\n\r\n if (!src) {\r\n // TODO(chrishenry): We should tighten the API to only accept\r\n // non-null objects, or add an assertion here.\r\n return false;\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (src));\r\n if (listenerMap) {\r\n var listenerObj = listenerMap.getListener(\r\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\r\n opt_handler);\r\n if (listenerObj) {\r\n return goog.events.unlistenByKey(listenerObj);\r\n }\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listen() by the key\r\n * returned by listen().\r\n *\r\n * @param {goog.events.Key} key The key returned by listen() for this\r\n * event listener.\r\n * @return {boolean} indicating whether the listener was there to remove.\r\n */\r\ngoog.events.unlistenByKey = function(key) {\r\n // TODO(chrishenry): Remove this check when tests that rely on this\r\n // are fixed.\r\n if (goog.isNumber(key)) {\r\n return false;\r\n }\r\n\r\n var listener = key;\r\n if (!listener || listener.removed) {\r\n return false;\r\n }\r\n\r\n var src = listener.src;\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\r\n }\r\n\r\n var type = listener.type;\r\n var proxy = listener.proxy;\r\n if (src.removeEventListener) {\r\n src.removeEventListener(type, proxy, listener.capture);\r\n } else if (src.detachEvent) {\r\n src.detachEvent(goog.events.getOnString_(type), proxy);\r\n } else if (src.addListener && src.removeListener) {\r\n src.removeListener(proxy);\r\n }\r\n goog.events.listenerCountEstimate_--;\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (src));\r\n // TODO(chrishenry): Try to remove this conditional and execute the\r\n // first branch always. This should be safe.\r\n if (listenerMap) {\r\n listenerMap.removeByKey(listener);\r\n if (listenerMap.getTypeCount() == 0) {\r\n // Null the src, just because this is simple to do (and useful\r\n // for IE <= 7).\r\n listenerMap.src = null;\r\n // We don't use delete here because IE does not allow delete\r\n // on a window object.\r\n src[goog.events.LISTENER_MAP_PROP_] = null;\r\n }\r\n } else {\r\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\r\n }\r\n\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listenWithWrapper().\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target to stop\r\n * listening to events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to remove.\r\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase of the\r\n * event.\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n */\r\ngoog.events.unlistenWithWrapper = function(\r\n src, wrapper, listener, opt_capt, opt_handler) {\r\n wrapper.unlisten(src, listener, opt_capt, opt_handler);\r\n};\r\n\r\n\r\n/**\r\n * Removes all listeners from an object. You can also optionally\r\n * remove listeners of a particular type.\r\n *\r\n * @param {Object|undefined} obj Object to remove listeners from. Must be an\r\n * EventTarget or a goog.events.Listenable.\r\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\r\n * Default is all types.\r\n * @return {number} Number of listeners removed.\r\n */\r\ngoog.events.removeAll = function(obj, opt_type) {\r\n // TODO(chrishenry): Change the type of obj to\r\n // (!EventTarget|!goog.events.Listenable).\r\n\r\n if (!obj) {\r\n return 0;\r\n }\r\n\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return /** @type {?} */ (obj).removeAllListeners(opt_type);\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (obj));\r\n if (!listenerMap) {\r\n return 0;\r\n }\r\n\r\n var count = 0;\r\n var typeStr = opt_type && opt_type.toString();\r\n for (var type in listenerMap.listeners) {\r\n if (!typeStr || type == typeStr) {\r\n // Clone so that we don't need to worry about unlistenByKey\r\n // changing the content of the ListenerMap.\r\n var listeners = listenerMap.listeners[type].concat();\r\n for (var i = 0; i < listeners.length; ++i) {\r\n if (goog.events.unlistenByKey(listeners[i])) {\r\n ++count;\r\n }\r\n }\r\n }\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Gets the listeners for a given object, type and capture phase.\r\n *\r\n * @param {Object} obj Object to get listeners for.\r\n * @param {string|!goog.events.EventId} type Event type.\r\n * @param {boolean} capture Capture phase?.\r\n * @return {Array<!goog.events.Listener>} Array of listener objects.\r\n */\r\ngoog.events.getListeners = function(obj, type, capture) {\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return /** @type {!goog.events.Listenable} */ (obj).getListeners(\r\n type, capture);\r\n } else {\r\n if (!obj) {\r\n // TODO(chrishenry): We should tighten the API to accept\r\n // !EventTarget|goog.events.Listenable, and add an assertion here.\r\n return [];\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (obj));\r\n return listenerMap ? listenerMap.getListeners(type, capture) : [];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Gets the goog.events.Listener for the event or null if no such listener is\r\n * in use.\r\n *\r\n * @param {EventTarget|goog.events.Listenable} src The target from\r\n * which to get listeners.\r\n * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.\r\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to get.\r\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the\r\n * capture or bubble phase of the event.\r\n * @param {Object=} opt_handler Element in whose scope to call the listener.\r\n * @return {goog.events.ListenableKey} the found listener or null if not found.\r\n * @template EVENTOBJ\r\n */\r\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\r\n // TODO(chrishenry): Change type from ?string to string, or add assertion.\r\n type = /** @type {string} */ (type);\r\n listener = goog.events.wrapListener(listener);\r\n var capture = !!opt_capt;\r\n if (goog.events.Listenable.isImplementedBy(src)) {\r\n return src.getListener(type, listener, capture, opt_handler);\r\n }\r\n\r\n if (!src) {\r\n // TODO(chrishenry): We should tighten the API to only accept\r\n // non-null objects, or add an assertion here.\r\n return null;\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (src));\r\n if (listenerMap) {\r\n return listenerMap.getListener(type, listener, capture, opt_handler);\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether an event target has any active listeners matching the\r\n * specified signature. If either the type or capture parameters are\r\n * unspecified, the function will match on the remaining criteria.\r\n *\r\n * @param {EventTarget|goog.events.Listenable} obj Target to get\r\n * listeners for.\r\n * @param {string|!goog.events.EventId=} opt_type Event type.\r\n * @param {boolean=} opt_capture Whether to check for capture or bubble-phase\r\n * listeners.\r\n * @return {boolean} Whether an event target has one or more listeners matching\r\n * the requested type and/or capture phase.\r\n */\r\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return obj.hasListener(opt_type, opt_capture);\r\n }\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {!EventTarget} */ (obj));\r\n return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);\r\n};\r\n\r\n\r\n/**\r\n * Provides a nice string showing the normalized event objects public members\r\n * @param {Object} e Event Object.\r\n * @return {string} String of the public members of the normalized event object.\r\n */\r\ngoog.events.expose = function(e) {\r\n var str = [];\r\n for (var key in e) {\r\n if (e[key] && e[key].id) {\r\n str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');\r\n } else {\r\n str.push(key + ' = ' + e[key]);\r\n }\r\n }\r\n return str.join('\\n');\r\n};\r\n\r\n\r\n/**\r\n * Returns a string with on prepended to the specified type. This is used for IE\r\n * which expects \"on\" to be prepended. This function caches the string in order\r\n * to avoid extra allocations in steady state.\r\n * @param {string} type Event type.\r\n * @return {string} The type string with 'on' prepended.\r\n * @private\r\n */\r\ngoog.events.getOnString_ = function(type) {\r\n if (type in goog.events.onStringMap_) {\r\n return goog.events.onStringMap_[type];\r\n }\r\n return goog.events.onStringMap_[type] = goog.events.onString_ + type;\r\n};\r\n\r\n\r\n/**\r\n * Fires an object's listeners of a particular type and phase\r\n *\r\n * @param {Object} obj Object whose listeners to call.\r\n * @param {string|!goog.events.EventId} type Event type.\r\n * @param {boolean} capture Which event phase.\r\n * @param {Object} eventObject Event object to be passed to listener.\r\n * @return {boolean} True if all listeners returned true else false.\r\n */\r\ngoog.events.fireListeners = function(obj, type, capture, eventObject) {\r\n if (goog.events.Listenable.isImplementedBy(obj)) {\r\n return /** @type {!goog.events.Listenable} */ (obj).fireListeners(\r\n type, capture, eventObject);\r\n }\r\n\r\n return goog.events.fireListeners_(obj, type, capture, eventObject);\r\n};\r\n\r\n\r\n/**\r\n * Fires an object's listeners of a particular type and phase.\r\n * @param {Object} obj Object whose listeners to call.\r\n * @param {string|!goog.events.EventId} type Event type.\r\n * @param {boolean} capture Which event phase.\r\n * @param {Object} eventObject Event object to be passed to listener.\r\n * @return {boolean} True if all listeners returned true else false.\r\n * @private\r\n */\r\ngoog.events.fireListeners_ = function(obj, type, capture, eventObject) {\r\n /** @type {boolean} */\r\n var retval = true;\r\n\r\n var listenerMap = goog.events.getListenerMap_(\r\n /** @type {EventTarget} */ (obj));\r\n if (listenerMap) {\r\n // TODO(chrishenry): Original code avoids array creation when there\r\n // is no listener, so we do the same. If this optimization turns\r\n // out to be not required, we can replace this with\r\n // listenerMap.getListeners(type, capture) instead, which is simpler.\r\n var listenerArray = listenerMap.listeners[type.toString()];\r\n if (listenerArray) {\r\n listenerArray = listenerArray.concat();\r\n for (var i = 0; i < listenerArray.length; i++) {\r\n var listener = listenerArray[i];\r\n // We might not have a listener if the listener was removed.\r\n if (listener && listener.capture == capture && !listener.removed) {\r\n var result = goog.events.fireListener(listener, eventObject);\r\n retval = retval && (result !== false);\r\n }\r\n }\r\n }\r\n }\r\n return retval;\r\n};\r\n\r\n\r\n/**\r\n * Fires a listener with a set of arguments\r\n *\r\n * @param {goog.events.Listener} listener The listener object to call.\r\n * @param {Object} eventObject The event object to pass to the listener.\r\n * @return {*} Result of listener.\r\n */\r\ngoog.events.fireListener = function(listener, eventObject) {\r\n var listenerFn = listener.listener;\r\n var listenerHandler = listener.handler || listener.src;\r\n\r\n if (listener.callOnce) {\r\n goog.events.unlistenByKey(listener);\r\n }\r\n return listenerFn.call(listenerHandler, eventObject);\r\n};\r\n\r\n\r\n/**\r\n * Gets the total number of listeners currently in the system.\r\n * @return {number} Number of listeners.\r\n * @deprecated This returns estimated count, now that Closure no longer\r\n * stores a central listener registry. We still return an estimation\r\n * to keep existing listener-related tests passing. In the near future,\r\n * this function will be removed.\r\n */\r\ngoog.events.getTotalListenerCount = function() {\r\n return goog.events.listenerCountEstimate_;\r\n};\r\n\r\n\r\n/**\r\n * Dispatches an event (or event like object) and calls all listeners\r\n * listening for events of this type. The type of the event is decided by the\r\n * type property on the event object.\r\n *\r\n * If any of the listeners returns false OR calls preventDefault then this\r\n * function will return false. If one of the capture listeners calls\r\n * stopPropagation, then the bubble listeners won't fire.\r\n *\r\n * @param {goog.events.Listenable} src The event target.\r\n * @param {goog.events.EventLike} e Event object.\r\n * @return {boolean} If anyone called preventDefault on the event object (or\r\n * if any of the handlers returns false) this will also return false.\r\n * If there are no handlers, or if all handlers return true, this returns\r\n * true.\r\n */\r\ngoog.events.dispatchEvent = function(src, e) {\r\n goog.asserts.assert(\r\n goog.events.Listenable.isImplementedBy(src),\r\n 'Can not use goog.events.dispatchEvent with ' +\r\n 'non-goog.events.Listenable instance.');\r\n return src.dispatchEvent(e);\r\n};\r\n\r\n\r\n/**\r\n * Installs exception protection for the browser event entry point using the\r\n * given error handler.\r\n *\r\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\r\n * protect the entry point.\r\n */\r\ngoog.events.protectBrowserEventEntryPoint = function(errorHandler) {\r\n goog.events.handleBrowserEvent_ =\r\n errorHandler.protectEntryPoint(goog.events.handleBrowserEvent_);\r\n};\r\n\r\n\r\n/**\r\n * Handles an event and dispatches it to the correct listeners. This\r\n * function is a proxy for the real listener the user specified.\r\n *\r\n * @param {goog.events.Listener} listener The listener object.\r\n * @param {Event=} opt_evt Optional event object that gets passed in via the\r\n * native event handlers.\r\n * @return {*} Result of the event handler.\r\n * @this {EventTarget} The object or Element that fired the event.\r\n * @private\r\n */\r\ngoog.events.handleBrowserEvent_ = function(listener, opt_evt) {\r\n if (listener.removed) {\r\n return true;\r\n }\r\n\r\n // Synthesize event propagation if the browser does not support W3C\r\n // event model.\r\n if (!goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT) {\r\n var ieEvent = opt_evt ||\r\n /** @type {Event} */ (goog.getObjectByName('window.event'));\r\n var evt = new goog.events.BrowserEvent(ieEvent, this);\r\n /** @type {*} */\r\n var retval = true;\r\n\r\n if (goog.events.CAPTURE_SIMULATION_MODE ==\r\n goog.events.CaptureSimulationMode.ON) {\r\n // If we have not marked this event yet, we should perform capture\r\n // simulation.\r\n if (!goog.events.isMarkedIeEvent_(ieEvent)) {\r\n goog.events.markIeEvent_(ieEvent);\r\n\r\n var ancestors = [];\r\n for (var parent = evt.currentTarget; parent;\r\n parent = parent.parentNode) {\r\n ancestors.push(parent);\r\n }\r\n\r\n // Fire capture listeners.\r\n var type = listener.type;\r\n for (var i = ancestors.length - 1; !evt.propagationStopped_ && i >= 0;\r\n i--) {\r\n evt.currentTarget = ancestors[i];\r\n var result =\r\n goog.events.fireListeners_(ancestors[i], type, true, evt);\r\n retval = retval && result;\r\n }\r\n\r\n // Fire bubble listeners.\r\n //\r\n // We can technically rely on IE to perform bubble event\r\n // propagation. However, it turns out that IE fires events in\r\n // opposite order of attachEvent registration, which broke\r\n // some code and tests that rely on the order. (While W3C DOM\r\n // Level 2 Events TR leaves the event ordering unspecified,\r\n // modern browsers and W3C DOM Level 3 Events Working Draft\r\n // actually specify the order as the registration order.)\r\n for (var i = 0; !evt.propagationStopped_ && i < ancestors.length; i++) {\r\n evt.currentTarget = ancestors[i];\r\n var result =\r\n goog.events.fireListeners_(ancestors[i], type, false, evt);\r\n retval = retval && result;\r\n }\r\n }\r\n } else {\r\n retval = goog.events.fireListener(listener, evt);\r\n }\r\n return retval;\r\n }\r\n\r\n // Otherwise, simply fire the listener.\r\n return goog.events.fireListener(\r\n listener, new goog.events.BrowserEvent(opt_evt, this));\r\n};\r\n\r\n\r\n/**\r\n * This is used to mark the IE event object so we do not do the Closure pass\r\n * twice for a bubbling event.\r\n * @param {Event} e The IE browser event.\r\n * @private\r\n */\r\ngoog.events.markIeEvent_ = function(e) {\r\n // Only the keyCode and the returnValue can be changed. We use keyCode for\r\n // non keyboard events.\r\n // event.returnValue is a bit more tricky. It is undefined by default. A\r\n // boolean false prevents the default action. In a window.onbeforeunload and\r\n // the returnValue is non undefined it will be alerted. However, we will only\r\n // modify the returnValue for keyboard events. We can get a problem if non\r\n // closure events sets the keyCode or the returnValue\r\n\r\n var useReturnValue = false;\r\n\r\n if (e.keyCode == 0) {\r\n // We cannot change the keyCode in case that srcElement is input[type=file].\r\n // We could test that that is the case but that would allocate 3 objects.\r\n // If we use try/catch we will only allocate extra objects in the case of a\r\n // failure.\r\n\r\n try {\r\n e.keyCode = -1;\r\n return;\r\n } catch (ex) {\r\n useReturnValue = true;\r\n }\r\n }\r\n\r\n if (useReturnValue ||\r\n /** @type {boolean|undefined} */ (e.returnValue) == undefined) {\r\n e.returnValue = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * This is used to check if an IE event has already been handled by the Closure\r\n * system so we do not do the Closure pass twice for a bubbling event.\r\n * @param {Event} e The IE browser event.\r\n * @return {boolean} True if the event object has been marked.\r\n * @private\r\n */\r\ngoog.events.isMarkedIeEvent_ = function(e) {\r\n return e.keyCode < 0 || e.returnValue != undefined;\r\n};\r\n\r\n\r\n/**\r\n * Counter to create unique event ids.\r\n * @private {number}\r\n */\r\ngoog.events.uniqueIdCounter_ = 0;\r\n\r\n\r\n/**\r\n * Creates a unique event id.\r\n *\r\n * @param {string} identifier The identifier.\r\n * @return {string} A unique identifier.\r\n * @idGenerator {unique}\r\n */\r\ngoog.events.getUniqueId = function(identifier) {\r\n return identifier + '_' + goog.events.uniqueIdCounter_++;\r\n};\r\n\r\n\r\n/**\r\n * @param {EventTarget} src The source object.\r\n * @return {goog.events.ListenerMap} A listener map for the given\r\n * source object, or null if none exists.\r\n * @private\r\n */\r\ngoog.events.getListenerMap_ = function(src) {\r\n var listenerMap = src[goog.events.LISTENER_MAP_PROP_];\r\n // IE serializes the property as well (e.g. when serializing outer\r\n // HTML). So we must check that the value is of the correct type.\r\n return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;\r\n};\r\n\r\n\r\n/**\r\n * Expando property for listener function wrapper for Object with\r\n * handleEvent.\r\n * @private @const {string}\r\n */\r\ngoog.events.LISTENER_WRAPPER_PROP_ =\r\n '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0);\r\n\r\n\r\n/**\r\n * @param {Object|Function} listener The listener function or an\r\n * object that contains handleEvent method.\r\n * @return {!Function} Either the original function or a function that\r\n * calls obj.handleEvent. If the same listener is passed to this\r\n * function more than once, the same function is guaranteed to be\r\n * returned.\r\n */\r\ngoog.events.wrapListener = function(listener) {\r\n goog.asserts.assert(listener, 'Listener can not be null.');\r\n\r\n if (goog.isFunction(listener)) {\r\n return listener;\r\n }\r\n\r\n goog.asserts.assert(\r\n listener.handleEvent, 'An object listener must have handleEvent method.');\r\n if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {\r\n listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) {\r\n return /** @type {?} */ (listener).handleEvent(e);\r\n };\r\n }\r\n return listener[goog.events.LISTENER_WRAPPER_PROP_];\r\n};\r\n\r\n\r\n// Register the browser event handler as an entry point, so that\r\n// it can be monitored for exception handling, etc.\r\ngoog.debug.entryPointRegistry.register(\r\n /**\r\n * @param {function(!Function): !Function} transformer The transforming\r\n * function.\r\n */\r\n function(transformer) {\r\n goog.events.handleBrowserEvent_ =\r\n transformer(goog.events.handleBrowserEvent_);\r\n });\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A disposable implementation of a custom\r\n * listenable/event target. See also: documentation for\r\n * `goog.events.Listenable`.\r\n *\r\n * @author arv@google.com (Erik Arvidsson) [Original implementation]\r\n * @see ../demos/eventtarget.html\r\n * @see goog.events.Listenable\r\n */\r\n\r\ngoog.provide('goog.events.EventTarget');\r\n\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.events');\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.Listenable');\r\ngoog.require('goog.events.ListenerMap');\r\ngoog.require('goog.object');\r\n\r\n\r\n\r\n/**\r\n * An implementation of `goog.events.Listenable` with full W3C\r\n * EventTarget-like support (capture/bubble mechanism, stopping event\r\n * propagation, preventing default actions).\r\n *\r\n * You may subclass this class to turn your class into a Listenable.\r\n *\r\n * Unless propagation is stopped, an event dispatched by an\r\n * EventTarget will bubble to the parent returned by\r\n * `getParentEventTarget`. To set the parent, call\r\n * `setParentEventTarget`. Subclasses that don't support\r\n * changing the parent can override the setter to throw an error.\r\n *\r\n * Example usage:\r\n * <pre>\r\n * var source = new goog.events.EventTarget();\r\n * function handleEvent(e) {\r\n * alert('Type: ' + e.type + '; Target: ' + e.target);\r\n * }\r\n * source.listen('foo', handleEvent);\r\n * // Or: goog.events.listen(source, 'foo', handleEvent);\r\n * ...\r\n * source.dispatchEvent('foo'); // will call handleEvent\r\n * ...\r\n * source.unlisten('foo', handleEvent);\r\n * // Or: goog.events.unlisten(source, 'foo', handleEvent);\r\n * </pre>\r\n *\r\n * @constructor\r\n * @extends {goog.Disposable}\r\n * @implements {goog.events.Listenable}\r\n */\r\ngoog.events.EventTarget = function() {\r\n goog.Disposable.call(this);\r\n\r\n /**\r\n * Maps of event type to an array of listeners.\r\n * @private {!goog.events.ListenerMap}\r\n */\r\n this.eventTargetListeners_ = new goog.events.ListenerMap(this);\r\n\r\n /**\r\n * The object to use for event.target. Useful when mixing in an\r\n * EventTarget to another object.\r\n * @private {!Object}\r\n */\r\n this.actualEventTarget_ = this;\r\n\r\n /**\r\n * Parent event target, used during event bubbling.\r\n *\r\n * TODO(chrishenry): Change this to goog.events.Listenable. This\r\n * currently breaks people who expect getParentEventTarget to return\r\n * goog.events.EventTarget.\r\n *\r\n * @private {?goog.events.EventTarget}\r\n */\r\n this.parentEventTarget_ = null;\r\n};\r\ngoog.inherits(goog.events.EventTarget, goog.Disposable);\r\ngoog.events.Listenable.addImplementation(goog.events.EventTarget);\r\n\r\n\r\n/**\r\n * An artificial cap on the number of ancestors you can have. This is mainly\r\n * for loop detection.\r\n * @const {number}\r\n * @private\r\n */\r\ngoog.events.EventTarget.MAX_ANCESTORS_ = 1000;\r\n\r\n\r\n/**\r\n * Returns the parent of this event target to use for bubbling.\r\n *\r\n * @return {goog.events.EventTarget} The parent EventTarget or null if\r\n * there is no parent.\r\n * @override\r\n */\r\ngoog.events.EventTarget.prototype.getParentEventTarget = function() {\r\n return this.parentEventTarget_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the parent of this event target to use for capture/bubble\r\n * mechanism.\r\n * @param {goog.events.EventTarget} parent Parent listenable (null if none).\r\n */\r\ngoog.events.EventTarget.prototype.setParentEventTarget = function(parent) {\r\n this.parentEventTarget_ = parent;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener to the event target. The same handler can only be\r\n * added once per the type. Even if you add the same handler multiple times\r\n * using the same type then it will only be called once when the event is\r\n * dispatched.\r\n *\r\n * @param {string|!goog.events.EventId} type The type of the event to listen for\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\r\n * to handle the event. The handler can also be an object that implements\r\n * the handleEvent method which takes the event object as argument.\r\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase\r\n * of the event.\r\n * @param {Object=} opt_handlerScope Object in whose scope to call\r\n * the listener.\r\n * @deprecated Use `#listen` instead, when possible. Otherwise, use\r\n * `goog.events.listen` if you are passing Object\r\n * (instead of Function) as handler.\r\n */\r\ngoog.events.EventTarget.prototype.addEventListener = function(\r\n type, handler, opt_capture, opt_handlerScope) {\r\n goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener from the event target. The handler must be the\r\n * same object as the one added. If the handler has not been added then\r\n * nothing is done.\r\n *\r\n * @param {string} type The type of the event to listen for.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\r\n * to handle the event. The handler can also be an object that implements\r\n * the handleEvent method which takes the event object as argument.\r\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase\r\n * of the event.\r\n * @param {Object=} opt_handlerScope Object in whose scope to call\r\n * the listener.\r\n * @deprecated Use `#unlisten` instead, when possible. Otherwise, use\r\n * `goog.events.unlisten` if you are passing Object\r\n * (instead of Function) as handler.\r\n */\r\ngoog.events.EventTarget.prototype.removeEventListener = function(\r\n type, handler, opt_capture, opt_handlerScope) {\r\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\r\n this.assertInitialized_();\r\n\r\n var ancestorsTree, ancestor = this.getParentEventTarget();\r\n if (ancestor) {\r\n ancestorsTree = [];\r\n var ancestorCount = 1;\r\n for (; ancestor; ancestor = ancestor.getParentEventTarget()) {\r\n ancestorsTree.push(ancestor);\r\n goog.asserts.assert(\r\n (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),\r\n 'infinite loop');\r\n }\r\n }\r\n\r\n return goog.events.EventTarget.dispatchEventInternal_(\r\n this.actualEventTarget_, e, ancestorsTree);\r\n};\r\n\r\n\r\n/**\r\n * Removes listeners from this object. Classes that extend EventTarget may\r\n * need to override this method in order to remove references to DOM Elements\r\n * and additional listeners.\r\n * @override\r\n * @protected\r\n */\r\ngoog.events.EventTarget.prototype.disposeInternal = function() {\r\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\r\n\r\n this.removeAllListeners();\r\n this.parentEventTarget_ = null;\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.listen = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n this.assertInitialized_();\r\n return this.eventTargetListeners_.add(\r\n String(type), listener, false /* callOnce */, opt_useCapture,\r\n opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.listenOnce = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n return this.eventTargetListeners_.add(\r\n String(type), listener, true /* callOnce */, opt_useCapture,\r\n opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.unlisten = function(\r\n type, listener, opt_useCapture, opt_listenerScope) {\r\n return this.eventTargetListeners_.remove(\r\n String(type), listener, opt_useCapture, opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\r\n return this.eventTargetListeners_.removeByKey(key);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\r\n // TODO(chrishenry): Previously, removeAllListeners can be called on\r\n // uninitialized EventTarget, so we preserve that behavior. We\r\n // should remove this when usages that rely on that fact are purged.\r\n if (!this.eventTargetListeners_) {\r\n return 0;\r\n }\r\n return this.eventTargetListeners_.removeAll(opt_type);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.fireListeners = function(\r\n type, capture, eventObject) {\r\n // TODO(chrishenry): Original code avoids array creation when there\r\n // is no listener, so we do the same. If this optimization turns\r\n // out to be not required, we can replace this with\r\n // getListeners(type, capture) instead, which is simpler.\r\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\r\n if (!listenerArray) {\r\n return true;\r\n }\r\n listenerArray = listenerArray.concat();\r\n\r\n var rv = true;\r\n for (var i = 0; i < listenerArray.length; ++i) {\r\n var listener = listenerArray[i];\r\n // We might not have a listener if the listener was removed.\r\n if (listener && !listener.removed && listener.capture == capture) {\r\n var listenerFn = listener.listener;\r\n var listenerHandler = listener.handler || listener.src;\r\n\r\n if (listener.callOnce) {\r\n this.unlistenByKey(listener);\r\n }\r\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\r\n }\r\n }\r\n\r\n return rv && eventObject.returnValue_ != false;\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\r\n return this.eventTargetListeners_.getListeners(String(type), capture);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.getListener = function(\r\n type, listener, capture, opt_listenerScope) {\r\n return this.eventTargetListeners_.getListener(\r\n String(type), listener, capture, opt_listenerScope);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.events.EventTarget.prototype.hasListener = function(\r\n opt_type, opt_capture) {\r\n var id = goog.isDef(opt_type) ? String(opt_type) : undefined;\r\n return this.eventTargetListeners_.hasListener(id, opt_capture);\r\n};\r\n\r\n\r\n/**\r\n * Sets the target to be used for `event.target` when firing\r\n * event. Mainly used for testing. For example, see\r\n * `goog.testing.events.mixinListenable`.\r\n * @param {!Object} target The target.\r\n */\r\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\r\n this.actualEventTarget_ = target;\r\n};\r\n\r\n\r\n/**\r\n * Asserts that the event target instance is initialized properly.\r\n * @private\r\n */\r\ngoog.events.EventTarget.prototype.assertInitialized_ = function() {\r\n goog.asserts.assert(\r\n this.eventTargetListeners_,\r\n 'Event target is not initialized. Did you call the superclass ' +\r\n '(goog.events.EventTarget) constructor?');\r\n};\r\n\r\n\r\n/**\r\n * Dispatches the given event on the ancestorsTree.\r\n *\r\n * @param {!Object} target The target to dispatch on.\r\n * @param {goog.events.Event|Object|string} e The event object.\r\n * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors\r\n * tree of the target, in reverse order from the closest ancestor\r\n * to the root event target. May be null if the target has no ancestor.\r\n * @return {boolean} If anyone called preventDefault on the event object (or\r\n * if any of the listeners returns false) this will also return false.\r\n * @private\r\n */\r\ngoog.events.EventTarget.dispatchEventInternal_ = function(\r\n target, e, opt_ancestorsTree) {\r\n /** @suppress {missingProperties} */\r\n var type = e.type || /** @type {string} */ (e);\r\n\r\n // If accepting a string or object, create a custom event object so that\r\n // preventDefault and stopPropagation work with the event.\r\n if (goog.isString(e)) {\r\n e = new goog.events.Event(e, target);\r\n } else if (!(e instanceof goog.events.Event)) {\r\n var oldEvent = e;\r\n e = new goog.events.Event(type, target);\r\n goog.object.extend(e, oldEvent);\r\n } else {\r\n e.target = e.target || target;\r\n }\r\n\r\n var rv = true, currentTarget;\r\n\r\n // Executes all capture listeners on the ancestors, if any.\r\n if (opt_ancestorsTree) {\r\n for (var i = opt_ancestorsTree.length - 1; !e.propagationStopped_ && i >= 0;\r\n i--) {\r\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\r\n rv = currentTarget.fireListeners(type, true, e) && rv;\r\n }\r\n }\r\n\r\n // Executes capture and bubble listeners on the target.\r\n if (!e.propagationStopped_) {\r\n currentTarget = /** @type {?} */ (e.currentTarget = target);\r\n rv = currentTarget.fireListeners(type, true, e) && rv;\r\n if (!e.propagationStopped_) {\r\n rv = currentTarget.fireListeners(type, false, e) && rv;\r\n }\r\n }\r\n\r\n // Executes all bubble listeners on the ancestors, if any.\r\n if (opt_ancestorsTree) {\r\n for (i = 0; !e.propagationStopped_ && i < opt_ancestorsTree.length; i++) {\r\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\r\n rv = currentTarget.fireListeners(type, false, e) && rv;\r\n }\r\n }\r\n\r\n return rv;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview JSON utility functions.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\ngoog.provide('goog.json');\r\ngoog.provide('goog.json.Replacer');\r\ngoog.provide('goog.json.Reviver');\r\ngoog.provide('goog.json.Serializer');\r\n\r\n\r\n/**\r\n * @define {boolean} If true, use the native JSON parsing API.\r\n * NOTE: The default `goog.json.parse` implementation is able to handle\r\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\r\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\r\n * faster and safer than the default implementation using `eval`.\r\n */\r\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\r\n\r\n/**\r\n * @define {boolean} If true, try the native JSON parsing API first. If it\r\n * fails, log an error and use `eval` instead. This is useful when\r\n * transitioning to `goog.json.USE_NATIVE_JSON`. The error logger needs to\r\n * be set by `goog.json.setErrorLogger`. If it is not set then the error\r\n * is ignored.\r\n */\r\ngoog.json.TRY_NATIVE_JSON = goog.define('goog.json.TRY_NATIVE_JSON', false);\r\n\r\n\r\n/**\r\n * Tests if a string is an invalid JSON string. This only ensures that we are\r\n * not using any invalid characters\r\n * @param {string} s The string to test.\r\n * @return {boolean} True if the input is a valid JSON string.\r\n */\r\ngoog.json.isValid = function(s) {\r\n // All empty whitespace is not valid.\r\n if (/^\\s*$/.test(s)) {\r\n return false;\r\n }\r\n\r\n // This is taken from http://www.json.org/json2.js which is released to the\r\n // public domain.\r\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\r\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\r\n // are in the RFC but IE and Safari does not match \\s to these so we need to\r\n // include them in the reg exps in all places where whitespace is allowed.\r\n // We allowed \\x7f inside strings because some tools don't escape it,\r\n // e.g. http://www.json.org/java/org/json/JSONObject.java\r\n\r\n // Parsing happens in three stages. In the first stage, we run the text\r\n // against regular expressions that look for non-JSON patterns. We are\r\n // especially concerned with '()' and 'new' because they can cause invocation,\r\n // and '=' because it can cause mutation. But just to be safe, we want to\r\n // reject all unexpected forms.\r\n\r\n // We split the first stage into 4 regexp operations in order to work around\r\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\r\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\r\n // replace all simple value tokens with ']' characters, but only when followed\r\n // by a colon, comma, closing bracket or end of string. Third, we delete all\r\n // open brackets that follow a colon or comma or that begin the text. Finally,\r\n // we look to see that the remaining characters are only whitespace or ']' or\r\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\r\n\r\n // Don't make these static since they have the global flag.\r\n var backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\r\n var simpleValuesRe =\r\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\r\n var openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\r\n var remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\r\n\r\n return remainderRe.test(\r\n s.replace(backslashesRe, '@')\r\n .replace(simpleValuesRe, ']')\r\n .replace(openBracketsRe, ''));\r\n};\r\n\r\n/**\r\n * Logs a parsing error in `JSON.parse` solvable by using `eval`\r\n * if `goog.json.TRY_NATIVE_JSON` is enabled.\r\n * @private {function(string, !Error)} The first parameter is the error message,\r\n * the second is the exception thrown by `JSON.parse`.\r\n */\r\ngoog.json.errorLogger_ = goog.nullFunction;\r\n\r\n\r\n/**\r\n * Sets an error logger to use if there's a recoverable parsing error and\r\n * `goog.json.TRY_NATIVE_JSON` is enabled.\r\n * @param {function(string, !Error)} errorLogger The first parameter is the\r\n * error message, the second is the exception thrown by `JSON.parse`.\r\n */\r\ngoog.json.setErrorLogger = function(errorLogger) {\r\n goog.json.errorLogger_ = errorLogger;\r\n};\r\n\r\n\r\n/**\r\n * Parses a JSON string and returns the result. This throws an exception if\r\n * the string is an invalid JSON string.\r\n *\r\n * Note that this is very slow on large strings. Use JSON.parse if possible.\r\n *\r\n * @param {*} s The JSON string to parse.\r\n * @throws Error if s is invalid JSON.\r\n * @return {Object} The object generated from the JSON string, or null.\r\n * @deprecated Use JSON.parse.\r\n */\r\ngoog.json.parse = goog.json.USE_NATIVE_JSON ?\r\n /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :\r\n function(s) {\r\n var error;\r\n if (goog.json.TRY_NATIVE_JSON) {\r\n try {\r\n return goog.global['JSON']['parse'](s);\r\n } catch (ex) {\r\n error = ex;\r\n }\r\n }\r\n var o = String(s);\r\n if (goog.json.isValid(o)) {\r\n\r\n try {\r\n var result = /** @type {?Object} */ (eval('(' + o + ')'));\r\n if (error) {\r\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\r\n }\r\n return result;\r\n } catch (ex) {\r\n }\r\n }\r\n throw new Error('Invalid JSON string: ' + o);\r\n };\r\n\r\n\r\n/**\r\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\r\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\r\n *\r\n * TODO(nicksantos): Array should also be a valid replacer.\r\n *\r\n * @typedef {function(this:Object, string, *): *}\r\n */\r\ngoog.json.Replacer;\r\n\r\n\r\n/**\r\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\r\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\r\n *\r\n * @typedef {function(this:Object, string, *): *}\r\n */\r\ngoog.json.Reviver;\r\n\r\n\r\n/**\r\n * Serializes an object or a value to a JSON string.\r\n *\r\n * @param {*} object The object to serialize.\r\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\r\n * called for each (key, value) pair that determines how the value\r\n * should be serialized. By defult, this just returns the value\r\n * and allows default serialization to kick in.\r\n * @throws Error if there are loops in the object graph.\r\n * @return {string} A JSON string representation of the input.\r\n */\r\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\r\n /** @type {function(*, ?goog.json.Replacer=):string} */\r\n (goog.global['JSON']['stringify']) :\r\n function(object, opt_replacer) {\r\n // NOTE(nicksantos): Currently, we never use JSON.stringify.\r\n //\r\n // The last time I evaluated this, JSON.stringify had subtle bugs and\r\n // behavior differences on all browsers, and the performance win was not\r\n // large enough to justify all the issues. This may change in the future\r\n // as browser implementations get better.\r\n //\r\n // assertSerialize in json_test contains if branches for the cases\r\n // that fail.\r\n return new goog.json.Serializer(opt_replacer).serialize(object);\r\n };\r\n\r\n\r\n\r\n/**\r\n * Class that is used to serialize JSON objects to a string.\r\n * @param {?goog.json.Replacer=} opt_replacer Replacer.\r\n * @constructor\r\n */\r\ngoog.json.Serializer = function(opt_replacer) {\r\n /**\r\n * @type {goog.json.Replacer|null|undefined}\r\n * @private\r\n */\r\n this.replacer_ = opt_replacer;\r\n};\r\n\r\n\r\n/**\r\n * Serializes an object or a value to a JSON string.\r\n *\r\n * @param {*} object The object to serialize.\r\n * @throws Error if there are loops in the object graph.\r\n * @return {string} A JSON string representation of the input.\r\n */\r\ngoog.json.Serializer.prototype.serialize = function(object) {\r\n var sb = [];\r\n this.serializeInternal(object, sb);\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Serializes a generic value to a JSON string\r\n * @protected\r\n * @param {*} object The object to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n * @throws Error if there are loops in the object graph.\r\n */\r\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\r\n if (object == null) {\r\n // undefined == null so this branch covers undefined as well as null\r\n sb.push('null');\r\n return;\r\n }\r\n\r\n if (typeof object == 'object') {\r\n if (goog.isArray(object)) {\r\n this.serializeArray(object, sb);\r\n return;\r\n } else if (\r\n object instanceof String || object instanceof Number ||\r\n object instanceof Boolean) {\r\n object = object.valueOf();\r\n // Fall through to switch below.\r\n } else {\r\n this.serializeObject_(/** @type {!Object} */ (object), sb);\r\n return;\r\n }\r\n }\r\n\r\n switch (typeof object) {\r\n case 'string':\r\n this.serializeString_(object, sb);\r\n break;\r\n case 'number':\r\n this.serializeNumber_(object, sb);\r\n break;\r\n case 'boolean':\r\n sb.push(String(object));\r\n break;\r\n case 'function':\r\n sb.push('null');\r\n break;\r\n default:\r\n throw new Error('Unknown type: ' + typeof object);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Character mappings used internally for goog.string.quote\r\n * @private\r\n * @type {!Object}\r\n */\r\ngoog.json.Serializer.charToJsonCharCache_ = {\r\n '\\\"': '\\\\\"',\r\n '\\\\': '\\\\\\\\',\r\n '/': '\\\\/',\r\n '\\b': '\\\\b',\r\n '\\f': '\\\\f',\r\n '\\n': '\\\\n',\r\n '\\r': '\\\\r',\r\n '\\t': '\\\\t',\r\n\r\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\r\n};\r\n\r\n\r\n/**\r\n * Regular expression used to match characters that need to be replaced.\r\n * The S60 browser has a bug where unicode characters are not matched by\r\n * regular expressions. The condition below detects such behaviour and\r\n * adjusts the regular expression accordingly.\r\n * @private\r\n * @type {!RegExp}\r\n */\r\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\r\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\r\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\r\n\r\n\r\n/**\r\n * Serializes a string to a JSON string\r\n * @private\r\n * @param {string} s The string to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n */\r\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\r\n // The official JSON implementation does not work with international\r\n // characters.\r\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\r\n // caching the result improves performance by a factor 2-3\r\n var rv = goog.json.Serializer.charToJsonCharCache_[c];\r\n if (!rv) {\r\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).substr(1);\r\n goog.json.Serializer.charToJsonCharCache_[c] = rv;\r\n }\r\n return rv;\r\n }), '\"');\r\n};\r\n\r\n\r\n/**\r\n * Serializes a number to a JSON string\r\n * @private\r\n * @param {number} n The number to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n */\r\ngoog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {\r\n sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');\r\n};\r\n\r\n\r\n/**\r\n * Serializes an array to a JSON string\r\n * @param {Array<string>} arr The array to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n * @protected\r\n */\r\ngoog.json.Serializer.prototype.serializeArray = function(arr, sb) {\r\n var l = arr.length;\r\n sb.push('[');\r\n var sep = '';\r\n for (var i = 0; i < l; i++) {\r\n sb.push(sep);\r\n\r\n var value = arr[i];\r\n this.serializeInternal(\r\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\r\n sb);\r\n\r\n sep = ',';\r\n }\r\n sb.push(']');\r\n};\r\n\r\n\r\n/**\r\n * Serializes an object to a JSON string\r\n * @private\r\n * @param {!Object} obj The object to serialize.\r\n * @param {Array<string>} sb Array used as a string builder.\r\n */\r\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\r\n sb.push('{');\r\n var sep = '';\r\n for (var key in obj) {\r\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\r\n var value = obj[key];\r\n // Skip functions.\r\n if (typeof value != 'function') {\r\n sb.push(sep);\r\n this.serializeString_(key, sb);\r\n sb.push(':');\r\n\r\n this.serializeInternal(\r\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\r\n\r\n sep = ',';\r\n }\r\n }\r\n }\r\n sb.push('}');\r\n};\r\n","// Copyright 2015 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Simple freelist.\r\n *\r\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\r\n * objects in the list contain a \"next\" property that can be used to maintain\r\n * the pool.\r\n */\r\n\r\ngoog.provide('goog.async.FreeList');\r\n\r\n\r\n/**\r\n * @template ITEM\r\n */\r\ngoog.async.FreeList = goog.defineClass(null, {\r\n /**\r\n * @param {function():ITEM} create\r\n * @param {function(ITEM):void} reset\r\n * @param {number} limit\r\n */\r\n constructor: function(create, reset, limit) {\r\n /** @private @const {number} */\r\n this.limit_ = limit;\r\n /** @private @const {function()} */\r\n this.create_ = create;\r\n /** @private @const {function(ITEM):void} */\r\n this.reset_ = reset;\r\n\r\n /** @private {number} */\r\n this.occupants_ = 0;\r\n /** @private {ITEM} */\r\n this.head_ = null;\r\n },\r\n\r\n /**\r\n * @return {ITEM}\r\n */\r\n get: function() {\r\n var item;\r\n if (this.occupants_ > 0) {\r\n this.occupants_--;\r\n item = this.head_;\r\n this.head_ = item.next;\r\n item.next = null;\r\n } else {\r\n item = this.create_();\r\n }\r\n return item;\r\n },\r\n\r\n /**\r\n * @param {ITEM} item An item available for possible future reuse.\r\n */\r\n put: function(item) {\r\n this.reset_(item);\r\n if (this.occupants_ < this.limit_) {\r\n this.occupants_++;\r\n item.next = this.head_;\r\n this.head_ = item;\r\n }\r\n },\r\n\r\n /**\r\n * Visible for testing.\r\n * @package\r\n * @return {number}\r\n */\r\n occupants: function() { return this.occupants_; }\r\n});\r\n","// Copyright 2015 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\ngoog.provide('goog.async.WorkItem');\r\ngoog.provide('goog.async.WorkQueue');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.async.FreeList');\r\n\r\n\r\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\r\n// than goog.async.run.\r\n\r\n\r\n\r\n/**\r\n * A low GC workqueue. The key elements of this design:\r\n * - avoids the need for goog.bind or equivalent by carrying scope\r\n * - avoids the need for array reallocation by using a linked list\r\n * - minimizes work entry objects allocation by recycling objects\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\ngoog.async.WorkQueue = function() {\r\n this.workHead_ = null;\r\n this.workTail_ = null;\r\n};\r\n\r\n\r\n/** @define {number} The maximum number of entries to keep for recycling. */\r\ngoog.async.WorkQueue.DEFAULT_MAX_UNUSED =\r\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\r\n\r\n\r\n/** @const @private {goog.async.FreeList<goog.async.WorkItem>} */\r\ngoog.async.WorkQueue.freelist_ = new goog.async.FreeList(\r\n function() { return new goog.async.WorkItem(); },\r\n function(item) { item.reset(); }, goog.async.WorkQueue.DEFAULT_MAX_UNUSED);\r\n\r\n\r\n/**\r\n * @param {function()} fn\r\n * @param {Object|null|undefined} scope\r\n */\r\ngoog.async.WorkQueue.prototype.add = function(fn, scope) {\r\n var item = this.getUnusedItem_();\r\n item.set(fn, scope);\r\n\r\n if (this.workTail_) {\r\n this.workTail_.next = item;\r\n this.workTail_ = item;\r\n } else {\r\n goog.asserts.assert(!this.workHead_);\r\n this.workHead_ = item;\r\n this.workTail_ = item;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {goog.async.WorkItem}\r\n */\r\ngoog.async.WorkQueue.prototype.remove = function() {\r\n var item = null;\r\n\r\n if (this.workHead_) {\r\n item = this.workHead_;\r\n this.workHead_ = this.workHead_.next;\r\n if (!this.workHead_) {\r\n this.workTail_ = null;\r\n }\r\n item.next = null;\r\n }\r\n return item;\r\n};\r\n\r\n\r\n/**\r\n * @param {goog.async.WorkItem} item\r\n */\r\ngoog.async.WorkQueue.prototype.returnUnused = function(item) {\r\n goog.async.WorkQueue.freelist_.put(item);\r\n};\r\n\r\n\r\n/**\r\n * @return {goog.async.WorkItem}\r\n * @private\r\n */\r\ngoog.async.WorkQueue.prototype.getUnusedItem_ = function() {\r\n return goog.async.WorkQueue.freelist_.get();\r\n};\r\n\r\n\r\n\r\n/**\r\n * @constructor\r\n * @final\r\n * @struct\r\n */\r\ngoog.async.WorkItem = function() {\r\n /** @type {?function()} */\r\n this.fn = null;\r\n /** @type {?Object|null|undefined} */\r\n this.scope = null;\r\n /** @type {?goog.async.WorkItem} */\r\n this.next = null;\r\n};\r\n\r\n\r\n/**\r\n * @param {function()} fn\r\n * @param {Object|null|undefined} scope\r\n */\r\ngoog.async.WorkItem.prototype.set = function(fn, scope) {\r\n this.fn = fn;\r\n this.scope = scope;\r\n this.next = null;\r\n};\r\n\r\n\r\n/** Reset the work item so they don't prevent GC before reuse */\r\ngoog.async.WorkItem.prototype.reset = function() {\r\n this.fn = null;\r\n this.scope = null;\r\n this.next = null;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\ngoog.provide('goog.async.run');\r\n\r\ngoog.require('goog.async.WorkQueue');\r\ngoog.require('goog.async.nextTick');\r\ngoog.require('goog.async.throwException');\r\n\r\n/**\r\n * @define {boolean} If true, use the global Promise to implement goog.async.run\r\n * assuming either the native, or polyfill version will be used. Does still\r\n * permit tests to use forceNextTick.\r\n */\r\ngoog.ASSUME_NATIVE_PROMISE = goog.define('goog.ASSUME_NATIVE_PROMISE', false);\r\n\r\n/**\r\n * Fires the provided callback just before the current callstack unwinds, or as\r\n * soon as possible after the current JS execution context.\r\n * @param {function(this:THIS)} callback\r\n * @param {THIS=} opt_context Object to use as the \"this value\" when calling\r\n * the provided function.\r\n * @template THIS\r\n */\r\ngoog.async.run = function(callback, opt_context) {\r\n if (!goog.async.run.schedule_) {\r\n goog.async.run.initializeRunner_();\r\n }\r\n if (!goog.async.run.workQueueScheduled_) {\r\n // Nothing is currently scheduled, schedule it now.\r\n goog.async.run.schedule_();\r\n goog.async.run.workQueueScheduled_ = true;\r\n }\r\n\r\n goog.async.run.workQueue_.add(callback, opt_context);\r\n};\r\n\r\n\r\n/**\r\n * Initializes the function to use to process the work queue.\r\n * @private\r\n */\r\ngoog.async.run.initializeRunner_ = function() {\r\n if (goog.ASSUME_NATIVE_PROMISE ||\r\n (goog.global.Promise && goog.global.Promise.resolve)) {\r\n // Use goog.global.Promise instead of just Promise because the relevant\r\n // externs may be missing, and don't alias it because this could confuse the\r\n // compiler into thinking the polyfill is required when it should be treated\r\n // as optional.\r\n var promise = goog.global.Promise.resolve(undefined);\r\n goog.async.run.schedule_ = function() {\r\n promise.then(goog.async.run.processWorkQueue);\r\n };\r\n } else {\r\n goog.async.run.schedule_ = function() {\r\n goog.async.nextTick(goog.async.run.processWorkQueue);\r\n };\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Forces goog.async.run to use nextTick instead of Promise.\r\n *\r\n * This should only be done in unit tests. It's useful because MockClock\r\n * replaces nextTick, but not the browser Promise implementation, so it allows\r\n * Promise-based code to be tested with MockClock.\r\n *\r\n * However, we also want to run promises if the MockClock is no longer in\r\n * control so we schedule a backup \"setTimeout\" to the unmocked timeout if\r\n * provided.\r\n *\r\n * @param {function(function())=} opt_realSetTimeout\r\n */\r\ngoog.async.run.forceNextTick = function(opt_realSetTimeout) {\r\n goog.async.run.schedule_ = function() {\r\n goog.async.nextTick(goog.async.run.processWorkQueue);\r\n if (opt_realSetTimeout) {\r\n opt_realSetTimeout(goog.async.run.processWorkQueue);\r\n }\r\n };\r\n};\r\n\r\n\r\n/**\r\n * The function used to schedule work asynchronousely.\r\n * @private {function()}\r\n */\r\ngoog.async.run.schedule_;\r\n\r\n\r\n/** @private {boolean} */\r\ngoog.async.run.workQueueScheduled_ = false;\r\n\r\n\r\n/** @private {!goog.async.WorkQueue} */\r\ngoog.async.run.workQueue_ = new goog.async.WorkQueue();\r\n\r\n\r\nif (goog.DEBUG) {\r\n /**\r\n * Reset the work queue. Only available for tests in debug mode.\r\n */\r\n goog.async.run.resetQueue = function() {\r\n goog.async.run.workQueueScheduled_ = false;\r\n goog.async.run.workQueue_ = new goog.async.WorkQueue();\r\n };\r\n}\r\n\r\n\r\n/**\r\n * Run any pending goog.async.run work items. This function is not intended\r\n * for general use, but for use by entry point handlers to run items ahead of\r\n * goog.async.nextTick.\r\n */\r\ngoog.async.run.processWorkQueue = function() {\r\n // NOTE: additional work queue items may be added while processing.\r\n var item = null;\r\n while (item = goog.async.run.workQueue_.remove()) {\r\n try {\r\n item.fn.call(item.scope);\r\n } catch (e) {\r\n goog.async.throwException(e);\r\n }\r\n goog.async.run.workQueue_.returnUnused(item);\r\n }\r\n\r\n // There are no more work items, allow processing to be scheduled again.\r\n goog.async.run.workQueueScheduled_ = false;\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Provides a function to schedule running a function as soon\r\n * as possible after the current JS execution stops and yields to the event\r\n * loop.\r\n *\r\n */\r\n\r\ngoog.provide('goog.async.nextTick');\r\ngoog.provide('goog.async.throwException');\r\n\r\ngoog.require('goog.debug.entryPointRegistry');\r\ngoog.require('goog.dom.TagName');\r\ngoog.require('goog.functions');\r\ngoog.require('goog.labs.userAgent.browser');\r\ngoog.require('goog.labs.userAgent.engine');\r\n\r\n\r\n/**\r\n * Throw an item without interrupting the current execution context. For\r\n * example, if processing a group of items in a loop, sometimes it is useful\r\n * to report an error while still allowing the rest of the batch to be\r\n * processed.\r\n * @param {*} exception\r\n */\r\ngoog.async.throwException = function(exception) {\r\n // Each throw needs to be in its own context.\r\n goog.global.setTimeout(function() { throw exception; }, 0);\r\n};\r\n\r\n\r\n/**\r\n * Fires the provided callbacks as soon as possible after the current JS\r\n * execution context. setTimeout(…, 0) takes at least 4ms when called from\r\n * within another setTimeout(…, 0) for legacy reasons.\r\n *\r\n * This will not schedule the callback as a microtask (i.e. a task that can\r\n * preempt user input or networking callbacks). It is meant to emulate what\r\n * setTimeout(_, 0) would do if it were not throttled. If you desire microtask\r\n * behavior, use {@see goog.Promise} instead.\r\n *\r\n * @param {function(this:SCOPE)} callback Callback function to fire as soon as\r\n * possible.\r\n * @param {SCOPE=} opt_context Object in whose scope to call the listener.\r\n * @param {boolean=} opt_useSetImmediate Avoid the IE workaround that\r\n * ensures correctness at the cost of speed. See comments for details.\r\n * @template SCOPE\r\n */\r\ngoog.async.nextTick = function(callback, opt_context, opt_useSetImmediate) {\r\n var cb = callback;\r\n if (opt_context) {\r\n cb = goog.bind(callback, opt_context);\r\n }\r\n cb = goog.async.nextTick.wrapCallback_(cb);\r\n // Note we do allow callers to also request setImmediate if they are willing\r\n // to accept the possible tradeoffs of incorrectness in exchange for speed.\r\n // The IE fallback of readystate change is much slower. See useSetImmediate_\r\n // for details.\r\n if (goog.isFunction(goog.global.setImmediate) &&\r\n (opt_useSetImmediate || goog.async.nextTick.useSetImmediate_())) {\r\n goog.global.setImmediate(cb);\r\n return;\r\n }\r\n\r\n // Look for and cache the custom fallback version of setImmediate.\r\n if (!goog.async.nextTick.setImmediate_) {\r\n goog.async.nextTick.setImmediate_ =\r\n goog.async.nextTick.getSetImmediateEmulator_();\r\n }\r\n goog.async.nextTick.setImmediate_(cb);\r\n};\r\n\r\n\r\n/**\r\n * Returns whether should use setImmediate implementation currently on window.\r\n *\r\n * window.setImmediate was introduced and currently only supported by IE10+,\r\n * but due to a bug in the implementation it is not guaranteed that\r\n * setImmediate is faster than setTimeout nor that setImmediate N is before\r\n * setImmediate N+1. That is why we do not use the native version if\r\n * available. We do, however, call setImmediate if it is a non-native function\r\n * because that indicates that it has been replaced by goog.testing.MockClock\r\n * which we do want to support.\r\n * See\r\n * http://connect.microsoft.com/IE/feedback/details/801823/setimmediate-and-messagechannel-are-broken-in-ie10\r\n *\r\n * @return {boolean} Whether to use the implementation of setImmediate defined\r\n * on Window.\r\n * @private\r\n * @suppress {missingProperties} For \"Window.prototype.setImmediate\"\r\n */\r\ngoog.async.nextTick.useSetImmediate_ = function() {\r\n // Not a browser environment.\r\n if (!goog.global.Window || !goog.global.Window.prototype) {\r\n return true;\r\n }\r\n\r\n // MS Edge has window.setImmediate natively, but it's not on Window.prototype.\r\n // Also, there's no clean way to detect if the goog.global.setImmediate has\r\n // been replaced by mockClock as its replacement also shows up as \"[native\r\n // code]\" when using toString. Therefore, just always use\r\n // goog.global.setImmediate for Edge. It's unclear if it suffers the same\r\n // issues as IE10/11, but based on\r\n // https://dev.modern.ie/testdrive/demos/setimmediatesorting/\r\n // it seems they've been working to ensure it's WAI.\r\n if (goog.labs.userAgent.browser.isEdge() ||\r\n goog.global.Window.prototype.setImmediate != goog.global.setImmediate) {\r\n // Something redefined setImmediate in which case we decide to use it (This\r\n // is so that we use the mockClock setImmediate).\r\n return true;\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Cache for the setImmediate implementation.\r\n * @type {function(function())}\r\n * @private\r\n */\r\ngoog.async.nextTick.setImmediate_;\r\n\r\n\r\n/**\r\n * Determines the best possible implementation to run a function as soon as\r\n * the JS event loop is idle.\r\n * @return {function(function())} The \"setImmediate\" implementation.\r\n * @private\r\n */\r\ngoog.async.nextTick.getSetImmediateEmulator_ = function() {\r\n // Create a private message channel and use it to postMessage empty messages\r\n // to ourselves.\r\n /** @type {!Function|undefined} */\r\n var Channel = goog.global['MessageChannel'];\r\n // If MessageChannel is not available and we are in a browser, implement\r\n // an iframe based polyfill in browsers that have postMessage and\r\n // document.addEventListener. The latter excludes IE8 because it has a\r\n // synchronous postMessage implementation.\r\n if (typeof Channel === 'undefined' && typeof window !== 'undefined' &&\r\n window.postMessage && window.addEventListener &&\r\n // Presto (The old pre-blink Opera engine) has problems with iframes\r\n // and contentWindow.\r\n !goog.labs.userAgent.engine.isPresto()) {\r\n /** @constructor */\r\n Channel = function() {\r\n // Make an empty, invisible iframe.\r\n var iframe = /** @type {!HTMLIFrameElement} */ (\r\n document.createElement(String(goog.dom.TagName.IFRAME)));\r\n iframe.style.display = 'none';\r\n iframe.src = '';\r\n document.documentElement.appendChild(iframe);\r\n var win = iframe.contentWindow;\r\n var doc = win.document;\r\n doc.open();\r\n doc.write('');\r\n doc.close();\r\n // Do not post anything sensitive over this channel, as the workaround for\r\n // pages with file: origin could allow that information to be modified or\r\n // intercepted.\r\n var message = 'callImmediate' + Math.random();\r\n // The same origin policy rejects attempts to postMessage from file: urls\r\n // unless the origin is '*'.\r\n var origin = win.location.protocol == 'file:' ?\r\n '*' :\r\n win.location.protocol + '//' + win.location.host;\r\n var onmessage = goog.bind(function(e) {\r\n // Validate origin and message to make sure that this message was\r\n // intended for us. If the origin is set to '*' (see above) only the\r\n // message needs to match since, for example, '*' != 'file://'. Allowing\r\n // the wildcard is ok, as we are not concerned with security here.\r\n if ((origin != '*' && e.origin != origin) || e.data != message) {\r\n return;\r\n }\r\n this['port1'].onmessage();\r\n }, this);\r\n win.addEventListener('message', onmessage, false);\r\n this['port1'] = {};\r\n this['port2'] = {\r\n postMessage: function() { win.postMessage(message, origin); }\r\n };\r\n };\r\n }\r\n if (typeof Channel !== 'undefined' && !goog.labs.userAgent.browser.isIE()) {\r\n // Exclude all of IE due to\r\n // http://codeforhire.com/2013/09/21/setimmediate-and-messagechannel-broken-on-internet-explorer-10/\r\n // which allows starving postMessage with a busy setTimeout loop.\r\n // This currently affects IE10 and IE11 which would otherwise be able\r\n // to use the postMessage based fallbacks.\r\n var channel = new Channel();\r\n // Use a fifo linked list to call callbacks in the right order.\r\n var head = {};\r\n var tail = head;\r\n channel['port1'].onmessage = function() {\r\n if (goog.isDef(head.next)) {\r\n head = head.next;\r\n var cb = head.cb;\r\n head.cb = null;\r\n cb();\r\n }\r\n };\r\n return function(cb) {\r\n tail.next = {cb: cb};\r\n tail = tail.next;\r\n channel['port2'].postMessage(0);\r\n };\r\n }\r\n // Implementation for IE6 to IE10: Script elements fire an asynchronous\r\n // onreadystatechange event when inserted into the DOM.\r\n if (typeof document !== 'undefined' &&\r\n 'onreadystatechange' in\r\n document.createElement(String(goog.dom.TagName.SCRIPT))) {\r\n return function(cb) {\r\n var script = /** @type {!HTMLScriptElement} */ (\r\n document.createElement(String(goog.dom.TagName.SCRIPT)));\r\n script.onreadystatechange = function() {\r\n // Clean up and call the callback.\r\n script.onreadystatechange = null;\r\n script.parentNode.removeChild(script);\r\n script = null;\r\n cb();\r\n cb = null;\r\n };\r\n document.documentElement.appendChild(script);\r\n };\r\n }\r\n // Fall back to setTimeout with 0. In browsers this creates a delay of 5ms\r\n // or more.\r\n // NOTE(user): This fallback is used for IE11.\r\n return function(cb) {\r\n goog.global.setTimeout(/** @type {function()} */ (cb), 0);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Helper function that is overrided to protect callbacks with entry point\r\n * monitor if the application monitors entry points.\r\n * @param {function()} callback Callback function to fire as soon as possible.\r\n * @return {function()} The wrapped callback.\r\n * @private\r\n */\r\ngoog.async.nextTick.wrapCallback_ = goog.functions.identity;\r\n\r\n\r\n// Register the callback function as an entry point, so that it can be\r\n// monitored for exception handling, etc. This has to be done in this file\r\n// since it requires special code to handle all browsers.\r\ngoog.debug.entryPointRegistry.register(\r\n /**\r\n * @param {function(!Function): !Function} transformer The transforming\r\n * function.\r\n */\r\n function(transformer) { goog.async.nextTick.wrapCallback_ = transformer; });\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A timer class to which other classes and objects can listen on.\r\n * This is only an abstraction above `setInterval`.\r\n *\r\n * @see ../demos/timers.html\r\n */\r\n\r\ngoog.provide('goog.Timer');\r\n\r\ngoog.require('goog.Promise');\r\ngoog.require('goog.events.EventTarget');\r\n\r\n\r\n\r\n/**\r\n * Class for handling timing events.\r\n *\r\n * @param {number=} opt_interval Number of ms between ticks (default: 1ms).\r\n * @param {Object=} opt_timerObject An object that has `setTimeout`,\r\n * `setInterval`, `clearTimeout` and `clearInterval`\r\n * (e.g., `window`).\r\n * @constructor\r\n * @extends {goog.events.EventTarget}\r\n */\r\ngoog.Timer = function(opt_interval, opt_timerObject) {\r\n goog.events.EventTarget.call(this);\r\n\r\n /**\r\n * Number of ms between ticks\r\n * @private {number}\r\n */\r\n this.interval_ = opt_interval || 1;\r\n\r\n /**\r\n * An object that implements `setTimeout`, `setInterval`,\r\n * `clearTimeout` and `clearInterval`. We default to the window\r\n * object. Changing this on {@link goog.Timer.prototype} changes the object\r\n * for all timer instances which can be useful if your environment has some\r\n * other implementation of timers than the `window` object.\r\n * @private {{setTimeout:!Function, clearTimeout:!Function}}\r\n */\r\n this.timerObject_ = /** @type {{setTimeout, clearTimeout}} */ (\r\n opt_timerObject || goog.Timer.defaultTimerObject);\r\n\r\n /**\r\n * Cached `tick_` bound to the object for later use in the timer.\r\n * @private {Function}\r\n * @const\r\n */\r\n this.boundTick_ = goog.bind(this.tick_, this);\r\n\r\n /**\r\n * Firefox browser often fires the timer event sooner (sometimes MUCH sooner)\r\n * than the requested timeout. So we compare the time to when the event was\r\n * last fired, and reschedule if appropriate. See also\r\n * {@link goog.Timer.intervalScale}.\r\n * @private {number}\r\n */\r\n this.last_ = goog.now();\r\n};\r\ngoog.inherits(goog.Timer, goog.events.EventTarget);\r\n\r\n\r\n/**\r\n * Maximum timeout value.\r\n *\r\n * Timeout values too big to fit into a signed 32-bit integer may cause overflow\r\n * in FF, Safari, and Chrome, resulting in the timeout being scheduled\r\n * immediately. It makes more sense simply not to schedule these timeouts, since\r\n * 24.8 days is beyond a reasonable expectation for the browser to stay open.\r\n *\r\n * @private {number}\r\n * @const\r\n */\r\ngoog.Timer.MAX_TIMEOUT_ = 2147483647;\r\n\r\n\r\n/**\r\n * A timer ID that cannot be returned by any known implementation of\r\n * `window.setTimeout`. Passing this value to `window.clearTimeout`\r\n * should therefore be a no-op.\r\n *\r\n * @private {number}\r\n * @const\r\n */\r\ngoog.Timer.INVALID_TIMEOUT_ID_ = -1;\r\n\r\n\r\n/**\r\n * Whether this timer is enabled\r\n * @type {boolean}\r\n */\r\ngoog.Timer.prototype.enabled = false;\r\n\r\n\r\n/**\r\n * An object that implements `setTimeout`, `setInterval`,\r\n * `clearTimeout` and `clearInterval`. We default to the global\r\n * object. Changing `goog.Timer.defaultTimerObject` changes the object for\r\n * all timer instances which can be useful if your environment has some other\r\n * implementation of timers you'd like to use.\r\n * @type {{setTimeout, clearTimeout}}\r\n */\r\ngoog.Timer.defaultTimerObject = goog.global;\r\n\r\n\r\n/**\r\n * Variable that controls the timer error correction. If the timer is called\r\n * before the requested interval times `intervalScale`, which often\r\n * happens on Mozilla, the timer is rescheduled.\r\n * @see {@link #last_}\r\n * @type {number}\r\n */\r\ngoog.Timer.intervalScale = 0.8;\r\n\r\n\r\n/**\r\n * Variable for storing the result of `setInterval`.\r\n * @private {?number}\r\n */\r\ngoog.Timer.prototype.timer_ = null;\r\n\r\n\r\n/**\r\n * Gets the interval of the timer.\r\n * @return {number} interval Number of ms between ticks.\r\n */\r\ngoog.Timer.prototype.getInterval = function() {\r\n return this.interval_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the interval of the timer.\r\n * @param {number} interval Number of ms between ticks.\r\n */\r\ngoog.Timer.prototype.setInterval = function(interval) {\r\n this.interval_ = interval;\r\n if (this.timer_ && this.enabled) {\r\n // Stop and then start the timer to reset the interval.\r\n this.stop();\r\n this.start();\r\n } else if (this.timer_) {\r\n this.stop();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Callback for the `setTimeout` used by the timer.\r\n * @private\r\n */\r\ngoog.Timer.prototype.tick_ = function() {\r\n if (this.enabled) {\r\n var elapsed = goog.now() - this.last_;\r\n if (elapsed > 0 && elapsed < this.interval_ * goog.Timer.intervalScale) {\r\n this.timer_ = this.timerObject_.setTimeout(\r\n this.boundTick_, this.interval_ - elapsed);\r\n return;\r\n }\r\n\r\n // Prevents setInterval from registering a duplicate timeout when called\r\n // in the timer event handler.\r\n if (this.timer_) {\r\n this.timerObject_.clearTimeout(this.timer_);\r\n this.timer_ = null;\r\n }\r\n\r\n this.dispatchTick();\r\n // The timer could be stopped in the timer event handler.\r\n if (this.enabled) {\r\n // Stop and start to ensure there is always only one timeout even if\r\n // start is called in the timer event handler.\r\n this.stop();\r\n this.start();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Dispatches the TICK event. This is its own method so subclasses can override.\r\n */\r\ngoog.Timer.prototype.dispatchTick = function() {\r\n this.dispatchEvent(goog.Timer.TICK);\r\n};\r\n\r\n\r\n/**\r\n * Starts the timer.\r\n */\r\ngoog.Timer.prototype.start = function() {\r\n this.enabled = true;\r\n\r\n // If there is no interval already registered, start it now\r\n if (!this.timer_) {\r\n // IMPORTANT!\r\n // window.setInterval in FireFox has a bug - it fires based on\r\n // absolute time, rather than on relative time. What this means\r\n // is that if a computer is sleeping/hibernating for 24 hours\r\n // and the timer interval was configured to fire every 1000ms,\r\n // then after the PC wakes up the timer will fire, in rapid\r\n // succession, 3600*24 times.\r\n // This bug is described here and is already fixed, but it will\r\n // take time to propagate, so for now I am switching this over\r\n // to setTimeout logic.\r\n // https://bugzilla.mozilla.org/show_bug.cgi?id=376643\r\n //\r\n this.timer_ = this.timerObject_.setTimeout(this.boundTick_, this.interval_);\r\n this.last_ = goog.now();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Stops the timer.\r\n */\r\ngoog.Timer.prototype.stop = function() {\r\n this.enabled = false;\r\n if (this.timer_) {\r\n this.timerObject_.clearTimeout(this.timer_);\r\n this.timer_ = null;\r\n }\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.Timer.prototype.disposeInternal = function() {\r\n goog.Timer.superClass_.disposeInternal.call(this);\r\n this.stop();\r\n delete this.timerObject_;\r\n};\r\n\r\n\r\n/**\r\n * Constant for the timer's event type.\r\n * @const\r\n */\r\ngoog.Timer.TICK = 'tick';\r\n\r\n\r\n/**\r\n * Calls the given function once, after the optional pause.\r\n * <p>\r\n * The function is always called asynchronously, even if the delay is 0. This\r\n * is a common trick to schedule a function to run after a batch of browser\r\n * event processing.\r\n *\r\n * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function\r\n * or object that has a handleEvent method.\r\n * @param {number=} opt_delay Milliseconds to wait; default is 0.\r\n * @param {SCOPE=} opt_handler Object in whose scope to call the listener.\r\n * @return {number} A handle to the timer ID.\r\n * @template SCOPE\r\n */\r\ngoog.Timer.callOnce = function(listener, opt_delay, opt_handler) {\r\n if (goog.isFunction(listener)) {\r\n if (opt_handler) {\r\n listener = goog.bind(listener, opt_handler);\r\n }\r\n } else if (listener && typeof listener.handleEvent == 'function') {\r\n // using typeof to prevent strict js warning\r\n listener = goog.bind(listener.handleEvent, listener);\r\n } else {\r\n throw new Error('Invalid listener argument');\r\n }\r\n\r\n if (Number(opt_delay) > goog.Timer.MAX_TIMEOUT_) {\r\n // Timeouts greater than MAX_INT return immediately due to integer\r\n // overflow in many browsers. Since MAX_INT is 24.8 days, just don't\r\n // schedule anything at all.\r\n return goog.Timer.INVALID_TIMEOUT_ID_;\r\n } else {\r\n return goog.Timer.defaultTimerObject.setTimeout(listener, opt_delay || 0);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears a timeout initiated by {@link #callOnce}.\r\n * @param {?number} timerId A timer ID.\r\n */\r\ngoog.Timer.clear = function(timerId) {\r\n goog.Timer.defaultTimerObject.clearTimeout(timerId);\r\n};\r\n\r\n\r\n/**\r\n * @param {number} delay Milliseconds to wait.\r\n * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value\r\n * with which the promise will be resolved.\r\n * @return {!goog.Promise<RESULT>} A promise that will be resolved after\r\n * the specified delay, unless it is canceled first.\r\n * @template RESULT\r\n */\r\ngoog.Timer.promise = function(delay, opt_result) {\r\n var timerKey = null;\r\n return new goog\r\n .Promise(function(resolve, reject) {\r\n timerKey =\r\n goog.Timer.callOnce(function() { resolve(opt_result); }, delay);\r\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\r\n reject(new Error('Failed to schedule timer.'));\r\n }\r\n })\r\n .thenCatch(function(error) {\r\n // Clear the timer. The most likely reason is \"cancel\" signal.\r\n goog.Timer.clear(timerKey);\r\n throw error;\r\n });\r\n};\r\n","// Copyright 2007 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Definition of the goog.async.Throttle class.\r\n *\r\n * @see ../demos/timers.html\r\n */\r\n\r\ngoog.provide('goog.Throttle');\r\ngoog.provide('goog.async.Throttle');\r\n\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.Timer');\r\n\r\n\r\n\r\n/**\r\n * Throttle will perform an action that is passed in no more than once\r\n * per interval (specified in milliseconds). If it gets multiple signals\r\n * to perform the action while it is waiting, it will only perform the action\r\n * once at the end of the interval.\r\n * @param {function(this: T, ...?)} listener Function to callback when the\r\n * action is triggered.\r\n * @param {number} interval Interval over which to throttle. The listener can\r\n * only be called once per interval.\r\n * @param {T=} opt_handler Object in whose scope to call the listener.\r\n * @constructor\r\n * @struct\r\n * @extends {goog.Disposable}\r\n * @final\r\n * @template T\r\n */\r\ngoog.async.Throttle = function(listener, interval, opt_handler) {\r\n goog.async.Throttle.base(this, 'constructor');\r\n\r\n /**\r\n * Function to callback\r\n * @type {function(this: T, ...?)}\r\n * @private\r\n */\r\n this.listener_ =\r\n opt_handler != null ? goog.bind(listener, opt_handler) : listener;\r\n\r\n /**\r\n * Interval for the throttle time\r\n * @type {number}\r\n * @private\r\n */\r\n this.interval_ = interval;\r\n\r\n /**\r\n * Cached callback function invoked after the throttle timeout completes\r\n * @type {Function}\r\n * @private\r\n */\r\n this.callback_ = goog.bind(this.onTimer_, this);\r\n\r\n /**\r\n * The last arguments passed into `fire`.\r\n * @private {!IArrayLike}\r\n */\r\n this.args_ = [];\r\n};\r\ngoog.inherits(goog.async.Throttle, goog.Disposable);\r\n\r\n\r\n\r\n/**\r\n * A deprecated alias.\r\n * @deprecated Use goog.async.Throttle instead.\r\n * @constructor\r\n * @final\r\n */\r\ngoog.Throttle = goog.async.Throttle;\r\n\r\n\r\n/**\r\n * Indicates that the action is pending and needs to be fired.\r\n * @type {boolean}\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.shouldFire_ = false;\r\n\r\n\r\n/**\r\n * Indicates the count of nested pauses currently in effect on the throttle.\r\n * When this count is not zero, fired actions will be postponed until the\r\n * throttle is resumed enough times to drop the pause count to zero.\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.pauseCount_ = 0;\r\n\r\n\r\n/**\r\n * Timer for scheduling the next callback\r\n * @type {?number}\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.timer_ = null;\r\n\r\n\r\n/**\r\n * Notifies the throttle that the action has happened. It will throttle the call\r\n * so that the callback is not called too often according to the interval\r\n * parameter passed to the constructor, passing the arguments from the last call\r\n * of this function into the throttled function.\r\n * @param {...?} var_args Arguments to pass on to the throttled function.\r\n */\r\ngoog.async.Throttle.prototype.fire = function(var_args) {\r\n this.args_ = arguments;\r\n if (!this.timer_ && !this.pauseCount_) {\r\n this.doAction_();\r\n } else {\r\n this.shouldFire_ = true;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Cancels any pending action callback. The throttle can be restarted by\r\n * calling {@link #fire}.\r\n */\r\ngoog.async.Throttle.prototype.stop = function() {\r\n if (this.timer_) {\r\n goog.Timer.clear(this.timer_);\r\n this.timer_ = null;\r\n this.shouldFire_ = false;\r\n this.args_ = [];\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Pauses the throttle. All pending and future action callbacks will be\r\n * delayed until the throttle is resumed. Pauses can be nested.\r\n */\r\ngoog.async.Throttle.prototype.pause = function() {\r\n this.pauseCount_++;\r\n};\r\n\r\n\r\n/**\r\n * Resumes the throttle. If doing so drops the pausing count to zero, pending\r\n * action callbacks will be executed as soon as possible, but still no sooner\r\n * than an interval's delay after the previous call. Future action callbacks\r\n * will be executed as normal.\r\n */\r\ngoog.async.Throttle.prototype.resume = function() {\r\n this.pauseCount_--;\r\n if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {\r\n this.shouldFire_ = false;\r\n this.doAction_();\r\n }\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.async.Throttle.prototype.disposeInternal = function() {\r\n goog.async.Throttle.base(this, 'disposeInternal');\r\n this.stop();\r\n};\r\n\r\n\r\n/**\r\n * Handler for the timer to fire the throttle\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.onTimer_ = function() {\r\n this.timer_ = null;\r\n\r\n if (this.shouldFire_ && !this.pauseCount_) {\r\n this.shouldFire_ = false;\r\n this.doAction_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls the callback\r\n * @private\r\n */\r\ngoog.async.Throttle.prototype.doAction_ = function() {\r\n this.timer_ = goog.Timer.callOnce(this.callback_, this.interval_);\r\n this.listener_.apply(null, this.args_);\r\n};\r\n","// Copyright 2005 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Class to create objects which want to handle multiple events\r\n * and have their listeners easily cleaned up via a dispose method.\r\n *\r\n * Example:\r\n * <pre>\r\n * function Something() {\r\n * Something.base(this);\r\n *\r\n * ... set up object ...\r\n *\r\n * // Add event listeners\r\n * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);\r\n * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);\r\n * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);\r\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);\r\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);\r\n * }\r\n * goog.inherits(Something, goog.events.EventHandler);\r\n *\r\n * Something.prototype.disposeInternal = function() {\r\n * Something.base(this, 'disposeInternal');\r\n * goog.dom.removeNode(this.container);\r\n * };\r\n *\r\n *\r\n * // Then elsewhere:\r\n *\r\n * var activeSomething = null;\r\n * function openSomething() {\r\n * activeSomething = new Something();\r\n * }\r\n *\r\n * function closeSomething() {\r\n * if (activeSomething) {\r\n * activeSomething.dispose(); // Remove event listeners\r\n * activeSomething = null;\r\n * }\r\n * }\r\n * </pre>\r\n *\r\n */\r\n\r\ngoog.provide('goog.events.EventHandler');\r\n\r\ngoog.require('goog.Disposable');\r\ngoog.require('goog.events');\r\ngoog.require('goog.object');\r\n\r\ngoog.forwardDeclare('goog.events.EventWrapper');\r\n\r\n\r\n\r\n/**\r\n * Super class for objects that want to easily manage a number of event\r\n * listeners. It allows a short cut to listen and also provides a quick way\r\n * to remove all events listeners belonging to this object.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.\r\n * @constructor\r\n * @extends {goog.Disposable}\r\n * @template SCOPE\r\n */\r\ngoog.events.EventHandler = function(opt_scope) {\r\n goog.Disposable.call(this);\r\n // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3\r\n // that access this private variable. :(\r\n this.handler_ = opt_scope;\r\n\r\n /**\r\n * Keys for events that are being listened to.\r\n * @type {!Object<!goog.events.Key>}\r\n * @private\r\n */\r\n this.keys_ = {};\r\n};\r\ngoog.inherits(goog.events.EventHandler, goog.Disposable);\r\n\r\n\r\n/**\r\n * Utility array used to unify the cases of listening for an array of types\r\n * and listening for a single event, without using recursion or allocating\r\n * an array each time.\r\n * @type {!Array<string>}\r\n * @const\r\n * @private\r\n */\r\ngoog.events.EventHandler.typeArray_ = [];\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted then the\r\n * EventHandler's handleEvent method will be used.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\r\n * opt_fn Optional callback function to be used as the listener or an object\r\n * with handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listen = function(\r\n src, type, opt_fn, opt_options) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n return self.listen_(src, type, opt_fn, opt_options);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted then the\r\n * EventHandler's handleEvent method will be used.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\r\n * null|undefined} fn Optional callback function to be used as the\r\n * listener or an object with handleEvent function.\r\n * @param {boolean|!AddEventListenerOptions|undefined} options\r\n * @param {T} scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template T, EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenWithScope = function(\r\n src, type, fn, options, scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Deprecate this function.\r\n return self.listen_(src, type, fn, options, scope);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted then the\r\n * EventHandler's handleEvent method will be used.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\r\n * Optional callback function to be used as the listener or an object with\r\n * handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {Object=} opt_scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n * @private\r\n */\r\ngoog.events.EventHandler.prototype.listen_ = function(\r\n src, type, opt_fn, opt_options, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n if (!goog.isArray(type)) {\r\n if (type) {\r\n goog.events.EventHandler.typeArray_[0] = type.toString();\r\n }\r\n type = goog.events.EventHandler.typeArray_;\r\n }\r\n for (var i = 0; i < type.length; i++) {\r\n var listenerObj = goog.events.listen(\r\n src, type[i], opt_fn || self.handleEvent, opt_options || false,\r\n opt_scope || self.handler_ || self);\r\n\r\n if (!listenerObj) {\r\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\r\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\r\n // value.\r\n return self;\r\n }\r\n\r\n var key = listenerObj.key;\r\n self.keys_[key] = listenerObj;\r\n }\r\n\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted, then the\r\n * EventHandler's handleEvent method will be used. After the event has fired the\r\n * event listener is removed from the target. If an array of event types is\r\n * provided, each event type will be listened to once.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\r\n * opt_fn\r\n * Optional callback function to be used as the listener or an object with\r\n * handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenOnce = function(\r\n src, type, opt_fn, opt_options) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n return self.listenOnce_(src, type, opt_fn, opt_options);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted, then the\r\n * EventHandler's handleEvent method will be used. After the event has fired the\r\n * event listener is removed from the target. If an array of event types is\r\n * provided, each event type will be listened to once.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\r\n * null|undefined} fn Optional callback function to be used as the\r\n * listener or an object with handleEvent function.\r\n * @param {boolean|undefined} capture Optional whether to use capture phase.\r\n * @param {T} scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template T, EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenOnceWithScope = function(\r\n src, type, fn, capture, scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Deprecate this function.\r\n return self.listenOnce_(src, type, fn, capture, scope);\r\n};\r\n\r\n\r\n/**\r\n * Listen to an event on a Listenable. If the function is omitted, then the\r\n * EventHandler's handleEvent method will be used. After the event has fired\r\n * the event listener is removed from the target. If an array of event types is\r\n * provided, each event type will be listened to once.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type to listen for or array of event types.\r\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\r\n * Optional callback function to be used as the listener or an object with\r\n * handleEvent function.\r\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\r\n * @param {Object=} opt_scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n * @private\r\n */\r\ngoog.events.EventHandler.prototype.listenOnce_ = function(\r\n src, type, opt_fn, opt_options, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n self.listenOnce_(src, type[i], opt_fn, opt_options, opt_scope);\r\n }\r\n } else {\r\n var listenerObj = goog.events.listenOnce(\r\n src, type, opt_fn || self.handleEvent, opt_options,\r\n opt_scope || self.handler_ || self);\r\n if (!listenerObj) {\r\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\r\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\r\n // value.\r\n return self;\r\n }\r\n\r\n var key = listenerObj.key;\r\n self.keys_[key] = listenerObj;\r\n }\r\n\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.EventTarget}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\r\n * events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener\r\n * Callback method, or an object with a handleEvent function.\r\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\r\n * false).\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenWithWrapper = function(\r\n src, wrapper, listener, opt_capt) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Remove the opt_scope from this function and then\r\n // templatize it.\r\n return self.listenWithWrapper_(src, wrapper, listener, opt_capt);\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.EventTarget}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\r\n * events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}\r\n * listener Optional callback function to be used as the\r\n * listener or an object with handleEvent function.\r\n * @param {boolean|undefined} capture Optional whether to use capture phase.\r\n * @param {T} scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template T, THIS\r\n */\r\ngoog.events.EventHandler.prototype.listenWithWrapperAndScope = function(\r\n src, wrapper, listener, capture, scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n // TODO(mknichel): Deprecate this function.\r\n return self.listenWithWrapper_(src, wrapper, listener, capture, scope);\r\n};\r\n\r\n\r\n/**\r\n * Adds an event listener with a specific event wrapper on a DOM Node or an\r\n * object that has implemented {@link goog.events.EventTarget}. A listener can\r\n * only be added once to an object.\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\r\n * events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback\r\n * method, or an object with a handleEvent function.\r\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\r\n * false).\r\n * @param {Object=} opt_scope Element in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template THIS\r\n * @private\r\n */\r\ngoog.events.EventHandler.prototype.listenWithWrapper_ = function(\r\n src, wrapper, listener, opt_capt, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n wrapper.listen(\r\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} Number of listeners registered by this handler.\r\n */\r\ngoog.events.EventHandler.prototype.getListenerCount = function() {\r\n var count = 0;\r\n for (var key in this.keys_) {\r\n if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {\r\n count++;\r\n }\r\n }\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Unlistens on an event.\r\n * @param {goog.events.ListenableType} src Event source.\r\n * @param {string|Array<string>|\r\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\r\n * type Event type or array of event types to unlisten to.\r\n * @param {function(this:?, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\r\n * opt_fn Optional callback function to be used as the listener or an object\r\n * with handleEvent function.\r\n * @param {(boolean|!EventListenerOptions)=} opt_options\r\n * @param {Object=} opt_scope Object in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template EVENTOBJ, THIS\r\n */\r\ngoog.events.EventHandler.prototype.unlisten = function(\r\n src, type, opt_fn, opt_options, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n if (goog.isArray(type)) {\r\n for (var i = 0; i < type.length; i++) {\r\n self.unlisten(src, type[i], opt_fn, opt_options, opt_scope);\r\n }\r\n } else {\r\n var capture =\r\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\r\n var listener = goog.events.getListener(\r\n src, type, opt_fn || self.handleEvent, capture,\r\n opt_scope || self.handler_ || self);\r\n\r\n if (listener) {\r\n goog.events.unlistenByKey(listener);\r\n delete self.keys_[listener.key];\r\n }\r\n }\r\n\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Removes an event listener which was added with listenWithWrapper().\r\n *\r\n * @param {EventTarget|goog.events.EventTarget} src The target to stop\r\n * listening to events on.\r\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\r\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\r\n * listener function to remove.\r\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\r\n * whether the listener is fired during the capture or bubble phase of the\r\n * event.\r\n * @param {Object=} opt_scope Element in whose scope to call the listener.\r\n * @return {THIS} This object, allowing for chaining of calls.\r\n * @this {THIS}\r\n * @template THIS\r\n */\r\ngoog.events.EventHandler.prototype.unlistenWithWrapper = function(\r\n src, wrapper, listener, opt_capt, opt_scope) {\r\n var self = /** @type {!goog.events.EventHandler} */ (this);\r\n wrapper.unlisten(\r\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\r\n return self;\r\n};\r\n\r\n\r\n/**\r\n * Unlistens to all events.\r\n */\r\ngoog.events.EventHandler.prototype.removeAll = function() {\r\n goog.object.forEach(this.keys_, function(listenerObj, key) {\r\n if (this.keys_.hasOwnProperty(key)) {\r\n goog.events.unlistenByKey(listenerObj);\r\n }\r\n }, this);\r\n\r\n this.keys_ = {};\r\n};\r\n\r\n\r\n/**\r\n * Disposes of this EventHandler and removes all listeners that it registered.\r\n * @override\r\n * @protected\r\n */\r\ngoog.events.EventHandler.prototype.disposeInternal = function() {\r\n goog.events.EventHandler.superClass_.disposeInternal.call(this);\r\n this.removeAll();\r\n};\r\n\r\n\r\n/**\r\n * Default event handler\r\n * @param {goog.events.Event} e Event object.\r\n */\r\ngoog.events.EventHandler.prototype.handleEvent = function(e) {\r\n throw new Error('EventHandler.handleEvent not implemented');\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Provides a utility for tracing and debugging WebChannel\r\n * requests.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.WebChannelDebug');\r\n\r\ngoog.require('goog.json');\r\ngoog.require('goog.log');\r\n\r\ngoog.forwardDeclare('goog.Uri');\r\ngoog.forwardDeclare('goog.net.XmlHttp.ReadyState');\r\n\r\n\r\n\r\n/**\r\n * Logs and keeps a buffer of debugging info for the Channel.\r\n *\r\n * @constructor\r\n * @struct\r\n * @final\r\n */\r\ngoog.labs.net.webChannel.WebChannelDebug = function() {\r\n /**\r\n * The logger instance.\r\n * @const\r\n * @private {?goog.log.Logger}\r\n */\r\n this.logger_ = goog.log.getLogger('goog.labs.net.webChannel.WebChannelDebug');\r\n\r\n /**\r\n * Whether to enable redact. Defaults to true.\r\n * @private {boolean}\r\n */\r\n this.redactEnabled_ = true;\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\n\r\n\r\n/**\r\n * Turns off redact.\r\n */\r\nWebChannelDebug.prototype.disableRedact = function() {\r\n this.redactEnabled_ = false;\r\n};\r\n\r\n\r\n/**\r\n * Logs that the browser went offline during the lifetime of a request.\r\n * @param {goog.Uri} url The URL being requested.\r\n */\r\nWebChannelDebug.prototype.browserOfflineResponse = function(url) {\r\n this.info(function() {\r\n return 'BROWSER_OFFLINE: ' + url;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs an XmlHttp request..\r\n * @param {string} verb The request type (GET/POST).\r\n * @param {goog.Uri} uri The request destination.\r\n * @param {string|number|undefined} id The request id.\r\n * @param {number} attempt Which attempt # the request was.\r\n * @param {?string} postData The data posted in the request.\r\n */\r\nWebChannelDebug.prototype.xmlHttpChannelRequest = function(\r\n verb, uri, id, attempt, postData) {\r\n var self = this;\r\n this.info(function() {\r\n return 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb +\r\n '\\n' + uri + '\\n' + self.maybeRedactPostData_(postData);\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs the meta data received from an XmlHttp request.\r\n * @param {string} verb The request type (GET/POST).\r\n * @param {goog.Uri} uri The request destination.\r\n * @param {string|number|undefined} id The request id.\r\n * @param {number} attempt Which attempt # the request was.\r\n * @param {goog.net.XmlHttp.ReadyState} readyState The ready state.\r\n * @param {number} statusCode The HTTP status code.\r\n */\r\nWebChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(\r\n verb, uri, id, attempt, readyState, statusCode) {\r\n this.info(function() {\r\n return 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb +\r\n '\\n' + uri + '\\n' + readyState + ' ' + statusCode;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs the response data received from an XmlHttp request.\r\n * @param {string|number|undefined} id The request id.\r\n * @param {?string} responseText The response text.\r\n * @param {?string=} opt_desc Optional request description.\r\n */\r\nWebChannelDebug.prototype.xmlHttpChannelResponseText = function(\r\n id, responseText, opt_desc) {\r\n var self = this;\r\n this.info(function() {\r\n return 'XMLHTTP TEXT (' + id + '): ' + self.redactResponse_(responseText) +\r\n (opt_desc ? ' ' + opt_desc : '');\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs a request timeout.\r\n * @param {goog.Uri} uri The uri that timed out.\r\n */\r\nWebChannelDebug.prototype.timeoutResponse = function(uri) {\r\n this.info(function() {\r\n return 'TIMEOUT: ' + uri;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Logs a debug message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.debug = function(text) {\r\n goog.log.fine(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Logs an exception\r\n * @param {Error} e The error or error event.\r\n * @param {goog.debug.Loggable=} opt_msg The optional message,\r\n * defaults to 'Exception'.\r\n */\r\nWebChannelDebug.prototype.dumpException = function(e, opt_msg) {\r\n goog.log.error(this.logger_, opt_msg || 'Exception', e);\r\n};\r\n\r\n\r\n/**\r\n * Logs an info message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.info = function(text) {\r\n goog.log.info(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Logs a warning message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.warning = function(text) {\r\n goog.log.warning(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Logs a severe message.\r\n * @param {!goog.debug.Loggable} text The message.\r\n */\r\nWebChannelDebug.prototype.severe = function(text) {\r\n goog.log.error(this.logger_, text);\r\n};\r\n\r\n\r\n/**\r\n * Removes potentially private data from a response so that we don't\r\n * accidentally save private and personal data to the server logs.\r\n * @param {?string} responseText A JSON response to clean.\r\n * @return {?string} The cleaned response.\r\n * @private\r\n */\r\nWebChannelDebug.prototype.redactResponse_ = function(responseText) {\r\n if (!this.redactEnabled_) {\r\n return responseText;\r\n }\r\n\r\n if (!responseText) {\r\n return null;\r\n }\r\n\r\n try {\r\n var responseArray = JSON.parse(responseText);\r\n if (responseArray) {\r\n for (var i = 0; i < responseArray.length; i++) {\r\n if (goog.isArray(responseArray[i])) {\r\n this.maybeRedactArray_(responseArray[i]);\r\n }\r\n }\r\n }\r\n\r\n return goog.json.serialize(responseArray);\r\n } catch (e) {\r\n this.debug('Exception parsing expected JS array - probably was not JS');\r\n return responseText;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes data from a response array that may be sensitive.\r\n * @param {!Array<?>} array The array to clean.\r\n * @private\r\n */\r\nWebChannelDebug.prototype.maybeRedactArray_ = function(array) {\r\n if (array.length < 2) {\r\n return;\r\n }\r\n var dataPart = array[1];\r\n if (!goog.isArray(dataPart)) {\r\n return;\r\n }\r\n if (dataPart.length < 1) {\r\n return;\r\n }\r\n\r\n var type = dataPart[0];\r\n if (type != 'noop' && type != 'stop' && type != 'close') {\r\n // redact all fields in the array\r\n for (var i = 1; i < dataPart.length; i++) {\r\n dataPart[i] = '';\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes potentially private data from a request POST body so that we don't\r\n * accidentally save private and personal data to the server logs.\r\n * @param {?string} data The data string to clean.\r\n * @return {?string} The data string with sensitive data replaced by 'redacted'.\r\n * @private\r\n */\r\nWebChannelDebug.prototype.maybeRedactPostData_ = function(data) {\r\n if (!this.redactEnabled_) {\r\n return data;\r\n }\r\n\r\n if (!data) {\r\n return null;\r\n }\r\n var out = '';\r\n var params = data.split('&');\r\n for (var i = 0; i < params.length; i++) {\r\n var param = params[i];\r\n var keyValue = param.split('=');\r\n if (keyValue.length > 1) {\r\n var key = keyValue[0];\r\n var value = keyValue[1];\r\n\r\n var keyParts = key.split('_');\r\n if (keyParts.length >= 2 && keyParts[1] == 'type') {\r\n out += key + '=' + value + '&';\r\n } else {\r\n out += key + '=' +\r\n 'redacted' +\r\n '&';\r\n }\r\n }\r\n }\r\n return out;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Static utilities for collecting stats associated with\r\n * ChannelRequest.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.requestStats');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.Event');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachability');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachabilityEvent');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.Stat');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.StatEvent');\r\ngoog.provide('goog.labs.net.webChannel.requestStats.TimingEvent');\r\n\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.EventTarget');\r\n\r\n\r\ngoog.scope(function() {\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\n\r\n\r\n/**\r\n * Events fired.\r\n * @const\r\n */\r\nrequestStats.Event = {};\r\n\r\n\r\n/**\r\n * Singleton event target for firing stat events\r\n * @type {goog.events.EventTarget}\r\n * @private\r\n */\r\nrequestStats.statEventTarget_ = new goog.events.EventTarget();\r\n\r\n\r\n/**\r\n * The type of event that occurs every time some information about how reachable\r\n * the server is is discovered.\r\n */\r\nrequestStats.Event.SERVER_REACHABILITY_EVENT = 'serverreachability';\r\n\r\n\r\n/**\r\n * Types of events which reveal information about the reachability of the\r\n * server.\r\n * @enum {number}\r\n */\r\nrequestStats.ServerReachability = {\r\n REQUEST_MADE: 1,\r\n REQUEST_SUCCEEDED: 2,\r\n REQUEST_FAILED: 3,\r\n BACK_CHANNEL_ACTIVITY: 4 // any response data received\r\n};\r\n\r\n\r\n\r\n/**\r\n * Event class for SERVER_REACHABILITY_EVENT.\r\n *\r\n * @param {goog.events.EventTarget} target The stat event target for\r\n the channel.\r\n * @param {requestStats.ServerReachability} reachabilityType\r\n * The reachability event type.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\nrequestStats.ServerReachabilityEvent = function(target, reachabilityType) {\r\n goog.events.Event.call(\r\n this, requestStats.Event.SERVER_REACHABILITY_EVENT, target);\r\n\r\n /**\r\n * @type {requestStats.ServerReachability}\r\n */\r\n this.reachabilityType = reachabilityType;\r\n};\r\ngoog.inherits(requestStats.ServerReachabilityEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Notify the channel that a particular fine grained network event has occurred.\r\n * Should be considered package-private.\r\n * @param {requestStats.ServerReachability} reachabilityType\r\n * The reachability event type.\r\n */\r\nrequestStats.notifyServerReachabilityEvent = function(reachabilityType) {\r\n var target = requestStats.statEventTarget_;\r\n target.dispatchEvent(\r\n new requestStats.ServerReachabilityEvent(target, reachabilityType));\r\n};\r\n\r\n\r\n/**\r\n * Stat Event that fires when things of interest happen that may be useful for\r\n * applications to know about for stats or debugging purposes.\r\n */\r\nrequestStats.Event.STAT_EVENT = 'statevent';\r\n\r\n\r\n/**\r\n * Enum that identifies events for statistics that are interesting to track.\r\n * @enum {number}\r\n */\r\nrequestStats.Stat = {\r\n /** Event indicating a new connection attempt. */\r\n CONNECT_ATTEMPT: 0,\r\n\r\n /** Event indicating a connection error due to a general network problem. */\r\n ERROR_NETWORK: 1,\r\n\r\n /**\r\n * Event indicating a connection error that isn't due to a general network\r\n * problem.\r\n */\r\n ERROR_OTHER: 2,\r\n\r\n /** Event indicating the start of test stage one. */\r\n TEST_STAGE_ONE_START: 3,\r\n\r\n /** Event indicating the start of test stage two. */\r\n TEST_STAGE_TWO_START: 4,\r\n\r\n /** Event indicating the first piece of test data was received. */\r\n TEST_STAGE_TWO_DATA_ONE: 5,\r\n\r\n /**\r\n * Event indicating that the second piece of test data was received and it was\r\n * received separately from the first.\r\n */\r\n TEST_STAGE_TWO_DATA_TWO: 6,\r\n\r\n /** Event indicating both pieces of test data were received simultaneously. */\r\n TEST_STAGE_TWO_DATA_BOTH: 7,\r\n\r\n /** Event indicating stage one of the test request failed. */\r\n TEST_STAGE_ONE_FAILED: 8,\r\n\r\n /** Event indicating stage two of the test request failed. */\r\n TEST_STAGE_TWO_FAILED: 9,\r\n\r\n /**\r\n * Event indicating that a buffering proxy is likely between the client and\r\n * the server.\r\n */\r\n PROXY: 10,\r\n\r\n /**\r\n * Event indicating that no buffering proxy is likely between the client and\r\n * the server.\r\n */\r\n NOPROXY: 11,\r\n\r\n /** Event indicating an unknown SID error. */\r\n REQUEST_UNKNOWN_SESSION_ID: 12,\r\n\r\n /** Event indicating a bad status code was received. */\r\n REQUEST_BAD_STATUS: 13,\r\n\r\n /** Event indicating incomplete data was received */\r\n REQUEST_INCOMPLETE_DATA: 14,\r\n\r\n /** Event indicating bad data was received */\r\n REQUEST_BAD_DATA: 15,\r\n\r\n /** Event indicating no data was received when data was expected. */\r\n REQUEST_NO_DATA: 16,\r\n\r\n /** Event indicating a request timeout. */\r\n REQUEST_TIMEOUT: 17,\r\n\r\n /**\r\n * Event indicating that the server never received our hanging GET and so it\r\n * is being retried.\r\n */\r\n BACKCHANNEL_MISSING: 18,\r\n\r\n /**\r\n * Event indicating that we have determined that our hanging GET is not\r\n * receiving data when it should be. Thus it is dead dead and will be retried.\r\n */\r\n BACKCHANNEL_DEAD: 19,\r\n\r\n /**\r\n * The browser declared itself offline during the lifetime of a request, or\r\n * was offline when a request was initially made.\r\n */\r\n BROWSER_OFFLINE: 20\r\n};\r\n\r\n\r\n\r\n/**\r\n * Event class for STAT_EVENT.\r\n *\r\n * @param {goog.events.EventTarget} eventTarget The stat event target for\r\n the channel.\r\n * @param {requestStats.Stat} stat The stat.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\nrequestStats.StatEvent = function(eventTarget, stat) {\r\n goog.events.Event.call(this, requestStats.Event.STAT_EVENT, eventTarget);\r\n\r\n /**\r\n * The stat\r\n * @type {requestStats.Stat}\r\n */\r\n this.stat = stat;\r\n\r\n};\r\ngoog.inherits(requestStats.StatEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Returns the singleton event target for stat events.\r\n * @return {goog.events.EventTarget} The event target for stat events.\r\n */\r\nrequestStats.getStatEventTarget = function() {\r\n return requestStats.statEventTarget_;\r\n};\r\n\r\n\r\n/**\r\n * Helper function to call the stat event callback.\r\n * @param {requestStats.Stat} stat The stat.\r\n */\r\nrequestStats.notifyStatEvent = function(stat) {\r\n var target = requestStats.statEventTarget_;\r\n target.dispatchEvent(new requestStats.StatEvent(target, stat));\r\n};\r\n\r\n\r\n/**\r\n * An event that fires when POST requests complete successfully, indicating\r\n * the size of the POST and the round trip time.\r\n */\r\nrequestStats.Event.TIMING_EVENT = 'timingevent';\r\n\r\n\r\n\r\n/**\r\n * Event class for requestStats.Event.TIMING_EVENT\r\n *\r\n * @param {goog.events.EventTarget} target The stat event target for\r\n the channel.\r\n * @param {number} size The number of characters in the POST data.\r\n * @param {number} rtt The total round trip time from POST to response in MS.\r\n * @param {number} retries The number of times the POST had to be retried.\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\nrequestStats.TimingEvent = function(target, size, rtt, retries) {\r\n goog.events.Event.call(this, requestStats.Event.TIMING_EVENT, target);\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.size = size;\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.rtt = rtt;\r\n\r\n /**\r\n * @type {number}\r\n */\r\n this.retries = retries;\r\n\r\n};\r\ngoog.inherits(requestStats.TimingEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * Helper function to notify listeners about POST request performance.\r\n *\r\n * @param {number} size Number of characters in the POST data.\r\n * @param {number} rtt The amount of time from POST start to response.\r\n * @param {number} retries The number of times the POST had to be retried.\r\n */\r\nrequestStats.notifyTimingEvent = function(size, rtt, retries) {\r\n var target = requestStats.statEventTarget_;\r\n target.dispatchEvent(\r\n new requestStats.TimingEvent(target, size, rtt, retries));\r\n};\r\n\r\n\r\n/**\r\n * Allows the application to set an execution hooks for when a channel\r\n * starts processing requests. This is useful to track timing or logging\r\n * special information. The function takes no parameters and return void.\r\n * @param {Function} startHook The function for the start hook.\r\n */\r\nrequestStats.setStartThreadExecutionHook = function(startHook) {\r\n requestStats.startExecutionHook_ = startHook;\r\n};\r\n\r\n\r\n/**\r\n * Allows the application to set an execution hooks for when a channel\r\n * stops processing requests. This is useful to track timing or logging\r\n * special information. The function takes no parameters and return void.\r\n * @param {Function} endHook The function for the end hook.\r\n */\r\nrequestStats.setEndThreadExecutionHook = function(endHook) {\r\n requestStats.endExecutionHook_ = endHook;\r\n};\r\n\r\n\r\n/**\r\n * Application provided execution hook for the start hook.\r\n *\r\n * @type {Function}\r\n * @private\r\n */\r\nrequestStats.startExecutionHook_ = function() {};\r\n\r\n\r\n/**\r\n * Application provided execution hook for the end hook.\r\n *\r\n * @type {Function}\r\n * @private\r\n */\r\nrequestStats.endExecutionHook_ = function() {};\r\n\r\n\r\n/**\r\n * Helper function to call the start hook\r\n */\r\nrequestStats.onStartExecution = function() {\r\n requestStats.startExecutionHook_();\r\n};\r\n\r\n\r\n/**\r\n * Helper function to call the end hook\r\n */\r\nrequestStats.onEndExecution = function() {\r\n requestStats.endExecutionHook_();\r\n};\r\n\r\n\r\n/**\r\n * Wrapper around SafeTimeout which calls the start and end execution hooks\r\n * with a try...finally block.\r\n * @param {Function} fn The callback function.\r\n * @param {number} ms The time in MS for the timer.\r\n * @return {number} The ID of the timer.\r\n */\r\nrequestStats.setTimeout = function(fn, ms) {\r\n if (!goog.isFunction(fn)) {\r\n throw new Error('Fn must not be null and must be a function');\r\n }\r\n return goog.global.setTimeout(function() {\r\n requestStats.onStartExecution();\r\n try {\r\n fn();\r\n } finally {\r\n requestStats.onEndExecution();\r\n }\r\n }, ms);\r\n};\r\n}); // goog.scope\r\n","// Copyright 2007 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Error codes shared between goog.net.IframeIo and\r\n * goog.net.XhrIo.\r\n */\r\n\r\ngoog.provide('goog.net.ErrorCode');\r\n\r\n\r\n/**\r\n * Error codes\r\n * @enum {number}\r\n */\r\ngoog.net.ErrorCode = {\r\n\r\n /**\r\n * There is no error condition.\r\n */\r\n NO_ERROR: 0,\r\n\r\n /**\r\n * The most common error from iframeio, unfortunately, is that the browser\r\n * responded with an error page that is classed as a different domain. The\r\n * situations, are when a browser error page is shown -- 404, access denied,\r\n * DNS failure, connection reset etc.)\r\n *\r\n */\r\n ACCESS_DENIED: 1,\r\n\r\n /**\r\n * Currently the only case where file not found will be caused is when the\r\n * code is running on the local file system and a non-IE browser makes a\r\n * request to a file that doesn't exist.\r\n */\r\n FILE_NOT_FOUND: 2,\r\n\r\n /**\r\n * If Firefox shows a browser error page, such as a connection reset by\r\n * server or access denied, then it will fail silently without the error or\r\n * load handlers firing.\r\n */\r\n FF_SILENT_ERROR: 3,\r\n\r\n /**\r\n * Custom error provided by the client through the error check hook.\r\n */\r\n CUSTOM_ERROR: 4,\r\n\r\n /**\r\n * Exception was thrown while processing the request.\r\n */\r\n EXCEPTION: 5,\r\n\r\n /**\r\n * The Http response returned a non-successful http status code.\r\n */\r\n HTTP_ERROR: 6,\r\n\r\n /**\r\n * The request was aborted.\r\n */\r\n ABORT: 7,\r\n\r\n /**\r\n * The request timed out.\r\n */\r\n TIMEOUT: 8,\r\n\r\n /**\r\n * The resource is not available offline.\r\n */\r\n OFFLINE: 9\r\n};\r\n\r\n\r\n/**\r\n * Returns a friendly error message for an error code. These messages are for\r\n * debugging and are not localized.\r\n * @param {goog.net.ErrorCode} errorCode An error code.\r\n * @return {string} A message for debugging.\r\n */\r\ngoog.net.ErrorCode.getDebugMessage = function(errorCode) {\r\n switch (errorCode) {\r\n case goog.net.ErrorCode.NO_ERROR:\r\n return 'No Error';\r\n\r\n case goog.net.ErrorCode.ACCESS_DENIED:\r\n return 'Access denied to content document';\r\n\r\n case goog.net.ErrorCode.FILE_NOT_FOUND:\r\n return 'File not found';\r\n\r\n case goog.net.ErrorCode.FF_SILENT_ERROR:\r\n return 'Firefox silently errored';\r\n\r\n case goog.net.ErrorCode.CUSTOM_ERROR:\r\n return 'Application custom error';\r\n\r\n case goog.net.ErrorCode.EXCEPTION:\r\n return 'An exception occurred';\r\n\r\n case goog.net.ErrorCode.HTTP_ERROR:\r\n return 'Http response at 400 or 500 level';\r\n\r\n case goog.net.ErrorCode.ABORT:\r\n return 'Request was aborted';\r\n\r\n case goog.net.ErrorCode.TIMEOUT:\r\n return 'Request timed out';\r\n\r\n case goog.net.ErrorCode.OFFLINE:\r\n return 'The resource is not available offline';\r\n\r\n default:\r\n return 'Unrecognized error code';\r\n }\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Common events for the network classes.\r\n */\r\n\r\n\r\ngoog.provide('goog.net.EventType');\r\n\r\n\r\n/**\r\n * Event names for network events\r\n * @enum {string}\r\n */\r\ngoog.net.EventType = {\r\n COMPLETE: 'complete',\r\n SUCCESS: 'success',\r\n ERROR: 'error',\r\n ABORT: 'abort',\r\n READY: 'ready',\r\n READY_STATE_CHANGE: 'readystatechange',\r\n TIMEOUT: 'timeout',\r\n INCREMENTAL_DATA: 'incrementaldata',\r\n PROGRESS: 'progress',\r\n // DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by\r\n // goog.net.XhrIo to allow binding listeners specific to each type of\r\n // progress.\r\n DOWNLOAD_PROGRESS: 'downloadprogress',\r\n UPLOAD_PROGRESS: 'uploadprogress'\r\n};\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Interface for a factory for creating XMLHttpRequest objects\r\n * and metadata about them.\r\n * @author dbk@google.com (David Barrett-Kahn)\r\n */\r\n\r\ngoog.provide('goog.net.XmlHttpFactory');\r\n\r\n/** @suppress {extraRequire} Typedef. */\r\ngoog.require('goog.net.XhrLike');\r\n\r\n\r\n\r\n/**\r\n * Abstract base class for an XmlHttpRequest factory.\r\n * @constructor\r\n */\r\ngoog.net.XmlHttpFactory = function() {};\r\n\r\n\r\n/**\r\n * Cache of options - we only actually call internalGetOptions once.\r\n * @type {?Object}\r\n * @private\r\n */\r\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\r\n\r\n\r\n/**\r\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\r\n */\r\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @return {Object} Options describing how xhr objects obtained from this\r\n * factory should be used.\r\n */\r\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\r\n return this.cachedOptions_ ||\r\n (this.cachedOptions_ = this.internalGetOptions());\r\n};\r\n\r\n\r\n/**\r\n * Override this method in subclasses to preserve the caching offered by\r\n * getOptions().\r\n * @return {Object} Options describing how xhr objects obtained from this\r\n * factory should be used.\r\n * @protected\r\n */\r\ngoog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Low level handling of XMLHttpRequest.\r\n * @author arv@google.com (Erik Arvidsson)\r\n * @author dbk@google.com (David Barrett-Kahn)\r\n */\r\n\r\ngoog.provide('goog.net.DefaultXmlHttpFactory');\r\ngoog.provide('goog.net.XmlHttp');\r\ngoog.provide('goog.net.XmlHttp.OptionType');\r\ngoog.provide('goog.net.XmlHttp.ReadyState');\r\ngoog.provide('goog.net.XmlHttpDefines');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.net.WrapperXmlHttpFactory');\r\ngoog.require('goog.net.XmlHttpFactory');\r\n\r\n\r\n/**\r\n * Static class for creating XMLHttpRequest objects.\r\n * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.\r\n */\r\ngoog.net.XmlHttp = function() {\r\n return goog.net.XmlHttp.factory_.createInstance();\r\n};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\r\n * true bypasses the ActiveX probing code.\r\n * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip\r\n * out the ActiveX probing code from binaries. To achieve this, use\r\n * `goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR` instead.\r\n * TODO(ruilopes): Collapse both defines.\r\n */\r\ngoog.net.XmlHttp.ASSUME_NATIVE_XHR =\r\n goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);\r\n\r\n\r\n/** @const */\r\ngoog.net.XmlHttpDefines = {};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\r\n * true eliminates the ActiveX probing code.\r\n */\r\ngoog.net.XmlHttpDefines.ASSUME_NATIVE_XHR =\r\n goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);\r\n\r\n\r\n/**\r\n * Gets the options to use with the XMLHttpRequest objects obtained using\r\n * the static methods.\r\n * @return {Object} The options.\r\n */\r\ngoog.net.XmlHttp.getOptions = function() {\r\n return goog.net.XmlHttp.factory_.getOptions();\r\n};\r\n\r\n\r\n/**\r\n * Type of options that an XmlHttp object can have.\r\n * @enum {number}\r\n */\r\ngoog.net.XmlHttp.OptionType = {\r\n /**\r\n * Whether a goog.nullFunction should be used to clear the onreadystatechange\r\n * handler instead of null.\r\n */\r\n USE_NULL_FUNCTION: 0,\r\n\r\n /**\r\n * NOTE(user): In IE if send() errors on a *local* request the readystate\r\n * is still changed to COMPLETE. We need to ignore it and allow the\r\n * try/catch around send() to pick up the error.\r\n */\r\n LOCAL_REQUEST_ERROR: 1\r\n};\r\n\r\n\r\n/**\r\n * Status constants for XMLHTTP, matches:\r\n * https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx\r\n * @enum {number}\r\n */\r\ngoog.net.XmlHttp.ReadyState = {\r\n /**\r\n * Constant for when xmlhttprequest.readyState is uninitialized\r\n */\r\n UNINITIALIZED: 0,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is loading.\r\n */\r\n LOADING: 1,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is loaded.\r\n */\r\n LOADED: 2,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is in an interactive state.\r\n */\r\n INTERACTIVE: 3,\r\n\r\n /**\r\n * Constant for when xmlhttprequest.readyState is completed\r\n */\r\n COMPLETE: 4\r\n};\r\n\r\n\r\n/**\r\n * The global factory instance for creating XMLHttpRequest objects.\r\n * @type {goog.net.XmlHttpFactory}\r\n * @private\r\n */\r\ngoog.net.XmlHttp.factory_;\r\n\r\n\r\n/**\r\n * Sets the factories for creating XMLHttpRequest objects and their options.\r\n * @param {Function} factory The factory for XMLHttpRequest objects.\r\n * @param {Function} optionsFactory The factory for options.\r\n * @deprecated Use setGlobalFactory instead.\r\n */\r\ngoog.net.XmlHttp.setFactory = function(factory, optionsFactory) {\r\n goog.net.XmlHttp.setGlobalFactory(\r\n new goog.net.WrapperXmlHttpFactory(\r\n goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));\r\n};\r\n\r\n\r\n/**\r\n * Sets the global factory object.\r\n * @param {!goog.net.XmlHttpFactory} factory New global factory object.\r\n */\r\ngoog.net.XmlHttp.setGlobalFactory = function(factory) {\r\n goog.net.XmlHttp.factory_ = factory;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Default factory to use when creating xhr objects. You probably shouldn't be\r\n * instantiating this directly, but rather using it via goog.net.XmlHttp.\r\n * @extends {goog.net.XmlHttpFactory}\r\n * @constructor\r\n */\r\ngoog.net.DefaultXmlHttpFactory = function() {\r\n goog.net.XmlHttpFactory.call(this);\r\n};\r\ngoog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);\r\n\r\n\r\n/** @override */\r\ngoog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {\r\n var progId = this.getProgId_();\r\n if (progId) {\r\n return new ActiveXObject(progId);\r\n } else {\r\n return new XMLHttpRequest();\r\n }\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {\r\n var progId = this.getProgId_();\r\n var options = {};\r\n if (progId) {\r\n options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;\r\n options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;\r\n }\r\n return options;\r\n};\r\n\r\n\r\n/**\r\n * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.\r\n * @type {string|undefined}\r\n * @private\r\n */\r\ngoog.net.DefaultXmlHttpFactory.prototype.ieProgId_;\r\n\r\n\r\n/**\r\n * Initialize the private state used by other functions.\r\n * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.\r\n * @private\r\n */\r\ngoog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {\r\n if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||\r\n goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {\r\n return '';\r\n }\r\n\r\n // The following blog post describes what PROG IDs to use to create the\r\n // XMLHTTP object in Internet Explorer:\r\n // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx\r\n // However we do not (yet) fully trust that this will be OK for old versions\r\n // of IE on Win9x so we therefore keep the last 2.\r\n if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&\r\n typeof ActiveXObject != 'undefined') {\r\n // Candidate Active X types.\r\n var ACTIVE_X_IDENTS = [\r\n 'MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP',\r\n 'Microsoft.XMLHTTP'\r\n ];\r\n for (var i = 0; i < ACTIVE_X_IDENTS.length; i++) {\r\n var candidate = ACTIVE_X_IDENTS[i];\r\n\r\n try {\r\n new ActiveXObject(candidate);\r\n // NOTE(user): cannot assign progid and return candidate in one line\r\n // because JSCompiler complaings: BUG 658126\r\n this.ieProgId_ = candidate;\r\n return candidate;\r\n } catch (e) {\r\n // do nothing; try next choice\r\n }\r\n }\r\n\r\n // couldn't find any matches\r\n throw new Error(\r\n 'Could not create ActiveXObject. ActiveX might be disabled,' +\r\n ' or MSXML might not be installed');\r\n }\r\n\r\n return /** @type {string} */ (this.ieProgId_);\r\n};\r\n\r\n\r\n// Set the global factory to an instance of the default factory.\r\ngoog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview The API spec for the WebChannel messaging library.\r\n *\r\n * Similar to HTML5 WebSocket and Closure BrowserChannel, WebChannel\r\n * offers an abstraction for point-to-point socket-like communication between\r\n * a browser client and a remote origin.\r\n *\r\n * WebChannels are created via <code>WebChannel</code>. Multiple WebChannels\r\n * may be multiplexed over the same WebChannelTransport, which represents\r\n * the underlying physical connectivity over standard wire protocols\r\n * such as HTTP and SPDY.\r\n *\r\n * A WebChannels in turn represents a logical communication channel between\r\n * the client and server end point. A WebChannel remains open for\r\n * as long as the client or server end-point allows.\r\n *\r\n * Messages may be delivered in-order or out-of-order, reliably or unreliably\r\n * over the same WebChannel. Message delivery guarantees of a WebChannel is\r\n * to be specified by the application code; and the choice of the\r\n * underlying wire protocols is completely transparent to the API users.\r\n *\r\n * Client-to-client messaging via WebRTC based transport may also be support\r\n * via the same WebChannel API in future.\r\n *\r\n * Note that we have no immediate plan to move this API out of labs. While\r\n * the implementation is production ready, the API is subject to change\r\n * (addition only):\r\n * 1. Adopt new Web APIs (mainly whatwg streams) and goog.net.streams.\r\n * 2. New programming models for cloud (on the server-side) may require\r\n * new APIs to be defined.\r\n * 3. WebRTC DataChannel alignment\r\n *\r\n */\r\n\r\ngoog.provide('goog.net.WebChannel');\r\n\r\ngoog.require('goog.events');\r\ngoog.require('goog.events.Event');\r\ngoog.require('goog.events.Listenable');\r\ngoog.require('goog.net.XmlHttpFactory');\r\n\r\n\r\n\r\n/**\r\n * A WebChannel represents a logical bi-directional channel over which the\r\n * client communicates with a remote server that holds the other endpoint\r\n * of the channel. A WebChannel is always created in the context of a shared\r\n * {@link WebChannelTransport} instance. It is up to the underlying client-side\r\n * and server-side implementations to decide how or when multiplexing is\r\n * to be enabled.\r\n *\r\n * @interface\r\n * @extends {EventTarget}\r\n * @extends {goog.events.Listenable}\r\n */\r\ngoog.net.WebChannel = function() {};\r\n\r\n\r\n\r\n/**\r\n * This interface defines a pluggable API to allow WebChannel runtime to support\r\n * customized algorithms in order to recover from transient failures such as\r\n * those failures caused by network or proxies (intermediaries).\r\n *\r\n * The algorithm may also choose to fail-fast, e.g. switch the client to some\r\n * offline mode.\r\n *\r\n * Extra measurements and logging could also be implemented in the custom\r\n * module, which has the full knowledge of all the state transitions\r\n * (due to failures).\r\n *\r\n * A default algorithm will be provided by the webchannel library itself. Custom\r\n * algorithms are expected to be tailored to specific client platforms or\r\n * networking environments, e.g. mobile, cellular network.\r\n *\r\n * @interface\r\n */\r\ngoog.net.WebChannel.FailureRecovery = function() {};\r\n\r\n\r\n/**\r\n * Configuration spec for newly created WebChannel instances.\r\n *\r\n * WebChannels are configured in the context of the containing\r\n * {@link WebChannelTransport}. The configuration parameters are specified\r\n * when a new instance of WebChannel is created via {@link WebChannelTransport}.\r\n *\r\n * messageHeaders: custom headers to be added to every message sent to the\r\n * server. This object is mutable, and custom headers may be changed, removed,\r\n * or added during the runtime after a channel has been opened.\r\n *\r\n * initMessageHeaders: similar to messageHeaders, but any custom headers will\r\n * be sent only once when the channel is opened. Typical usage is to send\r\n * an auth header to the server, which only checks the auth header at the time\r\n * when the channel is opened.\r\n *\r\n * messageContentType: sent as initMessageHeaders via X-WebChannel-Content-Type,\r\n * to inform the server the MIME type of WebChannel messages.\r\n *\r\n * messageUrlParams: custom url query parameters to be added to every message\r\n * sent to the server. This object is mutable, and custom parameters may be\r\n * changed, removed or added during the runtime after a channel has been opened.\r\n *\r\n * clientProtocolHeaderRequired: whether a special header should be added to\r\n * each message so that the server can dispatch webchannel messages without\r\n * knowing the URL path prefix. Defaults to false.\r\n *\r\n * concurrentRequestLimit: the maximum number of in-flight HTTP requests allowed\r\n * when SPDY is enabled. Currently we only detect SPDY in Chrome.\r\n * This parameter defaults to 10. When SPDY is not enabled, this parameter\r\n * will have no effect.\r\n *\r\n * supportsCrossDomainXhr: setting this to true to allow the use of sub-domains\r\n * (as configured by the server) to send XHRs with the CORS withCredentials\r\n * bit set to true.\r\n *\r\n * testUrl: the test URL for detecting connectivity during the initial\r\n * handshake. This parameter defaults to \"/<channel_url>/test\".\r\n *\r\n * sendRawJson: whether to bypass v8 encoding of client-sent messages.\r\n * This defaults to false now due to legacy servers. New applications should\r\n * always configure this option to true.\r\n *\r\n * httpSessionIdParam: the URL parameter name that contains the session id (\r\n * for sticky routing of HTTP requests). When this param is specified, a server\r\n * that supports this option will respond with an opaque session id as part of\r\n * the initial handshake (via the X-HTTP-Session-Id header); and all the\r\n * subsequent requests will contain the httpSessionIdParam. This option will\r\n * take precedence over any duplicated parameter specified with\r\n * messageUrlParams, whose value will be ignored.\r\n *\r\n * httpHeadersOverwriteParam: the URL parameter name to allow custom HTTP\r\n * headers to be overwritten as a URL param to bypass CORS preflight.\r\n * goog.net.rpc.HttpCors is used to encode the HTTP headers.\r\n *\r\n * backgroundChannelTest: whether to run the channel test (detecting networking\r\n * conditions) as a background process so the OPEN event will be fired sooner\r\n * to reduce the initial handshake delay. This option defaults to true.\r\n * The actual background channel test is not fully implemented.\r\n *\r\n * forceLongPolling: whether to force long-polling from client to server.\r\n * This defaults to false. Long-polling may be necessary when a (MITM) proxy\r\n * is buffering data sent by the server.\r\n *\r\n * fastHandshake: enable true 0-RTT message delivery, including\r\n * leveraging QUIC 0-RTT (which requires GET to be used). This option\r\n * defaults to false. Note it is allowed to send messages before Open event is\r\n * received, after a channel has been opened. In order to enable 0-RTT,\r\n * messages will be encoded as part of URL and therefore there needs be a size\r\n * limit for those initial messages that are sent immediately as part of the\r\n * GET handshake request. With sendRawJson=true, this limit is currently set\r\n * to 4K chars and data beyond this limit will be buffered till the handshake\r\n * (1-RTT) finishes. With sendRawJson=false, it's up to the application\r\n * to limit the amount of data that is sent as part of the handshake.\r\n *\r\n * disableRedact: whether to disable logging redact. By default, redact is\r\n * enabled to remove any message payload or user-provided info\r\n * from closure logs.\r\n *\r\n * clientProfile: inform the server about the client profile to enable\r\n * customized configs that are optimized for certain clients or environments.\r\n * Currently this information is sent via X-WebChannel-Client-Profile header.\r\n *\r\n * internalChannelParams: the internal channel parameter name to allow\r\n * experimental channel configurations. Supported options include fastfail,\r\n * baseRetryDelayMs, retryDelaySeedMs, forwardChannelMaxRetries and\r\n * forwardChannelRequestTimeoutMs. Note that these options are subject to\r\n * change.\r\n *\r\n * xmlHttpFactory: allows the caller to override the factory used to create\r\n * XMLHttpRequest objects. This is introduced to disable CORS on firefox OS.\r\n *\r\n * requestRefreshThresholds: client-side thresholds that decide when to refresh\r\n * an underlying HTTP request, to limit memory consumption due to XHR buffering\r\n * or compression context. The client-side thresholds should be signficantly\r\n * smaller than the server-side thresholds. This allows the client to eliminate\r\n * any latency introduced by request refreshing, i.e. an RTT window during which\r\n * messages may be buffered on the server-side. Supported params include\r\n * totalBytesReceived, totalDurationMs.\r\n *\r\n * @typedef {{\r\n * messageHeaders: (!Object<string, string>|undefined),\r\n * initMessageHeaders: (!Object<string, string>|undefined),\r\n * messageContentType: (string|undefined),\r\n * messageUrlParams: (!Object<string, string>|undefined),\r\n * clientProtocolHeaderRequired: (boolean|undefined),\r\n * concurrentRequestLimit: (number|undefined),\r\n * supportsCrossDomainXhr: (boolean|undefined),\r\n * testUrl: (string|undefined),\r\n * sendRawJson: (boolean|undefined),\r\n * httpSessionIdParam: (string|undefined),\r\n * httpHeadersOverwriteParam: (string|undefined),\r\n * backgroundChannelTest: (boolean|undefined),\r\n * forceLongPolling: (boolean|undefined),\r\n * fastHandshake: (boolean|undefined),\r\n * disableRedact: (boolean|undefined),\r\n * clientProfile: (string|undefined),\r\n * internalChannelParams: (!Object<string, boolean|number>|undefined),\r\n * xmlHttpFactory: (!goog.net.XmlHttpFactory|undefined),\r\n * requestRefreshThresholds: (!Object<string, number>|undefined),\r\n * }}\r\n */\r\ngoog.net.WebChannel.Options;\r\n\r\n\r\n/**\r\n * Types that are allowed as message data.\r\n *\r\n * Note that JS objects (sent by the client) can only have string encoded\r\n * values due to the limitation of the current wire protocol.\r\n *\r\n * Unicode strings (sent by the server) may or may not need be escaped, as\r\n * decided by the server.\r\n *\r\n * @typedef {(!ArrayBuffer|!Blob|!Object<string, !Object|string>|!Array|string)}\r\n */\r\ngoog.net.WebChannel.MessageData;\r\n\r\n\r\n/**\r\n * Open the WebChannel against the URI specified in the constructor.\r\n */\r\ngoog.net.WebChannel.prototype.open = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Close the WebChannel.\r\n *\r\n * This is a full close (shutdown) with no guarantee of FIFO delivery in respect\r\n * to any in-flight messages sent to the server.\r\n *\r\n * If you need such a guarantee, see the Half the halfClose() method.\r\n */\r\ngoog.net.WebChannel.prototype.close = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Half-close the WebChannel.\r\n *\r\n * Half-close semantics:\r\n * 1. delivered as a regular message in FIFO programming order\r\n * 2. the server is expected to return a half-close too (with or without\r\n * application involved), which will trigger a full close (shutdown)\r\n * on the client side\r\n * 3. for now, the half-close event defined for server-initiated\r\n * half-close is not exposed to the client application\r\n * 4. a client-side half-close may be triggered internally when the client\r\n * receives a half-close from the server; and the client is expected to\r\n * do a full close after the half-close is acked and delivered\r\n * on the server-side.\r\n * 5. Full close is always a forced one. See the close() method.\r\n *\r\n * New messages sent after halfClose() will be dropped.\r\n *\r\n * NOTE: This is not yet implemented, and will throw an exception if called.\r\n */\r\ngoog.net.WebChannel.prototype.halfClose = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Sends a message to the server that maintains the other end point of\r\n * the WebChannel.\r\n *\r\n * O-RTT behavior:\r\n * 1. messages sent before open() is called will always be delivered as\r\n * part of the handshake, i.e. with 0-RTT\r\n * 2. messages sent after open() is called but before the OPEN event\r\n * is received will be delivered as part of the handshake if\r\n * send() is called from the same execution context as open().\r\n * 3. otherwise, those messages will be buffered till the handshake\r\n * is completed (which will fire the OPEN event).\r\n *\r\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\r\n */\r\ngoog.net.WebChannel.prototype.send = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Common events fired by WebChannels.\r\n * @enum {string}\r\n */\r\ngoog.net.WebChannel.EventType = {\r\n /** Dispatched when the channel is opened. */\r\n OPEN: goog.events.getUniqueId('open'),\r\n\r\n /** Dispatched when the channel is closed. */\r\n CLOSE: goog.events.getUniqueId('close'),\r\n\r\n /**\r\n * Dispatched when the channel is aborted due to errors.\r\n *\r\n * For backward compatibility reasons, a CLOSE event will also be\r\n * dispatched, following the ERROR event, which indicates that the channel\r\n * has been completely shutdown .\r\n */\r\n ERROR: goog.events.getUniqueId('error'),\r\n\r\n /** Dispatched when the channel has received a new message. */\r\n MESSAGE: goog.events.getUniqueId('message')\r\n};\r\n\r\n\r\n\r\n/**\r\n * The event interface for the MESSAGE event.\r\n *\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\ngoog.net.WebChannel.MessageEvent = function() {\r\n goog.net.WebChannel.MessageEvent.base(\r\n this, 'constructor', goog.net.WebChannel.EventType.MESSAGE);\r\n};\r\ngoog.inherits(goog.net.WebChannel.MessageEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * The content of the message received from the server.\r\n *\r\n * @type {!goog.net.WebChannel.MessageData}\r\n */\r\ngoog.net.WebChannel.MessageEvent.prototype.data;\r\n\r\n\r\n/**\r\n * The metadata key when the MESSAGE event represents a metadata message.\r\n *\r\n * @type {string|undefined}\r\n */\r\ngoog.net.WebChannel.MessageEvent.prototype.metadataKey;\r\n\r\n\r\n/**\r\n * WebChannel level error conditions.\r\n *\r\n * Summary of error debugging and reporting in WebChannel:\r\n *\r\n * Network Error\r\n * 1. By default the webchannel library will set the error status to\r\n * NETWORK_ERROR when a channel has to be aborted or closed. NETWORK_ERROR\r\n * may be recovered by the application by retrying and opening a new channel.\r\n * 2. There may be lost messages (not acked by the server) when a channel is\r\n * aborted. Currently we don't have a public API to retrieve messages that\r\n * are waiting to be acked on the client side. File a bug if you think it\r\n * is useful to expose such an API.\r\n * 3. Details of why a channel fails are available via closure debug logs,\r\n * and stats events (see webchannel/requeststats.js). Those are internal\r\n * stats and are subject to change. File a bug if you think it's useful to\r\n * version and expose such stats as part of the WebChannel API.\r\n *\r\n * Server Error\r\n * 1. SERVER_ERROR is intended to indicate a non-recoverable condition, e.g.\r\n * when auth fails.\r\n * 2. We don't currently generate any such errors, because most of the time\r\n * it's the responsibility of upper-layer frameworks or the application\r\n * itself to indicate to the client why a webchannel has been failed\r\n * by the server.\r\n * 3. When a channel is failed by the server explicitly, we still signal\r\n * NETWORK_ERROR to the client. Explicit server failure may happen when the\r\n * server does a fail-over, or becomes overloaded, or conducts a forced\r\n * shutdown etc.\r\n * 4. We use some heuristic to decide if the network (aka cloud) is down\r\n * v.s. the actual server is down.\r\n *\r\n * RuntimeProperties.getLastStatusCode is a useful state that we expose to\r\n * the client to indicate the HTTP response status code of the last HTTP\r\n * request initiated by the WebChannel client library, for debugging\r\n * purposes only.\r\n *\r\n * See WebChannel.Options.backChannelFailureRecovery and\r\n * WebChannel.FailureRecovery to install a custom failure-recovery algorithm.\r\n *\r\n * @enum {number}\r\n */\r\ngoog.net.WebChannel.ErrorStatus = {\r\n /** No error has occurred. */\r\n OK: 0,\r\n\r\n /** Communication to the server has failed. */\r\n NETWORK_ERROR: 1,\r\n\r\n /** The server fails to accept or process the WebChannel. */\r\n SERVER_ERROR: 2\r\n};\r\n\r\n\r\n\r\n/**\r\n * The event interface for the ERROR event.\r\n *\r\n * @constructor\r\n * @extends {goog.events.Event}\r\n */\r\ngoog.net.WebChannel.ErrorEvent = function() {\r\n goog.net.WebChannel.ErrorEvent.base(\r\n this, 'constructor', goog.net.WebChannel.EventType.ERROR);\r\n};\r\ngoog.inherits(goog.net.WebChannel.ErrorEvent, goog.events.Event);\r\n\r\n\r\n/**\r\n * The error status.\r\n *\r\n * @type {!goog.net.WebChannel.ErrorStatus}\r\n */\r\ngoog.net.WebChannel.ErrorEvent.prototype.status;\r\n\r\n\r\n/**\r\n * @return {!goog.net.WebChannel.RuntimeProperties} The runtime properties\r\n * of the WebChannel instance.\r\n */\r\ngoog.net.WebChannel.prototype.getRuntimeProperties = goog.abstractMethod;\r\n\r\n\r\n\r\n/**\r\n * The runtime properties of the WebChannel instance.\r\n *\r\n * This class is defined for debugging and monitoring purposes, as well as for\r\n * runtime functions that the application may choose to manage by itself.\r\n *\r\n * @interface\r\n */\r\ngoog.net.WebChannel.RuntimeProperties = function() {};\r\n\r\n\r\n/**\r\n * @return {number} The effective limit for the number of concurrent HTTP\r\n * requests that are allowed to be made for sending messages from the client\r\n * to the server. When SPDY is not enabled, this limit will be one.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getConcurrentRequestLimit =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * For applications that need support multiple channels (e.g. from\r\n * different tabs) to the same origin, use this method to decide if SPDY is\r\n * enabled and therefore it is safe to open multiple channels.\r\n *\r\n * If SPDY is disabled, the application may choose to limit the number of active\r\n * channels to one or use other means such as sub-domains to work around\r\n * the browser connection limit.\r\n *\r\n * @return {boolean} Whether SPDY is enabled for the origin against which\r\n * the channel is created.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.isSpdyEnabled =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @return {number} The number of requests (for sending messages to the server)\r\n * that are pending. If this number is approaching the value of\r\n * getConcurrentRequestLimit(), client-to-server message delivery may experience\r\n * a higher latency.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getPendingRequestCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * For applications to query the current HTTP session id, sent by the server\r\n * during the initial handshake.\r\n *\r\n * @return {?string} the HTTP session id or null if no HTTP session is in use.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getHttpSessionId =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Experimental API.\r\n *\r\n * This method generates an in-band commit request to the server, which will\r\n * ack the commit request as soon as all messages sent prior to this commit\r\n * request have been committed by the application.\r\n *\r\n * Committing a message has a stronger semantics than delivering a message\r\n * to the application. Detail spec:\r\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * Timeout or cancellation is not supported and the application is expected to\r\n * abort the channel if the commit-ack fails to arrive in time.\r\n *\r\n * ===\r\n *\r\n * This is currently implemented only in the client layer and the commit\r\n * callback will be invoked after all the pending client-sent messages have been\r\n * delivered by the server-side webchannel end-point. This semantics is\r\n * different and weaker than what's required for end-to-end ack which requires\r\n * the server application to ack the in-order delivery of messages that are sent\r\n * before the commit request is issued.\r\n *\r\n * Commit should only be called after the channel open event is received.\r\n * Duplicated commits are allowed and only the last callback is guaranteed.\r\n * Commit called after the channel has been closed will be ignored.\r\n *\r\n * @param {function()} callback The callback will be invoked once an\r\n * ack has been received for the current commit or any newly issued commit.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.commit = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * This method may be used by the application to recover from a peer failure\r\n * or to enable sender-initiated flow-control.\r\n *\r\n * Detail spec: https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @return {number} The total number of messages that have not received\r\n * commit-ack from the server; or if no commit has been issued, the number\r\n * of messages that have not been delivered to the server application.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * A low water-mark message count to notify the application when the\r\n * flow-control condition is cleared, that is, when the application is\r\n * able to send more messages.\r\n *\r\n * We expect the application to configure a high water-mark message count,\r\n * which is checked via getNonAckedMessageCount(). When the high water-mark\r\n * is exceeded, the application should install a callback via this method\r\n * to be notified when to start to send new messages.\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @param {number} count The low water-mark count. It is an error to pass\r\n * a non-positive value.\r\n * @param {function()} callback The call back to notify the application\r\n * when NonAckedMessageCount is below the specified low water-mark count.\r\n * Any previously registered callback is cleared. This new callback will\r\n * be cleared once it has been fired, or when the channel is closed or aborted.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.notifyNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Experimental API.\r\n *\r\n * This method registers a callback to handle the commit request sent\r\n * by the server. Commit protocol spec:\r\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @param {function(!Object)} callback The callback will take an opaque\r\n * commitId which needs be passed back to the server when an ack-commit\r\n * response is generated by the client application, via ackCommit().\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.onCommit = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Experimental API.\r\n *\r\n * This method is used by the application to generate an ack-commit response\r\n * for the given commitId. Commit protocol spec:\r\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\r\n *\r\n * This is not yet implemented.\r\n *\r\n * @param {!Object} commitId The commitId which denotes the commit request\r\n * from the server that needs be ack'ed.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.ackCommit = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @return {number} The last HTTP status code received by the channel.\r\n */\r\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastStatusCode =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Enum to indicate the current recovery state.\r\n *\r\n * @enum {string}\r\n */\r\ngoog.net.WebChannel.FailureRecovery.State = {\r\n /** Initial state. */\r\n INIT: 'init',\r\n\r\n /** Once a failure has been detected. */\r\n FAILED: 'failed',\r\n\r\n /**\r\n * Once a recovery operation has been issued, e.g. a new request to resume\r\n * communication.\r\n */\r\n RECOVERING: 'recovering',\r\n\r\n /** The channel has been closed. */\r\n CLOSED: 'closed'\r\n};\r\n\r\n\r\n/**\r\n * Enum to indicate different failure conditions as detected by the webchannel\r\n * runtime.\r\n *\r\n * This enum is to be used only between the runtime and FailureRecovery module,\r\n * and new states are expected to be introduced in future.\r\n *\r\n * @enum {string}\r\n */\r\ngoog.net.WebChannel.FailureRecovery.FailureCondition = {\r\n /**\r\n * The HTTP response returned a non-successful http status code.\r\n */\r\n HTTP_ERROR: 'http_error',\r\n\r\n /**\r\n * The request was aborted.\r\n */\r\n ABORT: 'abort',\r\n\r\n /**\r\n * The request timed out.\r\n */\r\n TIMEOUT: 'timeout',\r\n\r\n /**\r\n * Exception was thrown while processing the request/response.\r\n */\r\n EXCEPTION: 'exception'\r\n};\r\n\r\n\r\n/**\r\n * @return {!goog.net.WebChannel.FailureRecovery.State} the current state,\r\n * mainly for debugging use.\r\n */\r\ngoog.net.WebChannel.FailureRecovery.prototype.getState = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * This method is for WebChannel runtime to set the current failure condition\r\n * and to provide a callback for the algorithm to signal to the runtime\r\n * when it is time to issue a recovery operation, e.g. a new request to the\r\n * server.\r\n *\r\n * Supported transitions include:\r\n * INIT->FAILED\r\n * FAILED->FAILED (re-entry ok)\r\n * RECOVERY->FAILED.\r\n *\r\n * Ignored if state == CLOSED.\r\n *\r\n * Advanced implementations are expected to track all the state transitions\r\n * and their timestamps for monitoring purposes.\r\n *\r\n * @param {!goog.net.WebChannel.FailureRecovery.FailureCondition} failure The\r\n * new failure condition generated by the WebChannel runtime.\r\n * @param {!Function} operation The callback function to the WebChannel\r\n * runtime to issue a recovery operation, e.g. a new request. E.g. the default\r\n * recovery algorithm will issue timeout-based recovery operations.\r\n * Post-condition for the callback: state transition to RECOVERING.\r\n *\r\n * @return {!goog.net.WebChannel.FailureRecovery.State} The updated state\r\n * as decided by the failure recovery module. Upon a recoverable failure event,\r\n * the state is transitioned to RECOVERING; or the state is transitioned to\r\n * FAILED which indicates a fail-fast decision for the runtime to execute.\r\n */\r\ngoog.net.WebChannel.FailureRecovery.prototype.setFailure = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * The Webchannel runtime needs call this method when webchannel is closed or\r\n * aborted.\r\n *\r\n * Once the instance is closed, any access to the instance will be a no-op.\r\n */\r\ngoog.net.WebChannel.FailureRecovery.prototype.close = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * A request header to indicate to the server the messaging protocol\r\n * each HTTP message is speaking.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_CLIENT_PROTOCOL = 'X-Client-Protocol';\r\n\r\n\r\n/**\r\n * The value for x-client-protocol when the messaging protocol is WebChannel.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL = 'webchannel';\r\n\r\n\r\n/**\r\n * A response header for the server to signal the wire-protocol that\r\n * the browser establishes with the server (or proxy), e.g. \"spdy\" (aka http/2)\r\n * \"quic\". This information avoids the need to use private APIs to decide if\r\n * HTTP requests are multiplexed etc.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL = 'X-Client-Wire-Protocol';\r\n\r\n\r\n/**\r\n * A response header for the server to send back the HTTP session id as part of\r\n * the initial handshake. The value of the HTTP session id is opaque to the\r\n * WebChannel protocol.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_HTTP_SESSION_ID = 'X-HTTP-Session-Id';\r\n\r\n\r\n/**\r\n * A response header for the server to send back any initial response data as a\r\n * header to avoid any possible buffering by an intermediary, which may\r\n * be undesired during the handshake.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_HTTP_INITIAL_RESPONSE = 'X-HTTP-Initial-Response';\r\n\r\n\r\n/**\r\n * A request header for specifying the content-type of WebChannel messages,\r\n * e.g. application-defined JSON encoding styles. Currently this header\r\n * is sent by the client via initMessageHeaders when the channel is opened.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE = 'X-WebChannel-Content-Type';\r\n\r\n\r\n/**\r\n * A request header for specifying the client profile in order to apply\r\n * customized config params on the server side, e.g. timeouts.\r\n *\r\n * @type {string}\r\n */\r\ngoog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE = 'X-WebChannel-Client-Profile';\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Definition of the ChannelRequest class. The request\r\n * object encapsulates the logic for making a single request, either for the\r\n * forward channel, back channel, or test channel, to the server. It contains\r\n * the logic for the two types of transports we use:\r\n * XMLHTTP and Image request. It provides timeout detection. More transports\r\n * to be added in future, such as Fetch, WebSocket.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.ChannelRequest');\r\n\r\ngoog.require('goog.Timer');\r\ngoog.require('goog.async.Throttle');\r\ngoog.require('goog.events.EventHandler');\r\ngoog.require('goog.labs.net.webChannel.Channel');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\ngoog.require('goog.labs.net.webChannel.environment');\r\ngoog.require('goog.labs.net.webChannel.requestStats');\r\ngoog.require('goog.net.ErrorCode');\r\ngoog.require('goog.net.EventType');\r\ngoog.require('goog.net.WebChannel');\r\ngoog.require('goog.net.XmlHttp');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.userAgent');\r\n\r\ngoog.forwardDeclare('goog.Uri');\r\ngoog.forwardDeclare('goog.net.XhrIo');\r\n\r\n\r\n\r\n/**\r\n * A new ChannelRequest is created for each request to the server.\r\n *\r\n * @param {goog.labs.net.webChannel.Channel} channel\r\n * The channel that owns this request.\r\n * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A\r\n * WebChannelDebug to use for logging.\r\n * @param {string=} opt_sessionId The session id for the channel.\r\n * @param {string|number=} opt_requestId The request id for this request.\r\n * @param {number=} opt_retryId The retry id for this request.\r\n * @constructor\r\n * @struct\r\n * @final\r\n */\r\ngoog.labs.net.webChannel.ChannelRequest = function(\r\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\r\n /**\r\n * The channel object that owns the request.\r\n * @private {goog.labs.net.webChannel.Channel}\r\n */\r\n this.channel_ = channel;\r\n\r\n /**\r\n * The channel debug to use for logging\r\n * @private {goog.labs.net.webChannel.WebChannelDebug}\r\n */\r\n this.channelDebug_ = channelDebug;\r\n\r\n /**\r\n * The Session ID for the channel.\r\n * @private {string|undefined}\r\n */\r\n this.sid_ = opt_sessionId;\r\n\r\n /**\r\n * The RID (request ID) for the request.\r\n * @private {string|number|undefined}\r\n */\r\n this.rid_ = opt_requestId;\r\n\r\n /**\r\n * The attempt number of the current request.\r\n * @private {number}\r\n */\r\n this.retryId_ = opt_retryId || 1;\r\n\r\n /**\r\n * An object to keep track of the channel request event listeners.\r\n * @private {!goog.events.EventHandler<\r\n * !goog.labs.net.webChannel.ChannelRequest>}\r\n */\r\n this.eventHandler_ = new goog.events.EventHandler(this);\r\n\r\n /**\r\n * The timeout in ms before failing the request.\r\n * @private {number}\r\n */\r\n this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;\r\n\r\n /**\r\n * A timer for polling responseText in browsers that don't fire\r\n * onreadystatechange during incremental loading of responseText.\r\n * @private {goog.Timer}\r\n */\r\n this.pollingTimer_ =\r\n new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());\r\n\r\n /**\r\n * Extra HTTP headers to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraHeaders_ = null;\r\n\r\n\r\n /**\r\n * Whether the request was successful. This is only set to true after the\r\n * request successfully completes.\r\n * @private {boolean}\r\n */\r\n this.successful_ = false;\r\n\r\n\r\n /**\r\n * The TimerID of the timer used to detect if the request has timed-out.\r\n * @type {?number}\r\n * @private\r\n */\r\n this.watchDogTimerId_ = null;\r\n\r\n /**\r\n * The time in the future when the request will timeout.\r\n * @private {?number}\r\n */\r\n this.watchDogTimeoutTime_ = null;\r\n\r\n /**\r\n * The time the request started.\r\n * @private {?number}\r\n */\r\n this.requestStartTime_ = null;\r\n\r\n /**\r\n * The type of request (XMLHTTP, IMG)\r\n * @private {?number}\r\n */\r\n this.type_ = null;\r\n\r\n /**\r\n * The base Uri for the request. The includes all the parameters except the\r\n * one that indicates the retry number.\r\n * @private {goog.Uri}\r\n */\r\n this.baseUri_ = null;\r\n\r\n /**\r\n * The request Uri that was actually used for the most recent request attempt.\r\n * @private {goog.Uri}\r\n */\r\n this.requestUri_ = null;\r\n\r\n /**\r\n * The post data, if the request is a post.\r\n * @private {?string}\r\n */\r\n this.postData_ = null;\r\n\r\n /**\r\n * An array of pending messages that we have either received a non-successful\r\n * response for, or no response at all, and which therefore may or may not\r\n * have been received by the server.\r\n * @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}\r\n */\r\n this.pendingMessages_ = [];\r\n\r\n /**\r\n * The XhrLte request if the request is using XMLHTTP\r\n * @private {goog.net.XhrIo}\r\n */\r\n this.xmlHttp_ = null;\r\n\r\n /**\r\n * The position of where the next unprocessed chunk starts in the response\r\n * text.\r\n * @private {number}\r\n */\r\n this.xmlHttpChunkStart_ = 0;\r\n\r\n /**\r\n * The verb (Get or Post) for the request.\r\n * @private {?string}\r\n */\r\n this.verb_ = null;\r\n\r\n /**\r\n * The last error if the request failed.\r\n * @private {?goog.labs.net.webChannel.ChannelRequest.Error}\r\n */\r\n this.lastError_ = null;\r\n\r\n /**\r\n * The last status code received.\r\n * @private {number}\r\n */\r\n this.lastStatusCode_ = -1;\r\n\r\n /**\r\n * Whether the request has been cancelled due to a call to cancel.\r\n * @private {boolean}\r\n */\r\n this.cancelled_ = false;\r\n\r\n /**\r\n * A throttle time in ms for readystatechange events for the backchannel.\r\n * Useful for throttling when ready state is INTERACTIVE (partial data).\r\n * If set to zero no throttle is used.\r\n *\r\n * See WebChannelBase.prototype.readyStateChangeThrottleMs_\r\n *\r\n * @private {number}\r\n */\r\n this.readyStateChangeThrottleMs_ = 0;\r\n\r\n /**\r\n * The throttle for readystatechange events for the current request, or null\r\n * if there is none.\r\n * @private {goog.async.Throttle}\r\n */\r\n this.readyStateChangeThrottle_ = null;\r\n\r\n /**\r\n * Whether to the result is expected to be encoded for chunking and thus\r\n * requires decoding.\r\n * @private {boolean}\r\n */\r\n this.decodeChunks_ = false;\r\n\r\n /**\r\n * Whether to decode x-http-initial-response.\r\n * @private {boolean}\r\n */\r\n this.decodeInitialResponse_ = false;\r\n\r\n /**\r\n * Whether x-http-initial-response has been decoded (dispatched).\r\n * @private {boolean}\r\n */\r\n this.initialResponseDecoded_ = false;\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannel = goog.net.WebChannel;\r\nvar Channel = goog.labs.net.webChannel.Channel;\r\nvar ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\nvar environment = goog.labs.net.webChannel.environment;\r\n\r\n\r\n/**\r\n * Default timeout in MS for a request. The server must return data within this\r\n * time limit for the request to not timeout.\r\n * @private {number}\r\n */\r\nChannelRequest.TIMEOUT_MS_ = 45 * 1000;\r\n\r\n\r\n/**\r\n * Enum for channel requests type\r\n * @enum {number}\r\n * @private\r\n */\r\nChannelRequest.Type_ = {\r\n /**\r\n * XMLHTTP requests.\r\n */\r\n XML_HTTP: 1,\r\n\r\n /**\r\n * IMG requests.\r\n */\r\n CLOSE_REQUEST: 2\r\n};\r\n\r\n\r\n/**\r\n * Enum type for identifying an error.\r\n * @enum {number}\r\n */\r\nChannelRequest.Error = {\r\n /**\r\n * Errors due to a non-200 status code.\r\n */\r\n STATUS: 0,\r\n\r\n /**\r\n * Errors due to no data being returned.\r\n */\r\n NO_DATA: 1,\r\n\r\n /**\r\n * Errors due to a timeout.\r\n */\r\n TIMEOUT: 2,\r\n\r\n /**\r\n * Errors due to the server returning an unknown.\r\n */\r\n UNKNOWN_SESSION_ID: 3,\r\n\r\n /**\r\n * Errors due to bad data being received.\r\n */\r\n BAD_DATA: 4,\r\n\r\n /**\r\n * Errors due to the handler throwing an exception.\r\n */\r\n HANDLER_EXCEPTION: 5,\r\n\r\n /**\r\n * The browser declared itself offline during the request.\r\n */\r\n BROWSER_OFFLINE: 6\r\n};\r\n\r\n\r\n/**\r\n * Returns a useful error string for debugging based on the specified error\r\n * code.\r\n * @param {?ChannelRequest.Error} errorCode The error code.\r\n * @param {number} statusCode The HTTP status code.\r\n * @return {string} The error string for the given code combination.\r\n */\r\nChannelRequest.errorStringFromCode = function(errorCode, statusCode) {\r\n switch (errorCode) {\r\n case ChannelRequest.Error.STATUS:\r\n return 'Non-200 return code (' + statusCode + ')';\r\n case ChannelRequest.Error.NO_DATA:\r\n return 'XMLHTTP failure (no data)';\r\n case ChannelRequest.Error.TIMEOUT:\r\n return 'HttpConnection timeout';\r\n default:\r\n return 'Unknown error';\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sentinel value used to indicate an invalid chunk in a multi-chunk response.\r\n * @private {Object}\r\n */\r\nChannelRequest.INVALID_CHUNK_ = {};\r\n\r\n\r\n/**\r\n * Sentinel value used to indicate an incomplete chunk in a multi-chunk\r\n * response.\r\n * @private {Object}\r\n */\r\nChannelRequest.INCOMPLETE_CHUNK_ = {};\r\n\r\n\r\n/**\r\n * Returns whether XHR streaming is supported on this browser.\r\n *\r\n * @return {boolean} Whether XHR streaming is supported.\r\n * @see http://code.google.com/p/closure-library/issues/detail?id=346\r\n */\r\nChannelRequest.supportsXhrStreaming = function() {\r\n return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);\r\n};\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @param {Object} extraHeaders The HTTP headers.\r\n */\r\nChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {\r\n this.extraHeaders_ = extraHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Overrides the default HTTP method.\r\n *\r\n * @param {string} verb The HTTP method\r\n */\r\nChannelRequest.prototype.setVerb = function(verb) {\r\n this.verb_ = verb;\r\n};\r\n\r\n\r\n/**\r\n * Sets the timeout for a request\r\n *\r\n * @param {number} timeout The timeout in MS for when we fail the request.\r\n */\r\nChannelRequest.prototype.setTimeout = function(timeout) {\r\n this.timeout_ = timeout;\r\n};\r\n\r\n\r\n/**\r\n * Sets the throttle for handling onreadystatechange events for the request.\r\n *\r\n * @param {number} throttle The throttle in ms. A value of zero indicates\r\n * no throttle.\r\n */\r\nChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {\r\n this.readyStateChangeThrottleMs_ = throttle;\r\n};\r\n\r\n\r\n/**\r\n * Sets the pending messages that this request is handling.\r\n *\r\n * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages\r\n * The pending messages for this request.\r\n */\r\nChannelRequest.prototype.setPendingMessages = function(pendingMessages) {\r\n this.pendingMessages_ = pendingMessages;\r\n};\r\n\r\n\r\n/**\r\n * Gets the pending messages that this request is handling, in case of a retry.\r\n *\r\n * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending\r\n * messages for this request.\r\n */\r\nChannelRequest.prototype.getPendingMessages = function() {\r\n return this.pendingMessages_;\r\n};\r\n\r\n\r\n/**\r\n * Uses XMLHTTP to send an HTTP POST to the server.\r\n *\r\n * @param {goog.Uri} uri The uri of the request.\r\n * @param {?string} postData The data for the post body.\r\n * @param {boolean} decodeChunks Whether to the result is expected to be\r\n * encoded for chunking and thus requires decoding.\r\n */\r\nChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {\r\n this.type_ = ChannelRequest.Type_.XML_HTTP;\r\n this.baseUri_ = uri.clone().makeUnique();\r\n this.postData_ = postData;\r\n this.decodeChunks_ = decodeChunks;\r\n this.sendXmlHttp_(null /* hostPrefix */);\r\n};\r\n\r\n\r\n/**\r\n * Uses XMLHTTP to send an HTTP GET to the server.\r\n *\r\n * @param {goog.Uri} uri The uri of the request.\r\n * @param {boolean} decodeChunks Whether to the result is expected to be\r\n * encoded for chunking and thus requires decoding.\r\n * @param {?string} hostPrefix The host prefix, if we might be using a\r\n * secondary domain. Note that it should also be in the URL, adding this\r\n * won't cause it to be added to the URL.\r\n */\r\nChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {\r\n this.type_ = ChannelRequest.Type_.XML_HTTP;\r\n this.baseUri_ = uri.clone().makeUnique();\r\n this.postData_ = null;\r\n this.decodeChunks_ = decodeChunks;\r\n\r\n this.sendXmlHttp_(hostPrefix);\r\n};\r\n\r\n\r\n/**\r\n * Sends a request via XMLHTTP according to the current state of the request\r\n * object.\r\n *\r\n * @param {?string} hostPrefix The host prefix, if we might be using a secondary\r\n * domain.\r\n * @private\r\n */\r\nChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {\r\n this.requestStartTime_ = goog.now();\r\n this.ensureWatchDogTimer_();\r\n\r\n // clone the base URI to create the request URI. The request uri has the\r\n // attempt number as a parameter which helps in debugging.\r\n this.requestUri_ = this.baseUri_.clone();\r\n this.requestUri_.setParameterValues('t', this.retryId_);\r\n\r\n // send the request either as a POST or GET\r\n this.xmlHttpChunkStart_ = 0;\r\n var useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();\r\n this.xmlHttp_ =\r\n this.channel_.createXhrIo(useSecondaryDomains ? hostPrefix : null);\r\n\r\n if (this.readyStateChangeThrottleMs_ > 0) {\r\n this.readyStateChangeThrottle_ = new goog.async.Throttle(\r\n goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),\r\n this.readyStateChangeThrottleMs_);\r\n }\r\n\r\n this.eventHandler_.listen(\r\n this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,\r\n this.readyStateChangeHandler_);\r\n\r\n var headers = this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};\r\n if (this.postData_) {\r\n if (!this.verb_) {\r\n this.verb_ = 'POST';\r\n }\r\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\r\n this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);\r\n } else {\r\n this.verb_ = 'GET';\r\n this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);\r\n }\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_MADE);\r\n this.channelDebug_.xmlHttpChannelRequest(\r\n this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);\r\n};\r\n\r\n\r\n/**\r\n * Handles a readystatechange event.\r\n * @param {goog.events.Event} evt The event.\r\n * @private\r\n */\r\nChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {\r\n var xhr = /** @type {goog.net.XhrIo} */ (evt.target);\r\n var throttle = this.readyStateChangeThrottle_;\r\n if (throttle &&\r\n xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\r\n // Only throttle in the partial data case.\r\n this.channelDebug_.debug('Throttling readystatechange.');\r\n throttle.fire();\r\n } else {\r\n // If we haven't throttled, just handle response directly.\r\n this.xmlHttpHandler_(xhr);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * XmlHttp handler\r\n * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.\r\n * @private\r\n */\r\nChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {\r\n requestStats.onStartExecution();\r\n\r\n\r\n try {\r\n if (xmlhttp == this.xmlHttp_) {\r\n this.onXmlHttpReadyStateChanged_();\r\n } else {\r\n this.channelDebug_.warning(\r\n 'Called back with an ' +\r\n 'unexpected xmlhttp');\r\n }\r\n } catch (ex) {\r\n this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');\r\n if (this.xmlHttp_ && this.xmlHttp_.getResponseText()) {\r\n var channelRequest = this;\r\n this.channelDebug_.dumpException(ex, function() {\r\n return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();\r\n });\r\n } else {\r\n this.channelDebug_.dumpException(ex, 'No response text');\r\n }\r\n } finally {\r\n requestStats.onEndExecution();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called by the readystate handler for XMLHTTP requests.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {\r\n var readyState = this.xmlHttp_.getReadyState();\r\n var errorCode = this.xmlHttp_.getLastErrorCode();\r\n var statusCode = this.xmlHttp_.getStatus();\r\n\r\n // we get partial results in browsers that support ready state interactive.\r\n // We also make sure that getResponseText is not null in interactive mode\r\n // before we continue.\r\n if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||\r\n (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&\r\n !environment.isPollingRequired() && // otherwise, go on to startPolling\r\n !this.xmlHttp_.getResponseText())) {\r\n return; // not yet ready\r\n }\r\n\r\n // Dispatch any appropriate network events.\r\n if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\r\n errorCode != goog.net.ErrorCode.ABORT) {\r\n // Pretty conservative, these are the only known scenarios which we'd\r\n // consider indicative of a truly non-functional network connection.\r\n if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_FAILED);\r\n } else {\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_SUCCEEDED);\r\n }\r\n }\r\n\r\n // got some data so cancel the watchdog timer\r\n this.cancelWatchDogTimer_();\r\n\r\n var status = this.xmlHttp_.getStatus();\r\n this.lastStatusCode_ = status;\r\n var responseText = this.xmlHttp_.getResponseText();\r\n if (!responseText) {\r\n var channelRequest = this;\r\n this.channelDebug_.debug(function() {\r\n return 'No response text for uri ' + channelRequest.requestUri_ +\r\n ' status ' + status;\r\n });\r\n }\r\n this.successful_ = (status == 200);\r\n\r\n this.channelDebug_.xmlHttpChannelResponseMetaData(\r\n /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,\r\n this.retryId_, readyState, status);\r\n\r\n if (!this.successful_) {\r\n if (status == 400 && responseText.indexOf('Unknown SID') > 0) {\r\n // the server error string will include 'Unknown SID' which indicates the\r\n // server doesn't know about the session (maybe it got restarted, maybe\r\n // the user got moved to another server, etc.,). Handlers can special\r\n // case this error\r\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;\r\n requestStats.notifyStatEvent(\r\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\r\n this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');\r\n } else {\r\n this.lastError_ = ChannelRequest.Error.STATUS;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);\r\n this.channelDebug_.warning(\r\n 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');\r\n }\r\n this.cleanup_();\r\n this.dispatchFailure_();\r\n return;\r\n }\r\n\r\n if (this.shouldCheckInitialResponse_()) {\r\n var initialResponse = this.getInitialResponse_();\r\n if (initialResponse) {\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, initialResponse,\r\n 'Initial handshake response via ' +\r\n WebChannel.X_HTTP_INITIAL_RESPONSE);\r\n this.initialResponseDecoded_ = true;\r\n this.safeOnRequestData_(initialResponse);\r\n } else {\r\n this.successful_ = false;\r\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast\r\n requestStats.notifyStatEvent(\r\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\r\n this.channelDebug_.warning(\r\n 'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +\r\n ' (' + this.rid_ + ')');\r\n this.cleanup_();\r\n this.dispatchFailure_();\r\n return;\r\n }\r\n }\r\n\r\n if (this.decodeChunks_) {\r\n this.decodeNextChunks_(readyState, responseText);\r\n if (environment.isPollingRequired() && this.successful_ &&\r\n readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\r\n this.startPolling_();\r\n }\r\n } else {\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, responseText, null);\r\n this.safeOnRequestData_(responseText);\r\n }\r\n\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n this.cleanup_();\r\n }\r\n\r\n if (!this.successful_) {\r\n return;\r\n }\r\n\r\n if (!this.cancelled_) {\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n this.channel_.onRequestComplete(this);\r\n } else {\r\n // The default is false, the result from this callback shouldn't carry\r\n // over to the next callback, otherwise the request looks successful if\r\n // the watchdog timer gets called\r\n this.successful_ = false;\r\n this.ensureWatchDogTimer_();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Whether we need check the initial-response header that is sent during the\r\n * fast handshake.\r\n *\r\n * @return {boolean} true if the initial-response header is yet to be processed.\r\n * @private\r\n */\r\nChannelRequest.prototype.shouldCheckInitialResponse_ = function() {\r\n return this.decodeInitialResponse_ && !this.initialResponseDecoded_;\r\n};\r\n\r\n\r\n/**\r\n * Queries the initial response header that is sent during the handshake.\r\n *\r\n * @return {?string} The non-empty header value or null.\r\n * @private\r\n */\r\nChannelRequest.prototype.getInitialResponse_ = function() {\r\n if (this.xmlHttp_) {\r\n var value = this.xmlHttp_.getStreamingResponseHeader(\r\n WebChannel.X_HTTP_INITIAL_RESPONSE);\r\n if (value && !goog.string.isEmptyOrWhitespace(value)) {\r\n return value;\r\n }\r\n }\r\n\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Check if the initial response header has been handled.\r\n *\r\n * @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.\r\n */\r\nChannelRequest.prototype.isInitialResponseDecoded = function() {\r\n return this.initialResponseDecoded_;\r\n};\r\n\r\n\r\n/**\r\n * Decodes X_HTTP_INITIAL_RESPONSE if present.\r\n */\r\nChannelRequest.prototype.setDecodeInitialResponse = function() {\r\n this.decodeInitialResponse_ = true;\r\n};\r\n\r\n\r\n/**\r\n * Decodes the next set of available chunks in the response.\r\n * @param {number} readyState The value of readyState.\r\n * @param {string} responseText The value of responseText.\r\n * @private\r\n */\r\nChannelRequest.prototype.decodeNextChunks_ = function(\r\n readyState, responseText) {\r\n var decodeNextChunksSuccessful = true;\r\n while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {\r\n var chunkText = this.getNextChunk_(responseText);\r\n if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n // should have consumed entire response when the request is done\r\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);\r\n decodeNextChunksSuccessful = false;\r\n }\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, null, '[Incomplete Response]');\r\n break;\r\n } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {\r\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, responseText, '[Invalid Chunk]');\r\n decodeNextChunksSuccessful = false;\r\n break;\r\n } else {\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, /** @type {string} */ (chunkText), null);\r\n this.safeOnRequestData_(/** @type {string} */ (chunkText));\r\n }\r\n }\r\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\r\n responseText.length == 0) {\r\n // also an error if we didn't get any response\r\n this.lastError_ = ChannelRequest.Error.NO_DATA;\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);\r\n decodeNextChunksSuccessful = false;\r\n }\r\n this.successful_ = this.successful_ && decodeNextChunksSuccessful;\r\n if (!decodeNextChunksSuccessful) {\r\n // malformed response - we make this trigger retry logic\r\n this.channelDebug_.xmlHttpChannelResponseText(\r\n this.rid_, responseText, '[Invalid Chunked Response]');\r\n this.cleanup_();\r\n this.dispatchFailure_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Polls the response for new data.\r\n * @private\r\n */\r\nChannelRequest.prototype.pollResponse_ = function() {\r\n if (!this.xmlHttp_) {\r\n return; // already closed\r\n }\r\n var readyState = this.xmlHttp_.getReadyState();\r\n var responseText = this.xmlHttp_.getResponseText();\r\n if (this.xmlHttpChunkStart_ < responseText.length) {\r\n this.cancelWatchDogTimer_();\r\n this.decodeNextChunks_(readyState, responseText);\r\n if (this.successful_ &&\r\n readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n this.ensureWatchDogTimer_();\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Starts a polling interval for changes to responseText of the\r\n * XMLHttpRequest, for browsers that don't fire onreadystatechange\r\n * as data comes in incrementally. This timer is disabled in\r\n * cleanup_().\r\n * @private\r\n */\r\nChannelRequest.prototype.startPolling_ = function() {\r\n this.eventHandler_.listen(\r\n this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);\r\n this.pollingTimer_.start();\r\n};\r\n\r\n\r\n/**\r\n * Returns the next chunk of a chunk-encoded response. This is not standard\r\n * HTTP chunked encoding because browsers don't expose the chunk boundaries to\r\n * the application through XMLHTTP. So we have an additional chunk encoding at\r\n * the application level that lets us tell where the beginning and end of\r\n * individual responses are so that we can only try to eval a complete JS array.\r\n *\r\n * The encoding is the size of the chunk encoded as a decimal string followed\r\n * by a newline followed by the data.\r\n *\r\n * @param {string} responseText The response text from the XMLHTTP response.\r\n * @return {string|Object} The next chunk string or a sentinel object\r\n * indicating a special condition.\r\n * @private\r\n */\r\nChannelRequest.prototype.getNextChunk_ = function(responseText) {\r\n var sizeStartIndex = this.xmlHttpChunkStart_;\r\n var sizeEndIndex = responseText.indexOf('\\n', sizeStartIndex);\r\n if (sizeEndIndex == -1) {\r\n return ChannelRequest.INCOMPLETE_CHUNK_;\r\n }\r\n\r\n var sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);\r\n var size = Number(sizeAsString);\r\n if (isNaN(size)) {\r\n return ChannelRequest.INVALID_CHUNK_;\r\n }\r\n\r\n var chunkStartIndex = sizeEndIndex + 1;\r\n if (chunkStartIndex + size > responseText.length) {\r\n return ChannelRequest.INCOMPLETE_CHUNK_;\r\n }\r\n\r\n var chunkText = responseText.substr(chunkStartIndex, size);\r\n this.xmlHttpChunkStart_ = chunkStartIndex + size;\r\n return chunkText;\r\n};\r\n\r\n\r\n/**\r\n * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.\r\n *\r\n * This is only currently used to terminate the connection, as an IMG tag is\r\n * the most reliable way to send something to the server while the page\r\n * is getting torn down.\r\n *\r\n * Navigator.sendBeacon is available on Chrome and Firefox as a formal\r\n * solution to ensure delivery without blocking window close. See\r\n * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\r\n *\r\n * For Chrome Apps, sendBeacon is always necessary due to Content Security\r\n * Policy (CSP) violation of using an IMG tag.\r\n *\r\n * For react-native, we use xhr to send the actual close request, and assume\r\n * there is no page-close issue with react-native.\r\n *\r\n * @param {goog.Uri} uri The uri to send a request to.\r\n */\r\nChannelRequest.prototype.sendCloseRequest = function(uri) {\r\n this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;\r\n this.baseUri_ = uri.clone().makeUnique();\r\n\r\n var requestSent = false;\r\n\r\n if (goog.global.navigator && goog.global.navigator.sendBeacon) {\r\n // empty string body to avoid 413 error on chrome < 41\r\n requestSent =\r\n goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');\r\n }\r\n\r\n if (!requestSent && goog.global.Image) {\r\n var eltImg = new Image();\r\n eltImg.src = this.baseUri_;\r\n requestSent = true;\r\n }\r\n\r\n if (!requestSent) {\r\n // no handler is set to match the sendBeacon/Image behavior\r\n this.xmlHttp_ = this.channel_.createXhrIo(null);\r\n this.xmlHttp_.send(this.baseUri_);\r\n }\r\n\r\n this.requestStartTime_ = goog.now();\r\n this.ensureWatchDogTimer_();\r\n};\r\n\r\n\r\n/**\r\n * Cancels the request no matter what the underlying transport is.\r\n */\r\nChannelRequest.prototype.cancel = function() {\r\n this.cancelled_ = true;\r\n this.cleanup_();\r\n};\r\n\r\n\r\n/**\r\n * Resets the timeout.\r\n *\r\n * @param {number=} opt_timeout The new timeout\r\n */\r\nChannelRequest.prototype.resetTimeout = function(opt_timeout) {\r\n if (opt_timeout) {\r\n this.setTimeout(opt_timeout);\r\n }\r\n // restart only if a timer is currently set\r\n if (this.watchDogTimerId_) {\r\n this.cancelWatchDogTimer_();\r\n this.ensureWatchDogTimer_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Ensures that there is watchdog timeout which is used to ensure that\r\n * the connection completes in time.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.ensureWatchDogTimer_ = function() {\r\n this.watchDogTimeoutTime_ = goog.now() + this.timeout_;\r\n this.startWatchDogTimer_(this.timeout_);\r\n};\r\n\r\n\r\n/**\r\n * Starts the watchdog timer which is used to ensure that the connection\r\n * completes in time.\r\n * @param {number} time The number of milliseconds to wait.\r\n * @private\r\n */\r\nChannelRequest.prototype.startWatchDogTimer_ = function(time) {\r\n if (this.watchDogTimerId_ != null) {\r\n // assertion\r\n throw new Error('WatchDog timer not null');\r\n }\r\n this.watchDogTimerId_ =\r\n requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);\r\n};\r\n\r\n\r\n/**\r\n * Cancels the watchdog timer if it has been started.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.cancelWatchDogTimer_ = function() {\r\n if (this.watchDogTimerId_) {\r\n goog.global.clearTimeout(this.watchDogTimerId_);\r\n this.watchDogTimerId_ = null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when the watchdog timer is triggered. It also handles a case where it\r\n * is called too early which we suspect may be happening sometimes\r\n * (not sure why)\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.onWatchDogTimeout_ = function() {\r\n this.watchDogTimerId_ = null;\r\n var now = goog.now();\r\n if (now - this.watchDogTimeoutTime_ >= 0) {\r\n this.handleTimeout_();\r\n } else {\r\n // got called too early for some reason\r\n this.channelDebug_.warning('WatchDog timer called too early');\r\n this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when the request has actually timed out. Will cleanup and notify the\r\n * channel of the failure.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.handleTimeout_ = function() {\r\n if (this.successful_) {\r\n // Should never happen.\r\n this.channelDebug_.severe(\r\n 'Received watchdog timeout even though request loaded successfully');\r\n }\r\n\r\n this.channelDebug_.timeoutResponse(this.requestUri_);\r\n\r\n // IMG or SendBeacon requests never notice if they were successful,\r\n // and always 'time out'. This fact says nothing about reachability.\r\n if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {\r\n requestStats.notifyServerReachabilityEvent(\r\n requestStats.ServerReachability.REQUEST_FAILED);\r\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);\r\n }\r\n\r\n this.cleanup_();\r\n\r\n // Set error and dispatch failure.\r\n // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.\r\n this.lastError_ = ChannelRequest.Error.TIMEOUT;\r\n this.dispatchFailure_();\r\n};\r\n\r\n\r\n/**\r\n * Notifies the channel that this request failed.\r\n * @private\r\n */\r\nChannelRequest.prototype.dispatchFailure_ = function() {\r\n if (this.channel_.isClosed() || this.cancelled_) {\r\n return;\r\n }\r\n\r\n this.channel_.onRequestComplete(this);\r\n};\r\n\r\n\r\n/**\r\n * Cleans up the objects used to make the request. This function is\r\n * idempotent.\r\n *\r\n * @private\r\n */\r\nChannelRequest.prototype.cleanup_ = function() {\r\n this.cancelWatchDogTimer_();\r\n\r\n goog.dispose(this.readyStateChangeThrottle_);\r\n this.readyStateChangeThrottle_ = null;\r\n\r\n // Stop the polling timer, if necessary.\r\n this.pollingTimer_.stop();\r\n\r\n // Unhook all event handlers.\r\n this.eventHandler_.removeAll();\r\n\r\n if (this.xmlHttp_) {\r\n // clear out this.xmlHttp_ before aborting so we handle getting reentered\r\n // inside abort\r\n var xmlhttp = this.xmlHttp_;\r\n this.xmlHttp_ = null;\r\n xmlhttp.abort();\r\n xmlhttp.dispose();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Indicates whether the request was successful. Only valid after the handler\r\n * is called to indicate completion of the request.\r\n *\r\n * @return {boolean} True if the request succeeded.\r\n */\r\nChannelRequest.prototype.getSuccess = function() {\r\n return this.successful_;\r\n};\r\n\r\n\r\n/**\r\n * If the request was not successful, returns the reason.\r\n *\r\n * @return {?ChannelRequest.Error} The last error.\r\n */\r\nChannelRequest.prototype.getLastError = function() {\r\n return this.lastError_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the status code of the last request.\r\n * @return {number} The status code of the last request.\r\n */\r\nChannelRequest.prototype.getLastStatusCode = function() {\r\n return this.lastStatusCode_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the session id for this channel.\r\n *\r\n * @return {string|undefined} The session ID.\r\n */\r\nChannelRequest.prototype.getSessionId = function() {\r\n return this.sid_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the request id for this request. Each request has a unique request\r\n * id and the request IDs are a sequential increasing count.\r\n *\r\n * @return {string|number|undefined} The request ID.\r\n */\r\nChannelRequest.prototype.getRequestId = function() {\r\n return this.rid_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the data for a post, if this request is a post.\r\n *\r\n * @return {?string} The POST data provided by the request initiator.\r\n */\r\nChannelRequest.prototype.getPostData = function() {\r\n return this.postData_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the XhrIo request object.\r\n *\r\n * @return {?goog.net.XhrIo} Any XhrIo request created for this object.\r\n */\r\nChannelRequest.prototype.getXhr = function() {\r\n return this.xmlHttp_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the time that the request started, if it has started.\r\n *\r\n * @return {?number} The time the request started, as returned by goog.now().\r\n */\r\nChannelRequest.prototype.getRequestStartTime = function() {\r\n return this.requestStartTime_;\r\n};\r\n\r\n\r\n/**\r\n * Helper to call the callback's onRequestData, which catches any\r\n * exception.\r\n * @param {string} data The request data.\r\n * @private\r\n */\r\nChannelRequest.prototype.safeOnRequestData_ = function(data) {\r\n try {\r\n this.channel_.onRequestData(this, data);\r\n var stats = requestStats.ServerReachability;\r\n requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);\r\n } catch (e) {\r\n // Dump debug info, but keep going without closing the channel.\r\n this.channelDebug_.dumpException(e, 'Error in httprequest callback');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Convenience factory method.\r\n *\r\n * @param {Channel} channel The channel object that owns this request.\r\n * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.\r\n * @param {string=} opt_sessionId The session id for the channel.\r\n * @param {string|number=} opt_requestId The request id for this request.\r\n * @param {number=} opt_retryId The retry id for this request.\r\n * @return {!ChannelRequest} The created channel request.\r\n */\r\nChannelRequest.createChannelRequest = function(\r\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\r\n return new ChannelRequest(\r\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);\r\n};\r\n}); // goog.scope\r\n","// Copyright 2018 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A single module to define user-agent specific environment\r\n * details.\r\n */\r\n\r\ngoog.module('goog.labs.net.webChannel.environment');\r\n\r\ngoog.module.declareLegacyNamespace();\r\n\r\nvar userAgent = goog.require('goog.userAgent');\r\n\r\n\r\n/**\r\n * The default polling interval in millis for Edge.\r\n *\r\n * Currently on edge, new-chunk events may be not be fired (at all) if a new\r\n * chunk arrives within 50ms following the previous chunk. This may be fixed\r\n * in future, which requires changes to the whatwg spec too.\r\n *\r\n * @private @const {number}\r\n */\r\nvar EDGE_POLLING_INTERVAL_ = 125;\r\n\r\n\r\n/**\r\n * History:\r\n *\r\n * IE11 is still using Trident, the traditional engine for IE.\r\n * Edge is using EdgeHTML, a fork of Trident. We are seeing the same issue\r\n * on IE-11 (reported in 2017), so treat IE the same as Edge for now.\r\n *\r\n * We used to do polling for Opera (only) with an 250ms interval, because Opera\r\n * only fires readyState == INTERACTIVE once. Opera switched to WebKit in 2013,\r\n * and then to Blink (chrome).\r\n *\r\n * TODO(user): check the raw UA string to keep polling for old, mobile operas\r\n * that may still be affected. For old Opera, double the polling interval\r\n * to 250ms.\r\n *\r\n * @return {boolean} True if polling is required with XHR.\r\n */\r\nexports.isPollingRequired = function() {\r\n return userAgent.EDGE_OR_IE;\r\n};\r\n\r\n\r\n/**\r\n * How often to poll (in MS) for changes to responseText in browsers that don't\r\n * fire onreadystatechange during incremental loading of the response body.\r\n *\r\n * @return {number|undefined} The polling interval (MS) for the current U-A;\r\n * or undefined if polling is not supposed to be enabled.\r\n */\r\nexports.getPollingInterval = function() {\r\n if (userAgent.EDGE_OR_IE) {\r\n return EDGE_POLLING_INTERVAL_;\r\n }\r\n\r\n return undefined;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Base WebChannel implementation.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.WebChannelBase');\r\n\r\ngoog.require('goog.Uri');\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.async.run');\r\ngoog.require('goog.debug.TextFormatter');\r\ngoog.require('goog.json');\r\ngoog.require('goog.labs.net.webChannel.BaseTestChannel');\r\ngoog.require('goog.labs.net.webChannel.Channel');\r\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\r\ngoog.require('goog.labs.net.webChannel.ConnectionState');\r\ngoog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\ngoog.require('goog.labs.net.webChannel.Wire');\r\ngoog.require('goog.labs.net.webChannel.WireV8');\r\ngoog.require('goog.labs.net.webChannel.netUtils');\r\ngoog.require('goog.labs.net.webChannel.requestStats');\r\ngoog.require('goog.log');\r\ngoog.require('goog.net.WebChannel');\r\ngoog.require('goog.net.XhrIo');\r\ngoog.require('goog.net.XmlHttpFactory');\r\ngoog.require('goog.net.rpc.HttpCors');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.CircularBuffer');\r\n\r\ngoog.scope(function() {\r\nvar WebChannel = goog.net.WebChannel;\r\nvar BaseTestChannel = goog.labs.net.webChannel.BaseTestChannel;\r\nvar ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\r\nvar ConnectionState = goog.labs.net.webChannel.ConnectionState;\r\nvar ForwardChannelRequestPool =\r\n goog.labs.net.webChannel.ForwardChannelRequestPool;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\nvar WireV8 = goog.labs.net.webChannel.WireV8;\r\nvar netUtils = goog.labs.net.webChannel.netUtils;\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\n\r\nvar httpCors = goog.module.get('goog.net.rpc.HttpCors');\r\n\r\n\r\n/**\r\n * This WebChannel implementation is branched off goog.net.BrowserChannel\r\n * for now. Ongoing changes to goog.net.BrowserChannel will be back\r\n * ported to this implementation as needed.\r\n *\r\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\r\n * WebChannel instance.\r\n * @param {number=} opt_clientVersion An application-specific version number\r\n * that is sent to the server when connected.\r\n * @param {!ConnectionState=} opt_conn Previously determined connection\r\n * conditions.\r\n * @constructor\r\n * @struct\r\n * @implements {goog.labs.net.webChannel.Channel}\r\n */\r\ngoog.labs.net.webChannel.WebChannelBase = function(\r\n opt_options, opt_clientVersion, opt_conn) {\r\n /**\r\n * The client library version (capabilities).\r\n * @private {number}\r\n */\r\n this.clientVersion_ = opt_clientVersion || 0;\r\n\r\n /**\r\n * The server library version (capabilities).\r\n * @private {number}\r\n */\r\n this.serverVersion_ = 0;\r\n\r\n\r\n /**\r\n * An array of queued maps that need to be sent to the server.\r\n * @private {!Array<Wire.QueuedMap>}\r\n */\r\n this.outgoingMaps_ = [];\r\n\r\n /**\r\n * The channel debug used for logging\r\n * @private {!WebChannelDebug}\r\n */\r\n this.channelDebug_ = new WebChannelDebug();\r\n\r\n /**\r\n * Previous connectivity test results.\r\n * @private {!ConnectionState}\r\n */\r\n this.connState_ = opt_conn || new ConnectionState();\r\n\r\n /**\r\n * Extra HTTP headers to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraHeaders_ = null;\r\n\r\n /**\r\n * Extra HTTP headers to add to the init request(s) sent to the server.\r\n * @private {Object}\r\n */\r\n this.initHeaders_ = null;\r\n\r\n /**\r\n * @private {?string} The URL param name to overwrite custom HTTP headers\r\n * to bypass CORS preflight.\r\n */\r\n this.httpHeadersOverwriteParam_ = null;\r\n\r\n /**\r\n * Extra parameters to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraParams_ = null;\r\n\r\n /**\r\n * Parameter name for the http session id.\r\n * @private {?string}\r\n */\r\n this.httpSessionIdParam_ = null;\r\n\r\n /**\r\n * The http session id, to be sent with httpSessionIdParam_ with each\r\n * request after the initial handshake.\r\n * @private {?string}\r\n */\r\n this.httpSessionId_ = null;\r\n\r\n /**\r\n * The ChannelRequest object for the backchannel.\r\n * @private {ChannelRequest}\r\n */\r\n this.backChannelRequest_ = null;\r\n\r\n /**\r\n * The relative path (in the context of the the page hosting the browser\r\n * channel) for making requests to the server.\r\n * @private {?string}\r\n */\r\n this.path_ = null;\r\n\r\n /**\r\n * The absolute URI for the forwardchannel request.\r\n * @private {goog.Uri}\r\n */\r\n this.forwardChannelUri_ = null;\r\n\r\n /**\r\n * The absolute URI for the backchannel request.\r\n * @private {goog.Uri}\r\n */\r\n this.backChannelUri_ = null;\r\n\r\n /**\r\n * A subdomain prefix for using a subdomain in IE for the backchannel\r\n * requests.\r\n * @private {?string}\r\n */\r\n this.hostPrefix_ = null;\r\n\r\n /**\r\n * Whether we allow the use of a subdomain in IE for the backchannel requests.\r\n * @private {boolean}\r\n */\r\n this.allowHostPrefix_ = true;\r\n\r\n /**\r\n * The next id to use for the RID (request identifier) parameter. This\r\n * identifier uniquely identifies the forward channel request.\r\n * @private {number}\r\n */\r\n this.nextRid_ = 0;\r\n\r\n /**\r\n * The id to use for the next outgoing map. This identifier uniquely\r\n * identifies a sent map.\r\n * @private {number}\r\n */\r\n this.nextMapId_ = 0;\r\n\r\n /**\r\n * Whether to fail forward-channel requests after one try or a few tries.\r\n * @private {boolean}\r\n */\r\n this.failFast_ =\r\n !!goog.getObjectByName('internalChannelParams.failFast', opt_options);\r\n\r\n /**\r\n * The handler that receive callbacks for state changes and data.\r\n * @private {goog.labs.net.webChannel.WebChannelBase.Handler}\r\n */\r\n this.handler_ = null;\r\n\r\n /**\r\n * Timer identifier for asynchronously making a forward channel request.\r\n * This is set to true if the func is scheduled with async.run, which\r\n * is equivalent to setTimeout(0).\r\n * @private {?number|?boolean}\r\n */\r\n this.forwardChannelTimerId_ = null;\r\n\r\n /**\r\n * Timer identifier for asynchronously making a back channel request.\r\n * @private {?number}\r\n */\r\n this.backChannelTimerId_ = null;\r\n\r\n /**\r\n * Timer identifier for the timer that waits for us to retry the backchannel\r\n * in the case where it is dead and no longer receiving data.\r\n * @private {?number}\r\n */\r\n this.deadBackChannelTimerId_ = null;\r\n\r\n /**\r\n * The TestChannel object which encapsulates the logic for determining\r\n * interesting network conditions about the client.\r\n * @private {BaseTestChannel}\r\n */\r\n this.connectionTest_ = null;\r\n\r\n /**\r\n * Whether the client's network conditions can support chunked responses.\r\n * @private {?boolean}\r\n */\r\n this.useChunked_ = null;\r\n\r\n /**\r\n * Whether chunked mode is allowed. In certain debugging situations, it's\r\n * useful to disable this.\r\n * @private {boolean}\r\n */\r\n this.allowChunkedMode_ = true;\r\n\r\n /**\r\n * The array identifier of the last array received from the server for the\r\n * backchannel request.\r\n * @private {number}\r\n */\r\n this.lastArrayId_ = -1;\r\n\r\n /**\r\n * The array id of the last array sent by the server that we know about.\r\n * @private {number}\r\n */\r\n this.lastPostResponseArrayId_ = -1;\r\n\r\n /**\r\n * The last status code received.\r\n * @private {number}\r\n */\r\n this.lastStatusCode_ = -1;\r\n\r\n /**\r\n * Number of times we have retried the current forward channel request.\r\n * @private {number}\r\n */\r\n this.forwardChannelRetryCount_ = 0;\r\n\r\n /**\r\n * Number of times in a row that we have retried the current back channel\r\n * request and received no data.\r\n * @private {number}\r\n */\r\n this.backChannelRetryCount_ = 0;\r\n\r\n /**\r\n * The attempt id for the current back channel request. Starts at 1 and\r\n * increments for each reconnect. The server uses this to log if our\r\n * connection is flaky or not.\r\n * @private {number}\r\n */\r\n this.backChannelAttemptId_ = 0;\r\n\r\n /**\r\n * The base part of the time before firing next retry request. Default is 5\r\n * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})\r\n * for all retries, and linear backoff is applied to the sum for subsequent\r\n * retries.\r\n * @private {number}\r\n */\r\n this.baseRetryDelayMs_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.baseRetryDelayMs', opt_options) ||\r\n 5 * 1000;\r\n\r\n /**\r\n * A random time between 0 and this number of MS is added to the\r\n * {@link baseRetryDelayMs_}. Default is 10 seconds.\r\n * @private {number}\r\n */\r\n this.retryDelaySeedMs_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.retryDelaySeedMs', opt_options) ||\r\n 10 * 1000;\r\n\r\n /**\r\n * Maximum number of attempts to connect to the server for forward channel\r\n * requests. Defaults to 2.\r\n * @private {number}\r\n */\r\n this.forwardChannelMaxRetries_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.forwardChannelMaxRetries', opt_options) ||\r\n 2;\r\n\r\n /**\r\n * The timeout in milliseconds for a forward channel request. Defaults to 20\r\n * seconds. Note that part of this timeout can be randomized.\r\n * @private {number}\r\n */\r\n this.forwardChannelRequestTimeoutMs_ =\r\n goog.getObjectByName(\r\n 'internalChannelParams.forwardChannelRequestTimeoutMs',\r\n opt_options) ||\r\n 20 * 1000;\r\n\r\n /**\r\n * The custom factory used to create XMLHttpRequest objects.\r\n * @private {!goog.net.XmlHttpFactory | undefined}\r\n */\r\n this.xmlHttpFactory_ =\r\n (opt_options && opt_options.xmlHttpFactory) || undefined;\r\n\r\n /**\r\n * The timeout in milliseconds for a back channel request. Defaults to using\r\n * the timeout configured in ChannelRequest (45s). If server-side\r\n * keepaliveInterval is known to the client, set the backchannel request\r\n * timeout to 1.5 * keepaliveInterval (ms).\r\n *\r\n * @private {number|undefined}\r\n */\r\n this.backChannelRequestTimeoutMs_ = undefined;\r\n\r\n /**\r\n * A throttle time in ms for readystatechange events for the backchannel.\r\n * Useful for throttling when ready state is INTERACTIVE (partial data).\r\n *\r\n * This throttle is useful if the server sends large data chunks down the\r\n * backchannel. It prevents examining XHR partial data on every readystate\r\n * change event. This is useful because large chunks can trigger hundreds\r\n * of readystatechange events, each of which takes ~5ms or so to handle,\r\n * in turn making the UI unresponsive for a significant period.\r\n *\r\n * If set to zero no throttle is used.\r\n * @private {number}\r\n */\r\n this.readyStateChangeThrottleMs_ = 0;\r\n\r\n /**\r\n * Whether cross origin requests are supported for the channel.\r\n *\r\n * See {@link goog.net.XhrIo#setWithCredentials}.\r\n * @private {boolean}\r\n */\r\n this.supportsCrossDomainXhrs_ =\r\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\r\n\r\n /**\r\n * The current session id.\r\n * @private {string}\r\n */\r\n this.sid_ = '';\r\n\r\n /**\r\n * The current ChannelRequest pool for the forward channel.\r\n * @private {!ForwardChannelRequestPool}\r\n */\r\n this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(\r\n opt_options && opt_options.concurrentRequestLimit);\r\n\r\n /**\r\n * The V8 codec.\r\n * @private {!WireV8}\r\n */\r\n this.wireCodec_ = new WireV8();\r\n\r\n /**\r\n * Whether to run the channel test as a background process to not block\r\n * the OPEN event.\r\n *\r\n * @private {boolean}\r\n */\r\n this.backgroundChannelTest_ =\r\n opt_options && goog.isDef(opt_options.backgroundChannelTest) ?\r\n opt_options.backgroundChannelTest :\r\n true;\r\n\r\n /**\r\n * Whether to turn on the fast handshake behavior.\r\n *\r\n * @private {boolean}\r\n */\r\n this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;\r\n\r\n if (this.fastHandshake_ && !this.backgroundChannelTest_) {\r\n this.channelDebug_.warning(\r\n 'Force backgroundChannelTest when fastHandshake is enabled.');\r\n this.backgroundChannelTest_ = true;\r\n }\r\n\r\n if (opt_options && opt_options.disableRedact) {\r\n this.channelDebug_.disableRedact();\r\n }\r\n\r\n if (opt_options && opt_options.forceLongPolling) {\r\n this.allowChunkedMode_ = false;\r\n }\r\n\r\n /**\r\n * Callback when all the pending client-sent messages have been flushed.\r\n *\r\n * @private {function()|undefined}\r\n */\r\n this.forwardChannelFlushedCallback_ = undefined;\r\n};\r\n\r\nvar WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\r\n\r\n\r\n/**\r\n * The channel version that we negotiated with the server for this session.\r\n * Starts out as the version we request, and then is changed to the negotiated\r\n * version after the initial open.\r\n * @private {number}\r\n */\r\nWebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;\r\n\r\n\r\n/**\r\n * Enum type for the channel state machine.\r\n * @enum {number}\r\n */\r\nWebChannelBase.State = {\r\n /** The channel is closed. */\r\n CLOSED: 0,\r\n\r\n /** The channel has been initialized but hasn't yet initiated a connection. */\r\n INIT: 1,\r\n\r\n /** The channel is in the process of opening a connection to the server. */\r\n OPENING: 2,\r\n\r\n /** The channel is open. */\r\n OPENED: 3\r\n};\r\n\r\n\r\n/**\r\n * The current state of the WebChannel.\r\n * @private {!WebChannelBase.State}\r\n */\r\nWebChannelBase.prototype.state_ = WebChannelBase.State.INIT;\r\n\r\n\r\n/**\r\n * The timeout in milliseconds for a forward channel request.\r\n * @type {number}\r\n */\r\nWebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;\r\n\r\n\r\n/**\r\n * Maximum number of attempts to connect to the server for back channel\r\n * requests.\r\n * @type {number}\r\n */\r\nWebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;\r\n\r\n\r\n/**\r\n * A number in MS of how long we guess the maxmium amount of time a round trip\r\n * to the server should take. In the future this could be substituted with a\r\n * real measurement of the RTT.\r\n * @type {number}\r\n */\r\nWebChannelBase.RTT_ESTIMATE = 3 * 1000;\r\n\r\n\r\n/**\r\n * When retrying for an inactive channel, we will multiply the total delay by\r\n * this number.\r\n * @type {number}\r\n */\r\nWebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;\r\n\r\n\r\n/**\r\n * Enum type for identifying an error.\r\n * @enum {number}\r\n */\r\nWebChannelBase.Error = {\r\n /** Value that indicates no error has occurred. */\r\n OK: 0,\r\n\r\n /** An error due to a request failing. */\r\n REQUEST_FAILED: 2,\r\n\r\n /** An error due to the user being logged out. */\r\n LOGGED_OUT: 4,\r\n\r\n /** An error due to server response which contains no data. */\r\n NO_DATA: 5,\r\n\r\n /** An error due to a server response indicating an unknown session id */\r\n UNKNOWN_SESSION_ID: 6,\r\n\r\n /** An error due to a server response requesting to stop the channel. */\r\n STOP: 7,\r\n\r\n /** A general network error. */\r\n NETWORK: 8,\r\n\r\n /** An error due to bad data being returned from the server. */\r\n BAD_DATA: 10,\r\n\r\n /** An error due to a response that is not parsable. */\r\n BAD_RESPONSE: 11\r\n};\r\n\r\n\r\n/**\r\n * Internal enum type for the two channel types.\r\n * @enum {number}\r\n * @private\r\n */\r\nWebChannelBase.ChannelType_ = {\r\n FORWARD_CHANNEL: 1,\r\n\r\n BACK_CHANNEL: 2\r\n};\r\n\r\n\r\n/**\r\n * The maximum number of maps that can be sent in one POST. Should match\r\n * MAX_MAPS_PER_REQUEST on the server code.\r\n * @type {number}\r\n * @private\r\n */\r\nWebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;\r\n\r\n\r\n/**\r\n * The maximum number of utf-8 chars that can be sent in one GET to enable 0-RTT\r\n * handshake.\r\n *\r\n * @const @private {number}\r\n */\r\nWebChannelBase.MAX_CHARS_PER_GET_ = 4 * 1024;\r\n\r\n\r\n/**\r\n * A guess at a cutoff at which to no longer assume the backchannel is dead\r\n * when we are slow to receive data. Number in bytes.\r\n *\r\n * Assumption: The worst bandwidth we work on is 50 kilobits/sec\r\n * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout\r\n * @type {number}\r\n */\r\nWebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;\r\n\r\n\r\n/**\r\n * @return {number} The server version or 0 if undefined\r\n */\r\nWebChannelBase.prototype.getServerVersion = function() {\r\n return this.serverVersion_;\r\n};\r\n\r\n\r\n/**\r\n * @return {!ForwardChannelRequestPool} The forward channel request pool.\r\n */\r\nWebChannelBase.prototype.getForwardChannelRequestPool = function() {\r\n return this.forwardChannelRequestPool_;\r\n};\r\n\r\n\r\n/**\r\n * @return {!Object} The codec object, to be used for the test channel.\r\n */\r\nWebChannelBase.prototype.getWireCodec = function() {\r\n return this.wireCodec_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the logger.\r\n *\r\n * @return {!WebChannelDebug} The channel debug object.\r\n */\r\nWebChannelBase.prototype.getChannelDebug = function() {\r\n return this.channelDebug_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the logger.\r\n *\r\n * @param {!WebChannelDebug} channelDebug The channel debug object.\r\n */\r\nWebChannelBase.prototype.setChannelDebug = function(channelDebug) {\r\n this.channelDebug_ = channelDebug;\r\n};\r\n\r\n\r\n/**\r\n * Starts the channel. This initiates connections to the server.\r\n *\r\n * @param {string} testPath The path for the test connection.\r\n * @param {string} channelPath The path for the channel connection.\r\n * @param {!Object=} opt_extraParams Extra parameter keys and values to add to\r\n * the requests.\r\n * @param {string=} opt_oldSessionId Session ID from a previous session.\r\n * @param {number=} opt_oldArrayId The last array ID from a previous session.\r\n */\r\nWebChannelBase.prototype.connect = function(\r\n testPath, channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {\r\n this.channelDebug_.debug('connect()');\r\n\r\n requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);\r\n\r\n this.path_ = channelPath;\r\n this.extraParams_ = opt_extraParams || {};\r\n\r\n // Attach parameters about the previous session if reconnecting.\r\n if (opt_oldSessionId && goog.isDef(opt_oldArrayId)) {\r\n this.extraParams_['OSID'] = opt_oldSessionId;\r\n this.extraParams_['OAID'] = opt_oldArrayId;\r\n }\r\n\r\n if (this.backgroundChannelTest_) {\r\n this.channelDebug_.debug('connect() bypassed channel-test.');\r\n this.connState_.handshakeResult = [];\r\n this.connState_.bufferingProxyResult = false;\r\n\r\n // TODO(user): merge states with background channel test\r\n // requestStats.setTimeout(goog.bind(this.connectTest_, this, testPath), 0);\r\n // this.connectChannel_();\r\n }\r\n\r\n this.connectTest_(testPath);\r\n};\r\n\r\n\r\n/**\r\n * Disconnects and closes the channel.\r\n */\r\nWebChannelBase.prototype.disconnect = function() {\r\n this.channelDebug_.debug('disconnect()');\r\n\r\n this.cancelRequests_();\r\n\r\n if (this.state_ == WebChannelBase.State.OPENED) {\r\n var rid = this.nextRid_++;\r\n var uri = this.forwardChannelUri_.clone();\r\n uri.setParameterValue('SID', this.sid_);\r\n uri.setParameterValue('RID', rid);\r\n uri.setParameterValue('TYPE', 'terminate');\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n var request = ChannelRequest.createChannelRequest(\r\n this, this.channelDebug_, this.sid_, rid);\r\n request.sendCloseRequest(uri);\r\n }\r\n\r\n this.onClose_();\r\n};\r\n\r\n\r\n/**\r\n * Returns the session id of the channel. Only available after the\r\n * channel has been opened.\r\n * @return {string} Session ID.\r\n */\r\nWebChannelBase.prototype.getSessionId = function() {\r\n return this.sid_;\r\n};\r\n\r\n\r\n/**\r\n * Starts the test channel to determine network conditions.\r\n *\r\n * @param {string} testPath The relative PATH for the test connection.\r\n * @private\r\n */\r\nWebChannelBase.prototype.connectTest_ = function(testPath) {\r\n this.channelDebug_.debug('connectTest_()');\r\n if (!this.okToMakeRequest_()) {\r\n return; // channel is cancelled\r\n }\r\n this.connectionTest_ = new BaseTestChannel(this, this.channelDebug_);\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n this.connectionTest_.setExtraHeaders(this.extraHeaders_);\r\n }\r\n\r\n var urlPath = testPath;\r\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\r\n urlPath = httpCors.setHttpHeadersWithOverwriteParam(\r\n testPath, this.httpHeadersOverwriteParam_, this.extraHeaders_);\r\n }\r\n\r\n this.connectionTest_.connect(/** @type {string} */ (urlPath));\r\n};\r\n\r\n\r\n/**\r\n * Starts the regular channel which is run after the test channel is complete.\r\n * @private\r\n */\r\nWebChannelBase.prototype.connectChannel_ = function() {\r\n this.channelDebug_.debug('connectChannel_()');\r\n this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);\r\n this.forwardChannelUri_ =\r\n this.getForwardChannelUri(/** @type {string} */ (this.path_));\r\n this.ensureForwardChannel_();\r\n};\r\n\r\n\r\n/**\r\n * Cancels all outstanding requests.\r\n * @private\r\n */\r\nWebChannelBase.prototype.cancelRequests_ = function() {\r\n if (this.connectionTest_) {\r\n this.connectionTest_.abort();\r\n this.connectionTest_ = null;\r\n }\r\n\r\n if (this.backChannelRequest_) {\r\n this.backChannelRequest_.cancel();\r\n this.backChannelRequest_ = null;\r\n }\r\n\r\n if (this.backChannelTimerId_) {\r\n goog.global.clearTimeout(this.backChannelTimerId_);\r\n this.backChannelTimerId_ = null;\r\n }\r\n\r\n this.clearDeadBackchannelTimer_();\r\n\r\n this.forwardChannelRequestPool_.cancel();\r\n\r\n if (this.forwardChannelTimerId_) {\r\n this.clearForwardChannelTimer_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears the forward channel timer.\r\n * @private\r\n */\r\nWebChannelBase.prototype.clearForwardChannelTimer_ = function() {\r\n if (goog.isNumber(this.forwardChannelTimerId_)) {\r\n goog.global.clearTimeout(this.forwardChannelTimerId_);\r\n }\r\n\r\n this.forwardChannelTimerId_ = null;\r\n};\r\n\r\n\r\n/**\r\n * Returns the extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @return {Object} The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.getExtraHeaders = function() {\r\n return this.extraHeaders_;\r\n};\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @param {Object} extraHeaders The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {\r\n this.extraHeaders_ = extraHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Returns the extra HTTP headers to add to the init requests\r\n * sent to the server.\r\n *\r\n * @return {Object} The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.getInitHeaders = function() {\r\n return this.initHeaders_;\r\n};\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to the init requests sent to the server.\r\n *\r\n * @param {Object} initHeaders The HTTP headers, or null.\r\n */\r\nWebChannelBase.prototype.setInitHeaders = function(initHeaders) {\r\n this.initHeaders_ = initHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Sets the URL param name to overwrite custom HTTP headers.\r\n *\r\n * @param {string} httpHeadersOverwriteParam The URL param name.\r\n */\r\nWebChannelBase.prototype.setHttpHeadersOverwriteParam = function(\r\n httpHeadersOverwriteParam) {\r\n this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {\r\n this.httpSessionIdParam_ = httpSessionIdParam;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getHttpSessionIdParam = function() {\r\n return this.httpSessionIdParam_;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {\r\n this.httpSessionId_ = httpSessionId;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getHttpSessionId = function() {\r\n return this.httpSessionId_;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getBackgroundChannelTest = function() {\r\n return this.backgroundChannelTest_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the throttle for handling onreadystatechange events for the request.\r\n *\r\n * @param {number} throttle The throttle in ms. A value of zero indicates\r\n * no throttle.\r\n */\r\nWebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {\r\n this.readyStateChangeThrottleMs_ = throttle;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether cross origin requests are supported for the channel.\r\n *\r\n * Setting this allows the creation of requests to secondary domains and\r\n * sends XHRs with the CORS withCredentials bit set to true.\r\n *\r\n * In order for cross-origin requests to work, the server will also need to set\r\n * CORS response headers as per:\r\n * https://developer.mozilla.org/en-US/docs/HTTP_access_control\r\n *\r\n * See {@link goog.net.XhrIo#setWithCredentials}.\r\n * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.\r\n */\r\nWebChannelBase.prototype.setSupportsCrossDomainXhrs = function(\r\n supportCrossDomain) {\r\n this.supportsCrossDomainXhrs_ = supportCrossDomain;\r\n};\r\n\r\n\r\n/**\r\n * Returns the handler used for channel callback events.\r\n *\r\n * @return {WebChannelBase.Handler} The handler.\r\n */\r\nWebChannelBase.prototype.getHandler = function() {\r\n return this.handler_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the handler used for channel callback events.\r\n * @param {WebChannelBase.Handler} handler The handler to set.\r\n */\r\nWebChannelBase.prototype.setHandler = function(handler) {\r\n this.handler_ = handler;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the channel allows the use of a subdomain. There may be\r\n * cases where this isn't allowed.\r\n * @return {boolean} Whether a host prefix is allowed.\r\n */\r\nWebChannelBase.prototype.getAllowHostPrefix = function() {\r\n return this.allowHostPrefix_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether the channel allows the use of a subdomain. There may be cases\r\n * where this isn't allowed, for example, logging in with troutboard where\r\n * using a subdomain causes Apache to force the user to authenticate twice.\r\n * @param {boolean} allowHostPrefix Whether a host prefix is allowed.\r\n */\r\nWebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {\r\n this.allowHostPrefix_ = allowHostPrefix;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the channel is buffered or not. This state is valid for\r\n * querying only after the test connection has completed. This may be\r\n * queried in the WebChannelBase.okToMakeRequest() callback.\r\n * A channel may be buffered if the test connection determines that\r\n * a chunked response could not be sent down within a suitable time.\r\n * @return {boolean} Whether the channel is buffered.\r\n */\r\nWebChannelBase.prototype.isBuffered = function() {\r\n return !this.useChunked_;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether chunked mode is allowed. In certain debugging situations,\r\n * it's useful for the application to have a way to disable chunked mode for a\r\n * user.\r\n\r\n * @return {boolean} Whether chunked mode is allowed.\r\n */\r\nWebChannelBase.prototype.getAllowChunkedMode = function() {\r\n return this.allowChunkedMode_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether chunked mode is allowed. In certain debugging situations, it's\r\n * useful for the application to have a way to disable chunked mode for a user.\r\n * @param {boolean} allowChunkedMode Whether chunked mode is allowed.\r\n */\r\nWebChannelBase.prototype.setAllowChunkedMode = function(allowChunkedMode) {\r\n this.allowChunkedMode_ = allowChunkedMode;\r\n};\r\n\r\n\r\n/**\r\n * Sends a request to the server. The format of the request is a Map data\r\n * structure of key/value pairs. These maps are then encoded in a format\r\n * suitable for the wire and then reconstituted as a Map data structure that\r\n * the server can process.\r\n * @param {!Object|!goog.structs.Map} map The map to send.\r\n * @param {!Object=} opt_context The context associated with the map.\r\n */\r\nWebChannelBase.prototype.sendMap = function(map, opt_context) {\r\n goog.asserts.assert(\r\n this.state_ != WebChannelBase.State.CLOSED,\r\n 'Invalid operation: sending map when state is closed');\r\n\r\n // We can only send 1000 maps per POST, but typically we should never have\r\n // that much to send, so warn if we exceed that (we still send all the maps).\r\n if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {\r\n // severe() is temporary so that we get these uploaded and can figure out\r\n // what's causing them. Afterwards can change to warning().\r\n this.channelDebug_.severe(function() {\r\n return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +\r\n ' queued maps upon queueing ' + goog.json.serialize(map);\r\n });\r\n }\r\n\r\n this.outgoingMaps_.push(\r\n new Wire.QueuedMap(this.nextMapId_++, map, opt_context));\r\n\r\n // Messages need be buffered during OPENING to avoid server-side race\r\n if (this.state_ == WebChannelBase.State.OPENED) {\r\n this.ensureForwardChannel_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * When set to true, this changes the behavior of the forward channel so it\r\n * will not retry requests; it will fail after one network failure, and if\r\n * there was already one network failure, the request will fail immediately.\r\n * @param {boolean} failFast Whether or not to fail fast.\r\n */\r\nWebChannelBase.prototype.setFailFast = function(failFast) {\r\n this.failFast_ = failFast;\r\n this.channelDebug_.info('setFailFast: ' + failFast);\r\n if ((this.forwardChannelRequestPool_.hasPendingRequest() ||\r\n this.forwardChannelTimerId_) &&\r\n this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {\r\n var self = this;\r\n this.channelDebug_.info(function() {\r\n return 'Retry count ' + self.forwardChannelRetryCount_ +\r\n ' > new maxRetries ' + self.getForwardChannelMaxRetries() +\r\n '. Fail immediately!';\r\n });\r\n\r\n if (!this.forwardChannelRequestPool_.forceComplete(\r\n goog.bind(this.onRequestComplete, this))) {\r\n // i.e., this.forwardChannelTimerId_\r\n this.clearForwardChannelTimer_();\r\n // The error code from the last failed request is gone, so just use a\r\n // generic one.\r\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The max number of forward-channel retries, which will be 0\r\n * in fail-fast mode.\r\n */\r\nWebChannelBase.prototype.getForwardChannelMaxRetries = function() {\r\n return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the maximum number of attempts to connect to the server for forward\r\n * channel requests.\r\n * @param {number} retries The maximum number of attempts.\r\n */\r\nWebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {\r\n this.forwardChannelMaxRetries_ = retries;\r\n};\r\n\r\n\r\n/**\r\n * Sets the timeout for a forward channel request.\r\n * @param {number} timeoutMs The timeout in milliseconds.\r\n */\r\nWebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {\r\n this.forwardChannelRequestTimeoutMs_ = timeoutMs;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The max number of back-channel retries, which is a constant.\r\n */\r\nWebChannelBase.prototype.getBackChannelMaxRetries = function() {\r\n // Back-channel retries is a constant.\r\n return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.isClosed = function() {\r\n return this.state_ == WebChannelBase.State.CLOSED;\r\n};\r\n\r\n\r\n/**\r\n * Returns the channel state.\r\n * @return {WebChannelBase.State} The current state of the channel.\r\n */\r\nWebChannelBase.prototype.getState = function() {\r\n return this.state_;\r\n};\r\n\r\n\r\n/**\r\n * Return the last status code received for a request.\r\n * @return {number} The last status code received for a request.\r\n */\r\nWebChannelBase.prototype.getLastStatusCode = function() {\r\n return this.lastStatusCode_;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The last array id received.\r\n */\r\nWebChannelBase.prototype.getLastArrayId = function() {\r\n return this.lastArrayId_;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether there are outstanding requests servicing the channel.\r\n * @return {boolean} true if there are outstanding requests.\r\n */\r\nWebChannelBase.prototype.hasOutstandingRequests = function() {\r\n return this.getOutstandingRequests_() != 0;\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of outstanding requests.\r\n * @return {number} The number of outstanding requests to the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.getOutstandingRequests_ = function() {\r\n var count = 0;\r\n if (this.backChannelRequest_) {\r\n count++;\r\n }\r\n count += this.forwardChannelRequestPool_.getRequestCount();\r\n return count;\r\n};\r\n\r\n\r\n/**\r\n * Ensures that a forward channel request is scheduled.\r\n * @private\r\n */\r\nWebChannelBase.prototype.ensureForwardChannel_ = function() {\r\n if (this.forwardChannelRequestPool_.isFull()) {\r\n // enough connection in process - no need to start a new request\r\n return;\r\n }\r\n\r\n if (this.forwardChannelTimerId_) {\r\n // no need to start a new request - one is already scheduled\r\n return;\r\n }\r\n\r\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\r\n // from chrome/firefox background tabs\r\n this.forwardChannelTimerId_ = true;\r\n goog.async.run(this.onStartForwardChannelTimer_, this);\r\n\r\n this.forwardChannelRetryCount_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * Schedules a forward-channel retry for the specified request, unless the max\r\n * retries has been reached.\r\n * @param {!ChannelRequest} request The failed request to retry.\r\n * @return {boolean} true iff a retry was scheduled.\r\n * @private\r\n */\r\nWebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {\r\n if (this.forwardChannelRequestPool_.getRequestCount() >=\r\n this.forwardChannelRequestPool_.getMaxSize() -\r\n (this.forwardChannelTimerId_ ? 1 : 0)) {\r\n // Should be impossible to be called in this state.\r\n this.channelDebug_.severe('Unexpected retry request is scheduled.');\r\n return false;\r\n }\r\n\r\n if (this.forwardChannelTimerId_) {\r\n this.channelDebug_.debug(\r\n 'Use the retry request that is already scheduled.');\r\n this.outgoingMaps_ =\r\n request.getPendingMessages().concat(this.outgoingMaps_);\r\n return true;\r\n }\r\n\r\n // No retry for open_() and fail-fast\r\n if (this.state_ == WebChannelBase.State.INIT ||\r\n this.state_ == WebChannelBase.State.OPENING ||\r\n (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {\r\n return false;\r\n }\r\n\r\n this.channelDebug_.debug('Going to retry POST');\r\n\r\n this.forwardChannelTimerId_ = requestStats.setTimeout(\r\n goog.bind(this.onStartForwardChannelTimer_, this, request),\r\n this.getRetryTime_(this.forwardChannelRetryCount_));\r\n this.forwardChannelRetryCount_++;\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Timer callback for ensureForwardChannel\r\n * @param {ChannelRequest=} opt_retryRequest A failed request\r\n * to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onStartForwardChannelTimer_ = function(\r\n opt_retryRequest) {\r\n // null is possible if scheduled with async.run\r\n if (this.forwardChannelTimerId_) {\r\n this.forwardChannelTimerId_ = null;\r\n this.startForwardChannel_(opt_retryRequest);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Begins a new forward channel operation to the server.\r\n * @param {ChannelRequest=} opt_retryRequest A failed request to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {\r\n this.channelDebug_.debug('startForwardChannel_');\r\n if (!this.okToMakeRequest_()) {\r\n return; // channel is cancelled\r\n } else if (this.state_ == WebChannelBase.State.INIT) {\r\n if (opt_retryRequest) {\r\n this.channelDebug_.severe('Not supposed to retry the open');\r\n return;\r\n }\r\n this.open_();\r\n this.state_ = WebChannelBase.State.OPENING;\r\n } else if (this.state_ == WebChannelBase.State.OPENED) {\r\n if (opt_retryRequest) {\r\n this.makeForwardChannelRequest_(opt_retryRequest);\r\n return;\r\n }\r\n\r\n if (this.outgoingMaps_.length == 0) {\r\n this.channelDebug_.debug(\r\n 'startForwardChannel_ returned: ' +\r\n 'nothing to send');\r\n // no need to start a new forward channel request\r\n return;\r\n }\r\n\r\n if (this.forwardChannelRequestPool_.isFull()) {\r\n // Should be impossible to be called in this state.\r\n this.channelDebug_.severe(\r\n 'startForwardChannel_ returned: ' +\r\n 'connection already in progress');\r\n return;\r\n }\r\n\r\n this.makeForwardChannelRequest_();\r\n this.channelDebug_.debug('startForwardChannel_ finished, sent request');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Establishes a new channel session with the the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.open_ = function() {\r\n this.channelDebug_.debug('open_()');\r\n this.nextRid_ = Math.floor(Math.random() * 100000);\r\n\r\n var rid = this.nextRid_++;\r\n var request =\r\n ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);\r\n\r\n // mix the init headers\r\n var extraHeaders = this.extraHeaders_;\r\n if (this.initHeaders_) {\r\n if (extraHeaders) {\r\n extraHeaders = goog.object.clone(extraHeaders);\r\n goog.object.extend(extraHeaders, this.initHeaders_);\r\n } else {\r\n extraHeaders = this.initHeaders_;\r\n }\r\n }\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n request.setExtraHeaders(extraHeaders);\r\n }\r\n\r\n var requestText = this.dequeueOutgoingMaps_(\r\n request,\r\n this.fastHandshake_ ? this.getMaxNumMessagesForFastHandshake_() :\r\n WebChannelBase.MAX_MAPS_PER_REQUEST_);\r\n\r\n var uri = this.forwardChannelUri_.clone();\r\n uri.setParameterValue('RID', rid);\r\n\r\n if (this.clientVersion_ > 0) {\r\n uri.setParameterValue('CVER', this.clientVersion_);\r\n }\r\n\r\n // http-session-id to be generated as the response\r\n if (this.getBackgroundChannelTest() && this.getHttpSessionIdParam()) {\r\n uri.setParameterValue(\r\n WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());\r\n }\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n if (this.httpHeadersOverwriteParam_ && extraHeaders) {\r\n httpCors.setHttpHeadersWithOverwriteParam(\r\n uri, this.httpHeadersOverwriteParam_, extraHeaders);\r\n }\r\n\r\n this.forwardChannelRequestPool_.addRequest(request);\r\n\r\n // Check the option and use GET to enable QUIC 0-RTT\r\n if (this.fastHandshake_) {\r\n uri.setParameterValue('$req', requestText);\r\n\r\n // enable handshake upgrade\r\n uri.setParameterValue('SID', 'null');\r\n request.setDecodeInitialResponse();\r\n\r\n request.xmlHttpPost(uri, null, true); // Send as a GET\r\n } else {\r\n request.xmlHttpPost(uri, requestText, true);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of raw JSON messages to be encoded\r\n * with the fast-handshake (GET) request, including zero. If messages are not\r\n * encoded as raw JSON data, return WebChannelBase.MAX_MAPS_PER_REQUEST_\r\n * @private\r\n */\r\nWebChannelBase.prototype.getMaxNumMessagesForFastHandshake_ = function() {\r\n var total = 0;\r\n for (var i = 0; i < this.outgoingMaps_.length; i++) {\r\n var map = this.outgoingMaps_[i];\r\n var size = map.getRawDataSize();\r\n if (size === undefined) {\r\n break;\r\n }\r\n total += size;\r\n\r\n if (total > WebChannelBase.MAX_CHARS_PER_GET_) {\r\n return i;\r\n }\r\n\r\n if (total === WebChannelBase.MAX_CHARS_PER_GET_ ||\r\n i === this.outgoingMaps_.length - 1) {\r\n return i + 1;\r\n }\r\n }\r\n\r\n return WebChannelBase.MAX_MAPS_PER_REQUEST_;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Makes a forward channel request using XMLHTTP.\r\n * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.makeForwardChannelRequest_ = function(\r\n opt_retryRequest) {\r\n var rid;\r\n if (opt_retryRequest) {\r\n rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry\r\n } else {\r\n rid = this.nextRid_++;\r\n }\r\n\r\n var uri = this.forwardChannelUri_.clone();\r\n uri.setParameterValue('SID', this.sid_);\r\n uri.setParameterValue('RID', rid);\r\n uri.setParameterValue('AID', this.lastArrayId_);\r\n // Add the additional reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\r\n httpCors.setHttpHeadersWithOverwriteParam(\r\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\r\n }\r\n\r\n var request = ChannelRequest.createChannelRequest(\r\n this, this.channelDebug_, this.sid_, rid,\r\n this.forwardChannelRetryCount_ + 1);\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n request.setExtraHeaders(this.extraHeaders_);\r\n }\r\n\r\n var requestText;\r\n if (opt_retryRequest) {\r\n this.requeuePendingMaps_(opt_retryRequest);\r\n }\r\n requestText =\r\n this.dequeueOutgoingMaps_(request, WebChannelBase.MAX_MAPS_PER_REQUEST_);\r\n\r\n // Randomize from 50%-100% of the forward channel timeout to avoid\r\n // a big hit if servers happen to die at once.\r\n request.setTimeout(\r\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +\r\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));\r\n this.forwardChannelRequestPool_.addRequest(request);\r\n request.xmlHttpPost(uri, requestText, true);\r\n};\r\n\r\n\r\n/**\r\n * Adds the additional parameters from the handler to the given URI.\r\n * @param {!goog.Uri} uri The URI to add the parameters to.\r\n * @private\r\n */\r\nWebChannelBase.prototype.addAdditionalParams_ = function(uri) {\r\n // Add the additional reconnect parameters as needed.\r\n if (this.handler_) {\r\n var params = this.handler_.getAdditionalParams(this);\r\n if (params) {\r\n goog.structs.forEach(params, function(value, key, coll) {\r\n uri.setParameterValue(key, value);\r\n });\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns the request text from the outgoing maps and resets it.\r\n * @param {!ChannelRequest} request The new request for sending the messages.\r\n * @param {number} maxNum The maximum number of messages to be encoded\r\n * @return {string} The encoded request text created from all the currently\r\n * queued outgoing maps.\r\n * @private\r\n */\r\nWebChannelBase.prototype.dequeueOutgoingMaps_ = function(request, maxNum) {\r\n var count = Math.min(this.outgoingMaps_.length, maxNum);\r\n\r\n var badMapHandler = this.handler_ ?\r\n goog.bind(this.handler_.badMapError, this.handler_, this) :\r\n null;\r\n var result = this.wireCodec_.encodeMessageQueue(\r\n this.outgoingMaps_, count, badMapHandler);\r\n\r\n request.setPendingMessages(this.outgoingMaps_.splice(0, count));\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Requeues unacknowledged sent arrays for retransmission in the next forward\r\n * channel request.\r\n * @param {!ChannelRequest} retryRequest A failed request to retry.\r\n * @private\r\n */\r\nWebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {\r\n this.outgoingMaps_ =\r\n retryRequest.getPendingMessages().concat(this.outgoingMaps_);\r\n};\r\n\r\n\r\n/**\r\n * Ensures there is a backchannel request for receiving data from the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.ensureBackChannel_ = function() {\r\n if (this.backChannelRequest_) {\r\n // already have one\r\n return;\r\n }\r\n\r\n if (this.backChannelTimerId_) {\r\n // no need to start a new request - one is already scheduled\r\n return;\r\n }\r\n\r\n this.backChannelAttemptId_ = 1;\r\n\r\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\r\n // from chrome/firefox background tabs\r\n // backChannelTimerId_ stays unset, as with setTimeout(0)\r\n goog.async.run(this.onStartBackChannelTimer_, this);\r\n\r\n this.backChannelRetryCount_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * Schedules a back-channel retry, unless the max retries has been reached.\r\n * @return {boolean} true iff a retry was scheduled.\r\n * @private\r\n */\r\nWebChannelBase.prototype.maybeRetryBackChannel_ = function() {\r\n if (this.backChannelRequest_ || this.backChannelTimerId_) {\r\n // Should be impossible to be called in this state.\r\n this.channelDebug_.severe('Request already in progress');\r\n return false;\r\n }\r\n\r\n if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {\r\n return false;\r\n }\r\n\r\n this.channelDebug_.debug('Going to retry GET');\r\n\r\n this.backChannelAttemptId_++;\r\n this.backChannelTimerId_ = requestStats.setTimeout(\r\n goog.bind(this.onStartBackChannelTimer_, this),\r\n this.getRetryTime_(this.backChannelRetryCount_));\r\n this.backChannelRetryCount_++;\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Timer callback for ensureBackChannel_.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onStartBackChannelTimer_ = function() {\r\n this.backChannelTimerId_ = null;\r\n this.startBackChannel_();\r\n};\r\n\r\n\r\n/**\r\n * Begins a new back channel operation to the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.startBackChannel_ = function() {\r\n if (!this.okToMakeRequest_()) {\r\n // channel is cancelled\r\n return;\r\n }\r\n\r\n this.channelDebug_.debug('Creating new HttpRequest');\r\n this.backChannelRequest_ = ChannelRequest.createChannelRequest(\r\n this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);\r\n\r\n if (this.httpHeadersOverwriteParam_ === null) {\r\n this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);\r\n }\r\n\r\n this.backChannelRequest_.setReadyStateChangeThrottle(\r\n this.readyStateChangeThrottleMs_);\r\n var uri = this.backChannelUri_.clone();\r\n uri.setParameterValue('RID', 'rpc');\r\n uri.setParameterValue('SID', this.sid_);\r\n uri.setParameterValue('CI', this.useChunked_ ? '0' : '1');\r\n uri.setParameterValue('AID', this.lastArrayId_);\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n uri.setParameterValue('TYPE', 'xmlhttp');\r\n\r\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\r\n httpCors.setHttpHeadersWithOverwriteParam(\r\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\r\n }\r\n\r\n if (this.backChannelRequestTimeoutMs_) {\r\n this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);\r\n }\r\n\r\n this.backChannelRequest_.xmlHttpGet(\r\n uri, true /* decodeChunks */, this.hostPrefix_);\r\n\r\n this.channelDebug_.debug('New Request created');\r\n};\r\n\r\n\r\n/**\r\n * Gives the handler a chance to return an error code and stop channel\r\n * execution. A handler might want to do this to check that the user is still\r\n * logged in, for example.\r\n * @private\r\n * @return {boolean} If it's OK to make a request.\r\n */\r\nWebChannelBase.prototype.okToMakeRequest_ = function() {\r\n if (this.handler_) {\r\n var result = this.handler_.okToMakeRequest(this);\r\n if (result != WebChannelBase.Error.OK) {\r\n this.channelDebug_.debug(\r\n 'Handler returned error code from okToMakeRequest');\r\n this.signalError_(result);\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.testConnectionFinished = function(\r\n testChannel, useChunked) {\r\n this.channelDebug_.debug('Test Connection Finished');\r\n\r\n // Forward channel will not be used prior to this method is called\r\n var clientProtocol = testChannel.getClientProtocol();\r\n if (clientProtocol) {\r\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\r\n }\r\n\r\n this.useChunked_ = this.allowChunkedMode_ && useChunked;\r\n this.lastStatusCode_ = testChannel.getLastStatusCode();\r\n\r\n this.connectChannel_();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.testConnectionFailure = function(\r\n testChannel, errorCode) {\r\n this.channelDebug_.debug('Test Connection Failed');\r\n this.lastStatusCode_ = testChannel.getLastStatusCode();\r\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.onRequestData = function(request, responseText) {\r\n if (this.state_ == WebChannelBase.State.CLOSED ||\r\n (this.backChannelRequest_ != request &&\r\n !this.forwardChannelRequestPool_.hasRequest(request))) {\r\n // either CLOSED or a request we don't know about (perhaps an old request)\r\n return;\r\n }\r\n this.lastStatusCode_ = request.getLastStatusCode();\r\n\r\n // first to check if request has been upgraded to backchannel\r\n if (!request.isInitialResponseDecoded() &&\r\n this.forwardChannelRequestPool_.hasRequest(request) &&\r\n this.state_ == WebChannelBase.State.OPENED) {\r\n var response;\r\n try {\r\n response = this.wireCodec_.decodeMessage(responseText);\r\n } catch (ex) {\r\n response = null;\r\n }\r\n if (goog.isArray(response) && response.length == 3) {\r\n this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);\r\n this.onForwardChannelFlushed_();\r\n } else {\r\n this.channelDebug_.debug('Bad POST response data returned');\r\n this.signalError_(WebChannelBase.Error.BAD_RESPONSE);\r\n }\r\n } else {\r\n if (request.isInitialResponseDecoded() ||\r\n this.backChannelRequest_ == request) {\r\n this.clearDeadBackchannelTimer_();\r\n }\r\n if (!goog.string.isEmptyOrWhitespace(responseText)) {\r\n var response = this.wireCodec_.decodeMessage(responseText);\r\n this.onInput_(/** @type {!Array<?>} */ (response), request);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Checks if we need call the flush callback.\r\n *\r\n * @private\r\n */\r\nWebChannelBase.prototype.onForwardChannelFlushed_ = function() {\r\n if (this.forwardChannelRequestPool_.getRequestCount() <= 1) {\r\n if (this.forwardChannelFlushedCallback_) {\r\n try {\r\n this.forwardChannelFlushedCallback_();\r\n } catch (ex) {\r\n this.channelDebug_.dumpException(\r\n ex, 'Exception from forwardChannelFlushedCallback_ ');\r\n }\r\n // reset\r\n this.forwardChannelFlushedCallback_ = undefined;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Handles a POST response from the server.\r\n * @param {Array<number>} responseValues The key value pairs in\r\n * the POST response.\r\n * @param {!ChannelRequest} forwardReq The forward channel request that\r\n * triggers this function call.\r\n * @private\r\n */\r\nWebChannelBase.prototype.handlePostResponse_ = function(\r\n responseValues, forwardReq) {\r\n // The first response value is set to 0 if server is missing backchannel.\r\n if (responseValues[0] == 0) {\r\n this.handleBackchannelMissing_(forwardReq);\r\n return;\r\n }\r\n this.lastPostResponseArrayId_ = responseValues[1];\r\n var outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;\r\n if (0 < outstandingArrays) {\r\n var numOutstandingBackchannelBytes = responseValues[2];\r\n this.channelDebug_.debug(\r\n numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +\r\n ' arrays) are outstanding on the BackChannel');\r\n if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {\r\n return;\r\n }\r\n if (!this.deadBackChannelTimerId_) {\r\n // We expect to receive data within 2 RTTs or we retry the backchannel.\r\n this.deadBackChannelTimerId_ = requestStats.setTimeout(\r\n goog.bind(this.onBackChannelDead_, this),\r\n 2 * WebChannelBase.RTT_ESTIMATE);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Handles a POST response from the server telling us that it has detected that\r\n * we have no hanging GET connection.\r\n * @param {!ChannelRequest} forwardReq The forward channel request that\r\n * triggers this function call.\r\n * @private\r\n */\r\nWebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {\r\n // As long as the back channel was started before the POST was sent,\r\n // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE\r\n // so as not to excessively retry the backchannel\r\n this.channelDebug_.debug('Server claims our backchannel is missing.');\r\n if (this.backChannelTimerId_) {\r\n this.channelDebug_.debug('But we are currently starting the request.');\r\n return;\r\n } else if (!this.backChannelRequest_) {\r\n this.channelDebug_.warning('We do not have a BackChannel established');\r\n } else if (\r\n this.backChannelRequest_.getRequestStartTime() +\r\n WebChannelBase.RTT_ESTIMATE <\r\n forwardReq.getRequestStartTime()) {\r\n this.clearDeadBackchannelTimer_();\r\n this.backChannelRequest_.cancel();\r\n this.backChannelRequest_ = null;\r\n } else {\r\n return;\r\n }\r\n this.maybeRetryBackChannel_();\r\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);\r\n};\r\n\r\n\r\n/**\r\n * Determines whether we should start the process of retrying a possibly\r\n * dead backchannel.\r\n * @param {number} outstandingBytes The number of bytes for which the server has\r\n * not yet received acknowledgement.\r\n * @return {boolean} Whether to start the backchannel retry timer.\r\n * @private\r\n */\r\nWebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {\r\n // Not too many outstanding bytes, not buffered and not after a retry.\r\n return outstandingBytes <\r\n WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&\r\n !this.isBuffered() && this.backChannelRetryCount_ == 0;\r\n};\r\n\r\n\r\n/**\r\n * Decides which host prefix should be used, if any. If there is a handler,\r\n * allows the handler to validate a host prefix provided by the server, and\r\n * optionally override it.\r\n * @param {?string} serverHostPrefix The host prefix provided by the server.\r\n * @return {?string} The host prefix to actually use, if any. Will return null\r\n * if the use of host prefixes was disabled via setAllowHostPrefix().\r\n * @override\r\n */\r\nWebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {\r\n if (this.allowHostPrefix_) {\r\n if (this.handler_) {\r\n return this.handler_.correctHostPrefix(serverHostPrefix);\r\n }\r\n return serverHostPrefix;\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Handles the timer that indicates that our backchannel is no longer able to\r\n * successfully receive data from the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onBackChannelDead_ = function() {\r\n if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) {\r\n this.deadBackChannelTimerId_ = null;\r\n this.backChannelRequest_.cancel();\r\n this.backChannelRequest_ = null;\r\n this.maybeRetryBackChannel_();\r\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears the timer that indicates that our backchannel is no longer able to\r\n * successfully receive data from the server.\r\n * @private\r\n */\r\nWebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {\r\n if (goog.isDefAndNotNull(this.deadBackChannelTimerId_)) {\r\n goog.global.clearTimeout(this.deadBackChannelTimerId_);\r\n this.deadBackChannelTimerId_ = null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns whether or not the given error/status combination is fatal or not.\r\n * On fatal errors we immediately close the session rather than retrying the\r\n * failed request.\r\n * @param {?ChannelRequest.Error} error The error code for the\r\n * failed request.\r\n * @param {number} statusCode The last HTTP status code.\r\n * @return {boolean} Whether or not the error is fatal.\r\n * @private\r\n */\r\nWebChannelBase.isFatalError_ = function(error, statusCode) {\r\n return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||\r\n (error == ChannelRequest.Error.STATUS && statusCode > 0);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.onRequestComplete = function(request) {\r\n this.channelDebug_.debug('Request complete');\r\n var type;\r\n var pendingMessages = null;\r\n if (this.backChannelRequest_ == request) {\r\n this.clearDeadBackchannelTimer_();\r\n this.backChannelRequest_ = null;\r\n type = WebChannelBase.ChannelType_.BACK_CHANNEL;\r\n } else if (this.forwardChannelRequestPool_.hasRequest(request)) {\r\n pendingMessages = request.getPendingMessages();\r\n this.forwardChannelRequestPool_.removeRequest(request);\r\n type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;\r\n } else {\r\n // return if it was an old request from a previous session\r\n return;\r\n }\r\n\r\n this.lastStatusCode_ = request.getLastStatusCode();\r\n\r\n if (this.state_ == WebChannelBase.State.CLOSED) {\r\n return;\r\n }\r\n\r\n if (request.getSuccess()) {\r\n // Yay!\r\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\r\n var size = request.getPostData() ? request.getPostData().length : 0;\r\n requestStats.notifyTimingEvent(\r\n size, goog.now() - request.getRequestStartTime(),\r\n this.forwardChannelRetryCount_);\r\n this.ensureForwardChannel_();\r\n this.onSuccess_(request);\r\n } else { // i.e., back-channel\r\n this.ensureBackChannel_();\r\n }\r\n return;\r\n }\r\n // Else unsuccessful. Fall through.\r\n\r\n var lastError = request.getLastError();\r\n if (!WebChannelBase.isFatalError_(lastError, this.lastStatusCode_)) {\r\n // Maybe retry.\r\n var self = this;\r\n this.channelDebug_.debug(function() {\r\n return 'Maybe retrying, last error: ' +\r\n ChannelRequest.errorStringFromCode(lastError, self.lastStatusCode_);\r\n });\r\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\r\n if (this.maybeRetryForwardChannel_(request)) {\r\n return;\r\n }\r\n }\r\n if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {\r\n if (this.maybeRetryBackChannel_()) {\r\n return;\r\n }\r\n }\r\n // Else exceeded max retries. Fall through.\r\n this.channelDebug_.debug('Exceeded max number of retries');\r\n } else {\r\n // Else fatal error. Fall through and mark the pending maps as failed.\r\n this.channelDebug_.debug('Not retrying due to error type');\r\n }\r\n\r\n\r\n // Abort the channel now\r\n\r\n // Record pending messages from the failed request\r\n if (pendingMessages && pendingMessages.length > 0) {\r\n this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);\r\n }\r\n\r\n this.channelDebug_.debug('Error: HTTP request failed');\r\n switch (lastError) {\r\n case ChannelRequest.Error.NO_DATA:\r\n this.signalError_(WebChannelBase.Error.NO_DATA);\r\n break;\r\n case ChannelRequest.Error.BAD_DATA:\r\n this.signalError_(WebChannelBase.Error.BAD_DATA);\r\n break;\r\n case ChannelRequest.Error.UNKNOWN_SESSION_ID:\r\n this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);\r\n break;\r\n default:\r\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\r\n break;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {number} retryCount Number of retries so far.\r\n * @return {number} Time in ms before firing next retry request.\r\n * @private\r\n */\r\nWebChannelBase.prototype.getRetryTime_ = function(retryCount) {\r\n var retryTime = this.baseRetryDelayMs_ +\r\n Math.floor(Math.random() * this.retryDelaySeedMs_);\r\n if (!this.isActive()) {\r\n this.channelDebug_.debug('Inactive channel');\r\n retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;\r\n }\r\n // Backoff for subsequent retries\r\n retryTime *= retryCount;\r\n return retryTime;\r\n};\r\n\r\n\r\n/**\r\n * @param {number} baseDelayMs The base part of the retry delay, in ms.\r\n * @param {number} delaySeedMs A random delay between 0 and this is added to\r\n * the base part.\r\n */\r\nWebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {\r\n this.baseRetryDelayMs_ = baseDelayMs;\r\n this.retryDelaySeedMs_ = delaySeedMs;\r\n};\r\n\r\n\r\n/**\r\n * Apply any handshake control headers.\r\n * @param {!ChannelRequest} request The underlying request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.applyControlHeaders_ = function(request) {\r\n if (!this.backgroundChannelTest_) {\r\n return;\r\n }\r\n\r\n var xhr = request.getXhr();\r\n if (xhr) {\r\n var clientProtocol =\r\n xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);\r\n if (clientProtocol) {\r\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\r\n }\r\n\r\n if (this.getHttpSessionIdParam()) {\r\n var httpSessionIdHeader =\r\n xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);\r\n if (httpSessionIdHeader) {\r\n this.setHttpSessionId(httpSessionIdHeader);\r\n // update the cached uri\r\n var httpSessionIdParam = this.getHttpSessionIdParam();\r\n\r\n this.forwardChannelUri_.setParameterValue(\r\n /** @type {string} */ (httpSessionIdParam), // never null\r\n httpSessionIdHeader);\r\n } else {\r\n this.channelDebug_.warning(\r\n 'Missing X_HTTP_SESSION_ID in the handshake response');\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Processes the data returned by the server.\r\n * @param {!Array<!Array<?>>} respArray The response array returned\r\n * by the server.\r\n * @param {!ChannelRequest} request The underlying request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.onInput_ = function(respArray, request) {\r\n var batch =\r\n this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;\r\n for (var i = 0; i < respArray.length; i++) {\r\n var nextArray = respArray[i];\r\n this.lastArrayId_ = nextArray[0];\r\n nextArray = nextArray[1];\r\n if (this.state_ == WebChannelBase.State.OPENING) {\r\n if (nextArray[0] == 'c') {\r\n this.sid_ = nextArray[1];\r\n this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);\r\n\r\n var negotiatedVersion = nextArray[3];\r\n if (goog.isDefAndNotNull(negotiatedVersion)) {\r\n this.channelVersion_ = negotiatedVersion;\r\n this.channelDebug_.info('VER=' + this.channelVersion_);\r\n }\r\n\r\n var negotiatedServerVersion = nextArray[4];\r\n if (goog.isDefAndNotNull(negotiatedServerVersion)) {\r\n this.serverVersion_ = negotiatedServerVersion;\r\n this.channelDebug_.info('SVER=' + this.serverVersion_);\r\n }\r\n\r\n // CVER=22\r\n var serverKeepaliveMs = nextArray[5];\r\n if (goog.isDefAndNotNull(serverKeepaliveMs) &&\r\n goog.isNumber(serverKeepaliveMs) && serverKeepaliveMs > 0) {\r\n var timeout = 1.5 * serverKeepaliveMs;\r\n this.backChannelRequestTimeoutMs_ = timeout;\r\n this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);\r\n }\r\n\r\n this.applyControlHeaders_(request);\r\n\r\n this.state_ = WebChannelBase.State.OPENED;\r\n if (this.handler_) {\r\n this.handler_.channelOpened(this);\r\n }\r\n\r\n this.startBackchannelAfterHandshake_(request);\r\n\r\n if (this.outgoingMaps_.length > 0) {\r\n this.ensureForwardChannel_();\r\n }\r\n } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\r\n // treat close also as an abort\r\n this.signalError_(WebChannelBase.Error.STOP);\r\n }\r\n } else if (this.state_ == WebChannelBase.State.OPENED) {\r\n if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\r\n if (batch && !goog.array.isEmpty(batch)) {\r\n this.handler_.channelHandleMultipleArrays(this, batch);\r\n batch.length = 0;\r\n }\r\n if (nextArray[0] == 'stop') {\r\n this.signalError_(WebChannelBase.Error.STOP);\r\n } else {\r\n this.disconnect();\r\n }\r\n } else if (nextArray[0] == 'noop') {\r\n // ignore - noop to keep connection happy\r\n } else {\r\n if (batch) {\r\n batch.push(nextArray);\r\n } else if (this.handler_) {\r\n this.handler_.channelHandleArray(this, nextArray);\r\n }\r\n }\r\n // We have received useful data on the back-channel, so clear its retry\r\n // count. We do this because back-channels by design do not complete\r\n // quickly, so on a flaky connection we could have many fail to complete\r\n // fully but still deliver a lot of data before they fail. We don't want\r\n // to count such failures towards the retry limit, because we don't want\r\n // to give up on a session if we can still receive data.\r\n this.backChannelRetryCount_ = 0;\r\n }\r\n }\r\n if (batch && !goog.array.isEmpty(batch)) {\r\n this.handler_.channelHandleMultipleArrays(this, batch);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Starts the backchannel after the handshake.\r\n *\r\n * @param {!ChannelRequest} request The underlying request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.startBackchannelAfterHandshake_ = function(request) {\r\n this.backChannelUri_ = this.getBackChannelUri(\r\n this.hostPrefix_, /** @type {string} */ (this.path_));\r\n\r\n if (request.isInitialResponseDecoded()) {\r\n this.channelDebug_.debug('Upgrade the handshake request to a backchannel.');\r\n this.forwardChannelRequestPool_.removeRequest(request);\r\n request.resetTimeout(this.backChannelRequestTimeoutMs_);\r\n this.backChannelRequest_ = request;\r\n } else {\r\n // Open connection to receive data\r\n this.ensureBackChannel_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Helper to ensure the channel is in the expected state.\r\n * @param {...number} var_args The channel must be in one of the indicated\r\n * states.\r\n * @private\r\n */\r\nWebChannelBase.prototype.ensureInState_ = function(var_args) {\r\n goog.asserts.assert(\r\n goog.array.contains(arguments, this.state_),\r\n 'Unexpected channel state: %s', this.state_);\r\n};\r\n\r\n\r\n/**\r\n * Signals an error has occurred.\r\n * @param {WebChannelBase.Error} error The error code for the failure.\r\n * @private\r\n */\r\nWebChannelBase.prototype.signalError_ = function(error) {\r\n this.channelDebug_.info('Error code ' + error);\r\n if (error == WebChannelBase.Error.REQUEST_FAILED) {\r\n // Create a separate Internet connection to check\r\n // if it's a server error or user's network error.\r\n var imageUri = null;\r\n if (this.handler_) {\r\n imageUri = this.handler_.getNetworkTestImageUri(this);\r\n }\r\n netUtils.testNetwork(goog.bind(this.testNetworkCallback_, this), imageUri);\r\n } else {\r\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\r\n }\r\n this.onError_(error);\r\n};\r\n\r\n\r\n/**\r\n * Callback for netUtils.testNetwork during error handling.\r\n * @param {boolean} networkUp Whether the network is up.\r\n * @private\r\n */\r\nWebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {\r\n if (networkUp) {\r\n this.channelDebug_.info('Successfully pinged google.com');\r\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\r\n } else {\r\n this.channelDebug_.info('Failed to ping google.com');\r\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);\r\n // Do not call onError_ again to eliminate duplicated Error events.\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when messages have been successfully sent from the queue.\r\n * @param {!ChannelRequest} request The request object\r\n * @private\r\n */\r\nWebChannelBase.prototype.onSuccess_ = function(request) {\r\n if (this.handler_) {\r\n this.handler_.channelSuccess(this, request);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Called when we've determined the final error for a channel. It closes the\r\n * notifiers the handler of the error and closes the channel.\r\n * @param {WebChannelBase.Error} error The error code for the failure.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onError_ = function(error) {\r\n this.channelDebug_.debug('HttpChannel: error - ' + error);\r\n this.state_ = WebChannelBase.State.CLOSED;\r\n if (this.handler_) {\r\n this.handler_.channelError(this, error);\r\n }\r\n this.onClose_();\r\n this.cancelRequests_();\r\n};\r\n\r\n\r\n/**\r\n * Called when the channel has been closed. It notifiers the handler of the\r\n * event, and reports any pending or undelivered maps.\r\n * @private\r\n */\r\nWebChannelBase.prototype.onClose_ = function() {\r\n this.state_ = WebChannelBase.State.CLOSED;\r\n this.lastStatusCode_ = -1;\r\n if (this.handler_) {\r\n var pendingMessages = this.forwardChannelRequestPool_.getPendingMessages();\r\n\r\n if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {\r\n this.handler_.channelClosed(this);\r\n } else {\r\n var self = this;\r\n this.channelDebug_.debug(function() {\r\n return 'Number of undelivered maps' +\r\n ', pending: ' + pendingMessages.length +\r\n ', outgoing: ' + self.outgoingMaps_.length;\r\n });\r\n\r\n this.forwardChannelRequestPool_.clearPendingMessages();\r\n\r\n var copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);\r\n this.outgoingMaps_.length = 0;\r\n\r\n this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getForwardChannelUri = function(path) {\r\n var uri = this.createDataUri(null, path);\r\n this.channelDebug_.debug('GetForwardChannelUri: ' + uri);\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getConnectionState = function() {\r\n return this.connState_;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {\r\n var uri = this.createDataUri(\r\n this.shouldUseSecondaryDomains() ? hostPrefix : null, path);\r\n this.channelDebug_.debug('GetBackChannelUri: ' + uri);\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.createDataUri = function(\r\n hostPrefix, path, opt_overridePort) {\r\n var uri = goog.Uri.parse(path);\r\n var uriAbsolute = (uri.getDomain() != '');\r\n if (uriAbsolute) {\r\n if (hostPrefix) {\r\n uri.setDomain(hostPrefix + '.' + uri.getDomain());\r\n }\r\n\r\n uri.setPort(opt_overridePort || uri.getPort());\r\n } else {\r\n var locationPage = goog.global.location;\r\n var hostName;\r\n if (hostPrefix) {\r\n hostName = hostPrefix + '.' + locationPage.hostname;\r\n } else {\r\n hostName = locationPage.hostname;\r\n }\r\n\r\n var port = opt_overridePort || +locationPage.port;\r\n\r\n uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);\r\n }\r\n\r\n if (this.extraParams_) {\r\n goog.object.forEach(this.extraParams_, function(value, key) {\r\n uri.setParameterValue(key, value);\r\n });\r\n }\r\n\r\n var param = this.getHttpSessionIdParam();\r\n var value = this.getHttpSessionId();\r\n if (param && value) {\r\n uri.setParameterValue(param, value);\r\n }\r\n\r\n // Add the protocol version to the URI.\r\n uri.setParameterValue('VER', this.channelVersion_);\r\n\r\n // Add the reconnect parameters.\r\n this.addAdditionalParams_(uri);\r\n\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.createXhrIo = function(hostPrefix) {\r\n if (hostPrefix && !this.supportsCrossDomainXhrs_) {\r\n throw new Error('Can\\'t create secondary domain capable XhrIo object.');\r\n }\r\n var xhr = new goog.net.XhrIo(this.xmlHttpFactory_);\r\n xhr.setWithCredentials(this.supportsCrossDomainXhrs_);\r\n return xhr;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.isActive = function() {\r\n return !!this.handler_ && this.handler_.isActive(this);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBase.prototype.shouldUseSecondaryDomains = function() {\r\n return this.supportsCrossDomainXhrs_;\r\n};\r\n\r\n\r\n/**\r\n * Sets (overwrites) the forward channel flush callback.\r\n *\r\n * @param {function()} callback The callback to be invoked.\r\n */\r\nWebChannelBase.prototype.setForwardChannelFlushCallback = function(callback) {\r\n this.forwardChannelFlushedCallback_ = callback;\r\n};\r\n\r\n\r\n/**\r\n * A LogSaver that can be used to accumulate all the debug logs so they\r\n * can be sent to the server when a problem is detected.\r\n * @const\r\n */\r\nWebChannelBase.LogSaver = {};\r\n\r\n\r\n/**\r\n * Buffer for accumulating the debug log\r\n * @type {goog.structs.CircularBuffer}\r\n * @private\r\n */\r\nWebChannelBase.LogSaver.buffer_ = new goog.structs.CircularBuffer(1000);\r\n\r\n\r\n/**\r\n * Whether we're currently accumulating the debug log.\r\n * @type {boolean}\r\n * @private\r\n */\r\nWebChannelBase.LogSaver.enabled_ = false;\r\n\r\n\r\n/**\r\n * Formatter for saving logs.\r\n * @type {goog.debug.Formatter}\r\n * @private\r\n */\r\nWebChannelBase.LogSaver.formatter_ = new goog.debug.TextFormatter();\r\n\r\n\r\n/**\r\n * Returns whether the LogSaver is enabled.\r\n * @return {boolean} Whether saving is enabled or disabled.\r\n */\r\nWebChannelBase.LogSaver.isEnabled = function() {\r\n return WebChannelBase.LogSaver.enabled_;\r\n};\r\n\r\n\r\n/**\r\n * Enables of disables the LogSaver.\r\n * @param {boolean} enable Whether to enable or disable saving.\r\n */\r\nWebChannelBase.LogSaver.setEnabled = function(enable) {\r\n if (enable == WebChannelBase.LogSaver.enabled_) {\r\n return;\r\n }\r\n\r\n var fn = WebChannelBase.LogSaver.addLogRecord;\r\n var logger = goog.log.getLogger('goog.net');\r\n if (enable) {\r\n goog.log.addHandler(logger, fn);\r\n } else {\r\n goog.log.removeHandler(logger, fn);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Adds a log record.\r\n * @param {goog.log.LogRecord} logRecord the LogRecord.\r\n */\r\nWebChannelBase.LogSaver.addLogRecord = function(logRecord) {\r\n WebChannelBase.LogSaver.buffer_.add(\r\n WebChannelBase.LogSaver.formatter_.formatRecord(logRecord));\r\n};\r\n\r\n\r\n/**\r\n * Returns the log as a single string.\r\n * @return {string} The log as a single string.\r\n */\r\nWebChannelBase.LogSaver.getBuffer = function() {\r\n return WebChannelBase.LogSaver.buffer_.getValues().join('');\r\n};\r\n\r\n\r\n/**\r\n * Clears the buffer\r\n */\r\nWebChannelBase.LogSaver.clearBuffer = function() {\r\n WebChannelBase.LogSaver.buffer_.clear();\r\n};\r\n\r\n\r\n\r\n/**\r\n * Abstract base class for the channel handler\r\n * @constructor\r\n * @struct\r\n */\r\nWebChannelBase.Handler = function() {};\r\n\r\n\r\n/**\r\n * Callback handler for when a batch of response arrays is received from the\r\n * server. When null, batched dispatching is disabled.\r\n * @type {?function(!WebChannelBase, !Array<!Array<?>>)}\r\n */\r\nWebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;\r\n\r\n\r\n/**\r\n * Whether it's okay to make a request to the server. A handler can return\r\n * false if the channel should fail. For example, if the user has logged out,\r\n * the handler may want all requests to fail immediately.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {WebChannelBase.Error} An error code. The code should\r\n * return WebChannelBase.Error.OK to indicate it's okay. Any other\r\n * error code will cause a failure.\r\n */\r\nWebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {\r\n return WebChannelBase.Error.OK;\r\n};\r\n\r\n\r\n/**\r\n * Indicates the WebChannel has successfully negotiated with the server\r\n * and can now send and receive data.\r\n * @param {WebChannelBase} channel The channel.\r\n */\r\nWebChannelBase.Handler.prototype.channelOpened = function(channel) {};\r\n\r\n\r\n/**\r\n * New input is available for the application to process.\r\n *\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {Array<?>} array The data array.\r\n */\r\nWebChannelBase.Handler.prototype.channelHandleArray = function(\r\n channel, array) {};\r\n\r\n\r\n/**\r\n * Indicates messages that have been successfully sent on the channel.\r\n *\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {!ChannelRequest} request The request object that contains\r\n * the pending messages that have been successfully delivered to the server.\r\n */\r\nWebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};\r\n\r\n\r\n/**\r\n * Indicates an error occurred on the WebChannel.\r\n *\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {WebChannelBase.Error} error The error code.\r\n */\r\nWebChannelBase.Handler.prototype.channelError = function(channel, error) {};\r\n\r\n\r\n/**\r\n * Indicates the WebChannel is closed. Also notifies about which maps,\r\n * if any, that may not have been delivered to the server.\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The\r\n * array of pending maps, which may or may not have been delivered to the\r\n * server.\r\n * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps\r\n * The array of undelivered maps, which have definitely not been delivered\r\n * to the server.\r\n */\r\nWebChannelBase.Handler.prototype.channelClosed = function(\r\n channel, opt_pendingMaps, opt_undeliveredMaps) {};\r\n\r\n\r\n/**\r\n * Gets any parameters that should be added at the time another connection is\r\n * made to the server.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {!Object} Extra parameter keys and values to add to the requests.\r\n */\r\nWebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {\r\n return {};\r\n};\r\n\r\n\r\n/**\r\n * Gets the URI of an image that can be used to test network connectivity.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {goog.Uri?} A custom URI to load for the network test.\r\n */\r\nWebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Gets whether this channel is currently active. This is used to determine the\r\n * length of time to wait before retrying.\r\n * @param {WebChannelBase} channel The channel.\r\n * @return {boolean} Whether the channel is currently active.\r\n */\r\nWebChannelBase.Handler.prototype.isActive = function(channel) {\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Called by the channel if enumeration of the map throws an exception.\r\n * @param {WebChannelBase} channel The channel.\r\n * @param {Object} map The map that can't be enumerated.\r\n */\r\nWebChannelBase.Handler.prototype.badMapError = function(channel, map) {};\r\n\r\n\r\n/**\r\n * Allows the handler to override a host prefix provided by the server. Will\r\n * be called whenever the channel has received such a prefix and is considering\r\n * its use.\r\n * @param {?string} serverHostPrefix The host prefix provided by the server.\r\n * @return {?string} The host prefix the client should use.\r\n */\r\nWebChannelBase.Handler.prototype.correctHostPrefix = function(\r\n serverHostPrefix) {\r\n return serverHostPrefix;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Generics method for collection-like classes and objects.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * This file contains functions to work with collections. It supports using\r\n * Map, Set, Array and Object and other classes that implement collection-like\r\n * methods.\r\n * @suppress {strictMissingProperties}\r\n */\r\n\r\n\r\ngoog.provide('goog.structs');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.object');\r\n\r\n\r\n// We treat an object as a dictionary if it has getKeys or it is an object that\r\n// isn't arrayLike.\r\n\r\n\r\n/**\r\n * Returns the number of values in the collection-like object.\r\n * @param {Object} col The collection-like object.\r\n * @return {number} The number of values in the collection-like object.\r\n */\r\ngoog.structs.getCount = function(col) {\r\n if (col.getCount && typeof col.getCount == 'function') {\r\n return col.getCount();\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return col.length;\r\n }\r\n return goog.object.getCount(col);\r\n};\r\n\r\n\r\n/**\r\n * Returns the values of the collection-like object.\r\n * @param {Object} col The collection-like object.\r\n * @return {!Array<?>} The values in the collection-like object.\r\n */\r\ngoog.structs.getValues = function(col) {\r\n if (col.getValues && typeof col.getValues == 'function') {\r\n return col.getValues();\r\n }\r\n if (goog.isString(col)) {\r\n return col.split('');\r\n }\r\n if (goog.isArrayLike(col)) {\r\n var rv = [];\r\n var l = col.length;\r\n for (var i = 0; i < l; i++) {\r\n rv.push(col[i]);\r\n }\r\n return rv;\r\n }\r\n return goog.object.getValues(col);\r\n};\r\n\r\n\r\n/**\r\n * Returns the keys of the collection. Some collections have no notion of\r\n * keys/indexes and this function will return undefined in those cases.\r\n * @param {Object} col The collection-like object.\r\n * @return {!Array|undefined} The keys in the collection.\r\n */\r\ngoog.structs.getKeys = function(col) {\r\n if (col.getKeys && typeof col.getKeys == 'function') {\r\n return col.getKeys();\r\n }\r\n // if we have getValues but no getKeys we know this is a key-less collection\r\n if (col.getValues && typeof col.getValues == 'function') {\r\n return undefined;\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n var rv = [];\r\n var l = col.length;\r\n for (var i = 0; i < l; i++) {\r\n rv.push(i);\r\n }\r\n return rv;\r\n }\r\n\r\n return goog.object.getKeys(col);\r\n};\r\n\r\n\r\n/**\r\n * Whether the collection contains the given value. This is O(n) and uses\r\n * equals (==) to test the existence.\r\n * @param {Object} col The collection-like object.\r\n * @param {*} val The value to check for.\r\n * @return {boolean} True if the map contains the value.\r\n */\r\ngoog.structs.contains = function(col, val) {\r\n if (col.contains && typeof col.contains == 'function') {\r\n return col.contains(val);\r\n }\r\n if (col.containsValue && typeof col.containsValue == 'function') {\r\n return col.containsValue(val);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\r\n }\r\n return goog.object.containsValue(col, val);\r\n};\r\n\r\n\r\n/**\r\n * Whether the collection is empty.\r\n * @param {Object} col The collection-like object.\r\n * @return {boolean} True if empty.\r\n */\r\ngoog.structs.isEmpty = function(col) {\r\n if (col.isEmpty && typeof col.isEmpty == 'function') {\r\n return col.isEmpty();\r\n }\r\n\r\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\r\n // string as\r\n // collection and as such even whitespace matters\r\n\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.isEmpty(/** @type {!Array<?>} */ (col));\r\n }\r\n return goog.object.isEmpty(col);\r\n};\r\n\r\n\r\n/**\r\n * Removes all the elements from the collection.\r\n * @param {Object} col The collection-like object.\r\n */\r\ngoog.structs.clear = function(col) {\r\n // NOTE(arv): This should not contain strings because strings are immutable\r\n if (col.clear && typeof col.clear == 'function') {\r\n col.clear();\r\n } else if (goog.isArrayLike(col)) {\r\n goog.array.clear(/** @type {IArrayLike<?>} */ (col));\r\n } else {\r\n goog.object.clear(col);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for each value in a collection. The function takes\r\n * three arguments; the value, the key and the collection.\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):?} f The function to call for every value.\r\n * This function takes\r\n * 3 arguments (the value, the key or undefined if the collection has no\r\n * notion of keys, and the collection) and the return value is irrelevant.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @template T,S\r\n * @deprecated Use a more specific method, e.g. goog.array.forEach,\r\n * goog.object.forEach, or for-of.\r\n */\r\ngoog.structs.forEach = function(col, f, opt_obj) {\r\n if (col.forEach && typeof col.forEach == 'function') {\r\n col.forEach(f, opt_obj);\r\n } else if (goog.isArrayLike(col) || goog.isString(col)) {\r\n goog.array.forEach(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n } else {\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for every value in the collection. When a call returns true,\r\n * adds the value to a new collection (Array is returned by default).\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\r\n * value. This function takes\r\n * 3 arguments (the value, the key or undefined if the collection has no\r\n * notion of keys, and the collection) and should return a Boolean. If the\r\n * return value is true the value is added to the result collection. If it\r\n * is false the value is not included.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {!Object|!Array<?>} A new collection where the passed values are\r\n * present. If col is a key-less collection an array is returned. If col\r\n * has keys and values a plain old JS object is returned.\r\n * @template T,S\r\n */\r\ngoog.structs.filter = function(col, f, opt_obj) {\r\n if (typeof col.filter == 'function') {\r\n return col.filter(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.filter(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n\r\n var rv;\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n if (keys) {\r\n rv = {};\r\n for (var i = 0; i < l; i++) {\r\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {\r\n rv[keys[i]] = values[i];\r\n }\r\n }\r\n } else {\r\n // We should not use goog.array.filter here since we want to make sure that\r\n // the index is undefined as well as make sure that col is passed to the\r\n // function.\r\n rv = [];\r\n for (var i = 0; i < l; i++) {\r\n if (f.call(opt_obj, values[i], undefined, col)) {\r\n rv.push(values[i]);\r\n }\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Calls a function for every value in the collection and adds the result into a\r\n * new collection (defaults to creating a new Array).\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):V} f The function to call for every value.\r\n * This function takes 3 arguments (the value, the key or undefined if the\r\n * collection has no notion of keys, and the collection) and should return\r\n * something. The result will be used as the value in the new collection.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {!Object<V>|!Array<V>} A new collection with the new values. If\r\n * col is a key-less collection an array is returned. If col has keys and\r\n * values a plain old JS object is returned.\r\n * @template T,S,V\r\n */\r\ngoog.structs.map = function(col, f, opt_obj) {\r\n if (typeof col.map == 'function') {\r\n return col.map(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.map(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n\r\n var rv;\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n if (keys) {\r\n rv = {};\r\n for (var i = 0; i < l; i++) {\r\n rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);\r\n }\r\n } else {\r\n // We should not use goog.array.map here since we want to make sure that\r\n // the index is undefined as well as make sure that col is passed to the\r\n // function.\r\n rv = [];\r\n for (var i = 0; i < l; i++) {\r\n rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Calls f for each value in a collection. If any call returns true this returns\r\n * true (without checking the rest). If all returns false this returns false.\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\r\n * value. This function takes 3 arguments (the value, the key or undefined\r\n * if the collection has no notion of keys, and the collection) and should\r\n * return a boolean.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {boolean} True if any value passes the test.\r\n * @template T,S\r\n */\r\ngoog.structs.some = function(col, f, opt_obj) {\r\n if (typeof col.some == 'function') {\r\n return col.some(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.some(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Calls f for each value in a collection. If all calls return true this return\r\n * true this returns true. If any returns false this returns false at this point\r\n * and does not continue to check the remaining values.\r\n *\r\n * @param {S} col The collection-like object.\r\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\r\n * value. This function takes 3 arguments (the value, the key or\r\n * undefined if the collection has no notion of keys, and the collection)\r\n * and should return a boolean.\r\n * @param {T=} opt_obj The object to be used as the value of 'this'\r\n * within `f`.\r\n * @return {boolean} True if all key-value pairs pass the test.\r\n * @template T,S\r\n */\r\ngoog.structs.every = function(col, f, opt_obj) {\r\n if (typeof col.every == 'function') {\r\n return col.every(f, opt_obj);\r\n }\r\n if (goog.isArrayLike(col) || goog.isString(col)) {\r\n return goog.array.every(/** @type {!Array<?>} */ (col), f, opt_obj);\r\n }\r\n var keys = goog.structs.getKeys(col);\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Datastructure: Hash Map.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * This file contains an implementation of a Map structure. It implements a lot\r\n * of the methods used in goog.structs so those functions work on hashes. This\r\n * is best suited for complex key types. For simple keys such as numbers and\r\n * strings consider using the lighter-weight utilities in goog.object.\r\n */\r\n\r\n\r\ngoog.provide('goog.structs.Map');\r\n\r\ngoog.require('goog.iter.Iterator');\r\ngoog.require('goog.iter.StopIteration');\r\n\r\n\r\n\r\n/**\r\n * Class for Hash Map datastructure.\r\n * @param {*=} opt_map Map or Object to initialize the map with.\r\n * @param {...*} var_args If 2 or more arguments are present then they\r\n * will be used as key-value pairs.\r\n * @constructor\r\n * @template K, V\r\n * @deprecated This type is misleading: use ES6 Map instead.\r\n */\r\ngoog.structs.Map = function(opt_map, var_args) {\r\n\r\n /**\r\n * Underlying JS object used to implement the map.\r\n * @private {!Object}\r\n */\r\n this.map_ = {};\r\n\r\n /**\r\n * An array of keys. This is necessary for two reasons:\r\n * 1. Iterating the keys using for (var key in this.map_) allocates an\r\n * object for every key in IE which is really bad for IE6 GC perf.\r\n * 2. Without a side data structure, we would need to escape all the keys\r\n * as that would be the only way we could tell during iteration if the\r\n * key was an internal key or a property of the object.\r\n *\r\n * This array can contain deleted keys so it's necessary to check the map\r\n * as well to see if the key is still in the map (this doesn't require a\r\n * memory allocation in IE).\r\n * @private {!Array<string>}\r\n */\r\n this.keys_ = [];\r\n\r\n /**\r\n * The number of key value pairs in the map.\r\n * @private {number}\r\n */\r\n this.count_ = 0;\r\n\r\n /**\r\n * Version used to detect changes while iterating.\r\n * @private {number}\r\n */\r\n this.version_ = 0;\r\n\r\n var argLength = arguments.length;\r\n\r\n if (argLength > 1) {\r\n if (argLength % 2) {\r\n throw new Error('Uneven number of arguments');\r\n }\r\n for (var i = 0; i < argLength; i += 2) {\r\n this.set(arguments[i], arguments[i + 1]);\r\n }\r\n } else if (opt_map) {\r\n this.addAll(/** @type {!Object} */ (opt_map));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of key-value pairs in the map.\r\n */\r\ngoog.structs.Map.prototype.getCount = function() {\r\n return this.count_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the values of the map.\r\n * @return {!Array<V>} The values in the map.\r\n */\r\ngoog.structs.Map.prototype.getValues = function() {\r\n this.cleanupKeysArray_();\r\n\r\n var rv = [];\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n rv.push(this.map_[key]);\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Returns the keys of the map.\r\n * @return {!Array<string>} Array of string values.\r\n */\r\ngoog.structs.Map.prototype.getKeys = function() {\r\n this.cleanupKeysArray_();\r\n return /** @type {!Array<string>} */ (this.keys_.concat());\r\n};\r\n\r\n\r\n/**\r\n * Whether the map contains the given key.\r\n * @param {*} key The key to check for.\r\n * @return {boolean} Whether the map contains the key.\r\n */\r\ngoog.structs.Map.prototype.containsKey = function(key) {\r\n return goog.structs.Map.hasKey_(this.map_, key);\r\n};\r\n\r\n\r\n/**\r\n * Whether the map contains the given value. This is O(n).\r\n * @param {V} val The value to check for.\r\n * @return {boolean} Whether the map contains the value.\r\n */\r\ngoog.structs.Map.prototype.containsValue = function(val) {\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Whether this map is equal to the argument map.\r\n * @param {goog.structs.Map} otherMap The map against which to test equality.\r\n * @param {function(V, V): boolean=} opt_equalityFn Optional equality function\r\n * to test equality of values. If not specified, this will test whether\r\n * the values contained in each map are identical objects.\r\n * @return {boolean} Whether the maps are equal.\r\n */\r\ngoog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) {\r\n if (this === otherMap) {\r\n return true;\r\n }\r\n\r\n if (this.count_ != otherMap.getCount()) {\r\n return false;\r\n }\r\n\r\n var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals;\r\n\r\n this.cleanupKeysArray_();\r\n for (var key, i = 0; key = this.keys_[i]; i++) {\r\n if (!equalityFn(this.get(key), otherMap.get(key))) {\r\n return false;\r\n }\r\n }\r\n\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Default equality test for values.\r\n * @param {*} a The first value.\r\n * @param {*} b The second value.\r\n * @return {boolean} Whether a and b reference the same object.\r\n */\r\ngoog.structs.Map.defaultEquals = function(a, b) {\r\n return a === b;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the map is empty.\r\n */\r\ngoog.structs.Map.prototype.isEmpty = function() {\r\n return this.count_ == 0;\r\n};\r\n\r\n\r\n/**\r\n * Removes all key-value pairs from the map.\r\n */\r\ngoog.structs.Map.prototype.clear = function() {\r\n this.map_ = {};\r\n this.keys_.length = 0;\r\n this.count_ = 0;\r\n this.version_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * Removes a key-value pair based on the key. This is O(logN) amortized due to\r\n * updating the keys array whenever the count becomes half the size of the keys\r\n * in the keys array.\r\n * @param {*} key The key to remove.\r\n * @return {boolean} Whether object was removed.\r\n */\r\ngoog.structs.Map.prototype.remove = function(key) {\r\n if (goog.structs.Map.hasKey_(this.map_, key)) {\r\n delete this.map_[key];\r\n this.count_--;\r\n this.version_++;\r\n\r\n // clean up the keys array if the threshold is hit\r\n if (this.keys_.length > 2 * this.count_) {\r\n this.cleanupKeysArray_();\r\n }\r\n\r\n return true;\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Cleans up the temp keys array by removing entries that are no longer in the\r\n * map.\r\n * @private\r\n */\r\ngoog.structs.Map.prototype.cleanupKeysArray_ = function() {\r\n if (this.count_ != this.keys_.length) {\r\n // First remove keys that are no longer in the map.\r\n var srcIndex = 0;\r\n var destIndex = 0;\r\n while (srcIndex < this.keys_.length) {\r\n var key = this.keys_[srcIndex];\r\n if (goog.structs.Map.hasKey_(this.map_, key)) {\r\n this.keys_[destIndex++] = key;\r\n }\r\n srcIndex++;\r\n }\r\n this.keys_.length = destIndex;\r\n }\r\n\r\n if (this.count_ != this.keys_.length) {\r\n // If the count still isn't correct, that means we have duplicates. This can\r\n // happen when the same key is added and removed multiple times. Now we have\r\n // to allocate one extra Object to remove the duplicates. This could have\r\n // been done in the first pass, but in the common case, we can avoid\r\n // allocating an extra object by only doing this when necessary.\r\n var seen = {};\r\n var srcIndex = 0;\r\n var destIndex = 0;\r\n while (srcIndex < this.keys_.length) {\r\n var key = this.keys_[srcIndex];\r\n if (!(goog.structs.Map.hasKey_(seen, key))) {\r\n this.keys_[destIndex++] = key;\r\n seen[key] = 1;\r\n }\r\n srcIndex++;\r\n }\r\n this.keys_.length = destIndex;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Returns the value for the given key. If the key is not found and the default\r\n * value is not given this will return `undefined`.\r\n * @param {*} key The key to get the value for.\r\n * @param {DEFAULT=} opt_val The value to return if no item is found for the\r\n * given key, defaults to undefined.\r\n * @return {V|DEFAULT} The value for the given key.\r\n * @template DEFAULT\r\n */\r\ngoog.structs.Map.prototype.get = function(key, opt_val) {\r\n if (goog.structs.Map.hasKey_(this.map_, key)) {\r\n return this.map_[key];\r\n }\r\n return opt_val;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key-value pair to the map.\r\n * @param {*} key The key.\r\n * @param {V} value The value to add.\r\n * @return {*} Some subclasses return a value.\r\n */\r\ngoog.structs.Map.prototype.set = function(key, value) {\r\n if (!(goog.structs.Map.hasKey_(this.map_, key))) {\r\n this.count_++;\r\n // TODO(johnlenz): This class lies, it claims to return an array of string\r\n // keys, but instead returns the original object used.\r\n this.keys_.push(/** @type {?} */ (key));\r\n // Only change the version if we add a new key.\r\n this.version_++;\r\n }\r\n this.map_[key] = value;\r\n};\r\n\r\n\r\n/**\r\n * Adds multiple key-value pairs from another goog.structs.Map or Object.\r\n * @param {?Object} map Object containing the data to add.\r\n */\r\ngoog.structs.Map.prototype.addAll = function(map) {\r\n if (map instanceof goog.structs.Map) {\r\n var keys = map.getKeys();\r\n for (var i = 0; i < keys.length; i++) {\r\n this.set(keys[i], map.get(keys[i]));\r\n }\r\n } else {\r\n for (var key in map) {\r\n this.set(key, map[key]);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Calls the given function on each entry in the map.\r\n * @param {function(this:T, V, K, goog.structs.Map<K,V>)} f\r\n * @param {T=} opt_obj The value of \"this\" inside f.\r\n * @template T\r\n */\r\ngoog.structs.Map.prototype.forEach = function(f, opt_obj) {\r\n var keys = this.getKeys();\r\n for (var i = 0; i < keys.length; i++) {\r\n var key = keys[i];\r\n var value = this.get(key);\r\n f.call(opt_obj, value, key, this);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clones a map and returns a new map.\r\n * @return {!goog.structs.Map} A new map with the same key-value pairs.\r\n */\r\ngoog.structs.Map.prototype.clone = function() {\r\n return new goog.structs.Map(this);\r\n};\r\n\r\n\r\n/**\r\n * Returns a new map in which all the keys and values are interchanged\r\n * (keys become values and values become keys). If multiple keys map to the\r\n * same value, the chosen transposed value is implementation-dependent.\r\n *\r\n * It acts very similarly to {goog.object.transpose(Object)}.\r\n *\r\n * @return {!goog.structs.Map} The transposed map.\r\n */\r\ngoog.structs.Map.prototype.transpose = function() {\r\n var transposed = new goog.structs.Map();\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n var value = this.map_[key];\r\n transposed.set(value, key);\r\n }\r\n\r\n return transposed;\r\n};\r\n\r\n\r\n/**\r\n * @return {!Object} Object representation of the map.\r\n */\r\ngoog.structs.Map.prototype.toObject = function() {\r\n this.cleanupKeysArray_();\r\n var obj = {};\r\n for (var i = 0; i < this.keys_.length; i++) {\r\n var key = this.keys_[i];\r\n obj[key] = this.map_[key];\r\n }\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the keys in the map. Removal of keys\r\n * while iterating might have undesired side effects.\r\n * @return {!goog.iter.Iterator} An iterator over the keys in the map.\r\n */\r\ngoog.structs.Map.prototype.getKeyIterator = function() {\r\n return this.__iterator__(true);\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the values in the map. Removal of\r\n * keys while iterating might have undesired side effects.\r\n * @return {!goog.iter.Iterator} An iterator over the values in the map.\r\n */\r\ngoog.structs.Map.prototype.getValueIterator = function() {\r\n return this.__iterator__(false);\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the values or the keys in the map.\r\n * This throws an exception if the map was mutated since the iterator was\r\n * created.\r\n * @param {boolean=} opt_keys True to iterate over the keys. False to iterate\r\n * over the values. The default value is false.\r\n * @return {!goog.iter.Iterator} An iterator over the values or keys in the map.\r\n */\r\ngoog.structs.Map.prototype.__iterator__ = function(opt_keys) {\r\n // Clean up keys to minimize the risk of iterating over dead keys.\r\n this.cleanupKeysArray_();\r\n\r\n var i = 0;\r\n var version = this.version_;\r\n var selfObj = this;\r\n\r\n var newIter = new goog.iter.Iterator;\r\n newIter.next = function() {\r\n if (version != selfObj.version_) {\r\n throw new Error('The map has changed since the iterator was created');\r\n }\r\n if (i >= selfObj.keys_.length) {\r\n throw goog.iter.StopIteration;\r\n }\r\n var key = selfObj.keys_[i++];\r\n return opt_keys ? key : selfObj.map_[key];\r\n };\r\n return newIter;\r\n};\r\n\r\n\r\n/**\r\n * Safe way to test for hasOwnProperty. It even allows testing for\r\n * 'hasOwnProperty'.\r\n * @param {!Object} obj The object to test for presence of the given key.\r\n * @param {*} key The key to check for.\r\n * @return {boolean} Whether the object has the key.\r\n * @private\r\n */\r\ngoog.structs.Map.hasKey_ = function(obj, key) {\r\n return Object.prototype.hasOwnProperty.call(obj, key);\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for string manipulation.\r\n * @author arv@google.com (Erik Arvidsson)\r\n */\r\n\r\n\r\n/**\r\n * Namespace for string utilities\r\n */\r\ngoog.provide('goog.string');\r\ngoog.provide('goog.string.Unicode');\r\n\r\ngoog.require('goog.string.internal');\r\n\r\n\r\n/**\r\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\r\n * with detection of double-escaping as this letter is frequently used.\r\n */\r\ngoog.string.DETECT_DOUBLE_ESCAPING =\r\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\r\n\r\n\r\n/**\r\n * @define {boolean} Whether to force non-dom html unescaping.\r\n */\r\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\r\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\r\n\r\n\r\n/**\r\n * Common Unicode string characters.\r\n * @enum {string}\r\n */\r\ngoog.string.Unicode = {\r\n NBSP: '\\xa0'\r\n};\r\n\r\n\r\n/**\r\n * Fast prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the start of `str`.\r\n * @return {boolean} True if `str` begins with `prefix`.\r\n */\r\ngoog.string.startsWith = goog.string.internal.startsWith;\r\n\r\n\r\n/**\r\n * Fast suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix`.\r\n */\r\ngoog.string.endsWith = goog.string.internal.endsWith;\r\n\r\n\r\n/**\r\n * Case-insensitive prefix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} prefix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` begins with `prefix` (ignoring\r\n * case).\r\n */\r\ngoog.string.caseInsensitiveStartsWith =\r\n goog.string.internal.caseInsensitiveStartsWith;\r\n\r\n\r\n/**\r\n * Case-insensitive suffix-checker.\r\n * @param {string} str The string to check.\r\n * @param {string} suffix A string to look for at the end of `str`.\r\n * @return {boolean} True if `str` ends with `suffix` (ignoring\r\n * case).\r\n */\r\ngoog.string.caseInsensitiveEndsWith =\r\n goog.string.internal.caseInsensitiveEndsWith;\r\n\r\n\r\n/**\r\n * Case-insensitive equality checker.\r\n * @param {string} str1 First string to check.\r\n * @param {string} str2 Second string to check.\r\n * @return {boolean} True if `str1` and `str2` are the same string,\r\n * ignoring case.\r\n */\r\ngoog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;\r\n\r\n\r\n/**\r\n * Does simple python-style string substitution.\r\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\r\n * @param {string} str The string containing the pattern.\r\n * @param {...*} var_args The items to substitute into the pattern.\r\n * @return {string} A copy of `str` in which each occurrence of\r\n * {@code %s} has been replaced an argument from `var_args`.\r\n */\r\ngoog.string.subs = function(str, var_args) {\r\n var splitParts = str.split('%s');\r\n var returnString = '';\r\n\r\n var subsArguments = Array.prototype.slice.call(arguments, 1);\r\n while (subsArguments.length &&\r\n // Replace up to the last split part. We are inserting in the\r\n // positions between split parts.\r\n splitParts.length > 1) {\r\n returnString += splitParts.shift() + subsArguments.shift();\r\n }\r\n\r\n return returnString + splitParts.join('%s'); // Join unused '%s'\r\n};\r\n\r\n\r\n/**\r\n * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines\r\n * and tabs) to a single space, and strips leading and trailing whitespace.\r\n * @param {string} str Input string.\r\n * @return {string} A copy of `str` with collapsed whitespace.\r\n */\r\ngoog.string.collapseWhitespace = function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return str.replace(/[\\s\\xa0]+/g, ' ').replace(/^\\s+|\\s+$/g, '');\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is empty or contains only whitespaces.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty or whitespace only.\r\n */\r\ngoog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;\r\n\r\n\r\n/**\r\n * Checks if a string is empty.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty.\r\n */\r\ngoog.string.isEmptyString = function(str) {\r\n return str.length == 0;\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is empty or contains only whitespaces.\r\n *\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether `str` is empty or whitespace only.\r\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\r\n */\r\ngoog.string.isEmpty = goog.string.isEmptyOrWhitespace;\r\n\r\n\r\n/**\r\n * Checks if a string is null, undefined, empty or contains only whitespaces.\r\n * @param {*} str The string to check.\r\n * @return {boolean} Whether `str` is null, undefined, empty, or\r\n * whitespace only.\r\n * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))\r\n * instead.\r\n */\r\ngoog.string.isEmptyOrWhitespaceSafe = function(str) {\r\n return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string is null, undefined, empty or contains only whitespaces.\r\n *\r\n * @param {*} str The string to check.\r\n * @return {boolean} Whether `str` is null, undefined, empty, or\r\n * whitespace only.\r\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\r\n */\r\ngoog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;\r\n\r\n\r\n/**\r\n * Checks if a string is all breaking whitespace.\r\n * @param {string} str The string to check.\r\n * @return {boolean} Whether the string is all breaking whitespace.\r\n */\r\ngoog.string.isBreakingWhitespace = function(str) {\r\n return !/[^\\t\\n\\r ]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string contains all letters.\r\n * @param {string} str string to check.\r\n * @return {boolean} True if `str` consists entirely of letters.\r\n */\r\ngoog.string.isAlpha = function(str) {\r\n return !/[^a-zA-Z]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string contains only numbers.\r\n * @param {*} str string to check. If not a string, it will be\r\n * casted to one.\r\n * @return {boolean} True if `str` is numeric.\r\n */\r\ngoog.string.isNumeric = function(str) {\r\n return !/[^0-9]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a string contains only numbers or letters.\r\n * @param {string} str string to check.\r\n * @return {boolean} True if `str` is alphanumeric.\r\n */\r\ngoog.string.isAlphaNumeric = function(str) {\r\n return !/[^a-zA-Z0-9]/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Checks if a character is a space character.\r\n * @param {string} ch Character to check.\r\n * @return {boolean} True if `ch` is a space.\r\n */\r\ngoog.string.isSpace = function(ch) {\r\n return ch == ' ';\r\n};\r\n\r\n\r\n/**\r\n * Checks if a character is a valid unicode character.\r\n * @param {string} ch Character to check.\r\n * @return {boolean} True if `ch` is a valid unicode character.\r\n */\r\ngoog.string.isUnicodeChar = function(ch) {\r\n return ch.length == 1 && ch >= ' ' && ch <= '~' ||\r\n ch >= '\\u0080' && ch <= '\\uFFFD';\r\n};\r\n\r\n\r\n/**\r\n * Takes a string and replaces newlines with a space. Multiple lines are\r\n * replaced with a single space.\r\n * @param {string} str The string from which to strip newlines.\r\n * @return {string} A copy of `str` stripped of newlines.\r\n */\r\ngoog.string.stripNewlines = function(str) {\r\n return str.replace(/(\\r\\n|\\r|\\n)+/g, ' ');\r\n};\r\n\r\n\r\n/**\r\n * Replaces Windows and Mac new lines with unix style: \\r or \\r\\n with \\n.\r\n * @param {string} str The string to in which to canonicalize newlines.\r\n * @return {string} `str` A copy of {@code} with canonicalized newlines.\r\n */\r\ngoog.string.canonicalizeNewlines = function(str) {\r\n return str.replace(/(\\r\\n|\\r|\\n)/g, '\\n');\r\n};\r\n\r\n\r\n/**\r\n * Normalizes whitespace in a string, replacing all whitespace chars with\r\n * a space.\r\n * @param {string} str The string in which to normalize whitespace.\r\n * @return {string} A copy of `str` with all whitespace normalized.\r\n */\r\ngoog.string.normalizeWhitespace = function(str) {\r\n return str.replace(/\\xa0|\\s/g, ' ');\r\n};\r\n\r\n\r\n/**\r\n * Normalizes spaces in a string, replacing all consecutive spaces and tabs\r\n * with a single space. Replaces non-breaking space with a space.\r\n * @param {string} str The string in which to normalize spaces.\r\n * @return {string} A copy of `str` with all consecutive spaces and tabs\r\n * replaced with a single space.\r\n */\r\ngoog.string.normalizeSpaces = function(str) {\r\n return str.replace(/\\xa0|[ \\t]+/g, ' ');\r\n};\r\n\r\n\r\n/**\r\n * Removes the breaking spaces from the left and right of the string and\r\n * collapses the sequences of breaking spaces in the middle into single spaces.\r\n * The original and the result strings render the same way in HTML.\r\n * @param {string} str A string in which to collapse spaces.\r\n * @return {string} Copy of the string with normalized breaking spaces.\r\n */\r\ngoog.string.collapseBreakingSpaces = function(str) {\r\n return str.replace(/[\\t\\r\\n ]+/g, ' ')\r\n .replace(/^[\\t\\r\\n ]+|[\\t\\r\\n ]+$/g, '');\r\n};\r\n\r\n\r\n/**\r\n * Trims white spaces to the left and right of a string.\r\n * @param {string} str The string to trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.trim = goog.string.internal.trim;\r\n\r\n\r\n/**\r\n * Trims whitespaces at the left end of a string.\r\n * @param {string} str The string to left trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.trimLeft = function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return str.replace(/^[\\s\\xa0]+/, '');\r\n};\r\n\r\n\r\n/**\r\n * Trims whitespaces at the right end of a string.\r\n * @param {string} str The string to right trim.\r\n * @return {string} A trimmed copy of `str`.\r\n */\r\ngoog.string.trimRight = function(str) {\r\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\r\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\r\n // include it in the regexp to enforce consistent cross-browser behavior.\r\n return str.replace(/[\\s\\xa0]+$/, '');\r\n};\r\n\r\n\r\n/**\r\n * A string comparator that ignores case.\r\n * -1 = str1 less than str2\r\n * 0 = str1 equals str2\r\n * 1 = str1 greater than str2\r\n *\r\n * @param {string} str1 The string to compare.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} The comparator result, as described above.\r\n */\r\ngoog.string.caseInsensitiveCompare =\r\n goog.string.internal.caseInsensitiveCompare;\r\n\r\n\r\n/**\r\n * Compares two strings interpreting their numeric substrings as numbers.\r\n *\r\n * @param {string} str1 First string.\r\n * @param {string} str2 Second string.\r\n * @param {!RegExp} tokenizerRegExp Splits a string into substrings of\r\n * non-negative integers, non-numeric characters and optionally fractional\r\n * numbers starting with a decimal point.\r\n * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if\r\n * str1 > str2.\r\n * @private\r\n */\r\ngoog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) {\r\n if (str1 == str2) {\r\n return 0;\r\n }\r\n if (!str1) {\r\n return -1;\r\n }\r\n if (!str2) {\r\n return 1;\r\n }\r\n\r\n // Using match to split the entire string ahead of time turns out to be faster\r\n // for most inputs than using RegExp.exec or iterating over each character.\r\n var tokens1 = str1.toLowerCase().match(tokenizerRegExp);\r\n var tokens2 = str2.toLowerCase().match(tokenizerRegExp);\r\n\r\n var count = Math.min(tokens1.length, tokens2.length);\r\n\r\n for (var i = 0; i < count; i++) {\r\n var a = tokens1[i];\r\n var b = tokens2[i];\r\n\r\n // Compare pairs of tokens, returning if one token sorts before the other.\r\n if (a != b) {\r\n // Only if both tokens are integers is a special comparison required.\r\n // Decimal numbers are sorted as strings (e.g., '.09' < '.1').\r\n var num1 = parseInt(a, 10);\r\n if (!isNaN(num1)) {\r\n var num2 = parseInt(b, 10);\r\n if (!isNaN(num2) && num1 - num2) {\r\n return num1 - num2;\r\n }\r\n }\r\n return a < b ? -1 : 1;\r\n }\r\n }\r\n\r\n // If one string is a substring of the other, the shorter string sorts first.\r\n if (tokens1.length != tokens2.length) {\r\n return tokens1.length - tokens2.length;\r\n }\r\n\r\n // The two strings must be equivalent except for case (perfect equality is\r\n // tested at the head of the function.) Revert to default ASCII string\r\n // comparison to stabilize the sort.\r\n return str1 < str2 ? -1 : 1;\r\n};\r\n\r\n\r\n/**\r\n * String comparison function that handles non-negative integer numbers in a\r\n * way humans might expect. Using this function, the string 'File 2.jpg' sorts\r\n * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison\r\n * is mostly case-insensitive, though strings that are identical except for case\r\n * are sorted with the upper-case strings before lower-case.\r\n *\r\n * This comparison function is up to 50x slower than either the default or the\r\n * case-insensitive compare. It should not be used in time-critical code, but\r\n * should be fast enough to sort several hundred short strings (like filenames)\r\n * with a reasonable delay.\r\n *\r\n * @param {string} str1 The string to compare in a numerically sensitive way.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\r\n * 0 if str1 > str2.\r\n */\r\ngoog.string.intAwareCompare = function(str1, str2) {\r\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\D+/g);\r\n};\r\n\r\n\r\n/**\r\n * String comparison function that handles non-negative integer and fractional\r\n * numbers in a way humans might expect. Using this function, the string\r\n * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent\r\n * to {@link goog.string.intAwareCompare} apart from the way how it interprets\r\n * dots.\r\n *\r\n * @param {string} str1 The string to compare in a numerically sensitive way.\r\n * @param {string} str2 The string to compare `str1` to.\r\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\r\n * 0 if str1 > str2.\r\n */\r\ngoog.string.floatAwareCompare = function(str1, str2) {\r\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\.\\d+|\\D+/g);\r\n};\r\n\r\n\r\n/**\r\n * Alias for {@link goog.string.floatAwareCompare}.\r\n *\r\n * @param {string} str1\r\n * @param {string} str2\r\n * @return {number}\r\n */\r\ngoog.string.numerateCompare = goog.string.floatAwareCompare;\r\n\r\n\r\n/**\r\n * URL-encodes a string\r\n * @param {*} str The string to url-encode.\r\n * @return {string} An encoded copy of `str` that is safe for urls.\r\n * Note that '#', ':', and other characters used to delimit portions\r\n * of URLs *will* be encoded.\r\n */\r\ngoog.string.urlEncode = function(str) {\r\n return encodeURIComponent(String(str));\r\n};\r\n\r\n\r\n/**\r\n * URL-decodes the string. We need to specially handle '+'s because\r\n * the javascript library doesn't convert them to spaces.\r\n * @param {string} str The string to url decode.\r\n * @return {string} The decoded `str`.\r\n */\r\ngoog.string.urlDecode = function(str) {\r\n return decodeURIComponent(str.replace(/\\+/g, ' '));\r\n};\r\n\r\n\r\n/**\r\n * Converts \\n to <br>s or <br />s.\r\n * @param {string} str The string in which to convert newlines.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} A copy of `str` with converted newlines.\r\n */\r\ngoog.string.newLineToBr = goog.string.internal.newLineToBr;\r\n\r\n\r\n/**\r\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\r\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\r\n * value within double or single quotes.\r\n *\r\n * It should be noted that > doesn't need to be escaped for the HTML or XML to\r\n * be valid, but it has been decided to escape it for consistency with other\r\n * implementations.\r\n *\r\n * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the\r\n * lowercase letter \"e\".\r\n *\r\n * NOTE(user):\r\n * HtmlEscape is often called during the generation of large blocks of HTML.\r\n * Using statics for the regular expressions and strings is an optimization\r\n * that can more than half the amount of time IE spends in this function for\r\n * large apps, since strings and regexes both contribute to GC allocations.\r\n *\r\n * Testing for the presence of a character before escaping increases the number\r\n * of function calls, but actually provides a speed increase for the average\r\n * case -- since the average case often doesn't require the escaping of all 4\r\n * characters and indexOf() is much cheaper than replace().\r\n * The worst case does suffer slightly from the additional calls, therefore the\r\n * opt_isLikelyToContainHtmlChars option has been included for situations\r\n * where all 4 HTML entities are very likely to be present and need escaping.\r\n *\r\n * Some benchmarks (times tended to fluctuate +-0.05ms):\r\n * FireFox IE6\r\n * (no chars / average (mix of cases) / all 4 chars)\r\n * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80\r\n * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84\r\n * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85\r\n *\r\n * An additional advantage of checking if replace actually needs to be called\r\n * is a reduction in the number of object allocations, so as the size of the\r\n * application grows the difference between the various methods would increase.\r\n *\r\n * @param {string} str string to be escaped.\r\n * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see\r\n * if the character needs replacing - use this option if you expect each of\r\n * the characters to appear often. Leave false if you expect few html\r\n * characters to occur in your strings, such as if you are escaping HTML.\r\n * @return {string} An escaped copy of `str`.\r\n */\r\ngoog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {\r\n str = goog.string.internal.htmlEscape(str, opt_isLikelyToContainHtmlChars);\r\n if (goog.string.DETECT_DOUBLE_ESCAPING) {\r\n str = str.replace(goog.string.E_RE_, '&#101;');\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Regular expression that matches a lowercase letter \"e\", for use in escaping.\r\n * @const {!RegExp}\r\n * @private\r\n */\r\ngoog.string.E_RE_ = /e/g;\r\n\r\n\r\n/**\r\n * Unescapes an HTML string.\r\n *\r\n * @param {string} str The string to unescape.\r\n * @return {string} An unescaped copy of `str`.\r\n */\r\ngoog.string.unescapeEntities = function(str) {\r\n if (goog.string.contains(str, '&')) {\r\n // We are careful not to use a DOM if we do not have one or we explicitly\r\n // requested non-DOM html unescaping.\r\n if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&\r\n 'document' in goog.global) {\r\n return goog.string.unescapeEntitiesUsingDom_(str);\r\n } else {\r\n // Fall back on pure XML entities\r\n return goog.string.unescapePureXmlEntities_(str);\r\n }\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Unescapes a HTML string using the provided document.\r\n *\r\n * @param {string} str The string to unescape.\r\n * @param {!Document} document A document to use in escaping the string.\r\n * @return {string} An unescaped copy of `str`.\r\n */\r\ngoog.string.unescapeEntitiesWithDocument = function(str, document) {\r\n if (goog.string.contains(str, '&')) {\r\n return goog.string.unescapeEntitiesUsingDom_(str, document);\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric\r\n * entities. This function is XSS-safe and whitespace-preserving.\r\n * @private\r\n * @param {string} str The string to unescape.\r\n * @param {Document=} opt_document An optional document to use for creating\r\n * elements. If this is not specified then the default window.document\r\n * will be used.\r\n * @return {string} The unescaped `str` string.\r\n */\r\ngoog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {\r\n /** @type {!Object<string, string>} */\r\n var seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"'};\r\n /** @type {!Element} */\r\n var div;\r\n if (opt_document) {\r\n div = opt_document.createElement('div');\r\n } else {\r\n div = goog.global.document.createElement('div');\r\n }\r\n // Match as many valid entity characters as possible. If the actual entity\r\n // happens to be shorter, it will still work as innerHTML will return the\r\n // trailing characters unchanged. Since the entity characters do not include\r\n // open angle bracket, there is no chance of XSS from the innerHTML use.\r\n // Since no whitespace is passed to innerHTML, whitespace is preserved.\r\n return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {\r\n // Check for cached entity.\r\n var value = seen[s];\r\n if (value) {\r\n return value;\r\n }\r\n // Check for numeric entity.\r\n if (entity.charAt(0) == '#') {\r\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex numbers.\r\n var n = Number('0' + entity.substr(1));\r\n if (!isNaN(n)) {\r\n value = String.fromCharCode(n);\r\n }\r\n }\r\n // Fall back to innerHTML otherwise.\r\n if (!value) {\r\n // Append a non-entity character to avoid a bug in Webkit that parses\r\n // an invalid entity at the end of innerHTML text as the empty string.\r\n div.innerHTML = s + ' ';\r\n // Then remove the trailing character from the result.\r\n value = div.firstChild.nodeValue.slice(0, -1);\r\n }\r\n // Cache and return.\r\n return seen[s] = value;\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Unescapes XML entities.\r\n * @private\r\n * @param {string} str The string to unescape.\r\n * @return {string} An unescaped copy of `str`.\r\n */\r\ngoog.string.unescapePureXmlEntities_ = function(str) {\r\n return str.replace(/&([^;]+);/g, function(s, entity) {\r\n switch (entity) {\r\n case 'amp':\r\n return '&';\r\n case 'lt':\r\n return '<';\r\n case 'gt':\r\n return '>';\r\n case 'quot':\r\n return '\"';\r\n default:\r\n if (entity.charAt(0) == '#') {\r\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex.\r\n var n = Number('0' + entity.substr(1));\r\n if (!isNaN(n)) {\r\n return String.fromCharCode(n);\r\n }\r\n }\r\n // For invalid entities we just return the entity\r\n return s;\r\n }\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Regular expression that matches an HTML entity.\r\n * See also HTML5: Tokenization / Tokenizing character references.\r\n * @private\r\n * @type {!RegExp}\r\n */\r\ngoog.string.HTML_ENTITY_PATTERN_ = /&([^;\\s<&]+);?/g;\r\n\r\n\r\n/**\r\n * Do escaping of whitespace to preserve spatial formatting. We use character\r\n * entity #160 to make it safer for xml.\r\n * @param {string} str The string in which to escape whitespace.\r\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\r\n * @return {string} An escaped copy of `str`.\r\n */\r\ngoog.string.whitespaceEscape = function(str, opt_xml) {\r\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\r\n return goog.string.newLineToBr(str.replace(/ /g, ' &#160;'), opt_xml);\r\n};\r\n\r\n\r\n/**\r\n * Preserve spaces that would be otherwise collapsed in HTML by replacing them\r\n * with non-breaking space Unicode characters.\r\n * @param {string} str The string in which to preserve whitespace.\r\n * @return {string} A copy of `str` with preserved whitespace.\r\n */\r\ngoog.string.preserveSpaces = function(str) {\r\n return str.replace(/(^|[\\n ]) /g, '$1' + goog.string.Unicode.NBSP);\r\n};\r\n\r\n\r\n/**\r\n * Strip quote characters around a string. The second argument is a string of\r\n * characters to treat as quotes. This can be a single character or a string of\r\n * multiple character and in that case each of those are treated as possible\r\n * quote characters. For example:\r\n *\r\n * <pre>\r\n * goog.string.stripQuotes('\"abc\"', '\"`') --> 'abc'\r\n * goog.string.stripQuotes('`abc`', '\"`') --> 'abc'\r\n * </pre>\r\n *\r\n * @param {string} str The string to strip.\r\n * @param {string} quoteChars The quote characters to strip.\r\n * @return {string} A copy of `str` without the quotes.\r\n */\r\ngoog.string.stripQuotes = function(str, quoteChars) {\r\n var length = quoteChars.length;\r\n for (var i = 0; i < length; i++) {\r\n var quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);\r\n if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {\r\n return str.substring(1, str.length - 1);\r\n }\r\n }\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Truncates a string to a certain length and adds '...' if necessary. The\r\n * length also accounts for the ellipsis, so a maximum length of 10 and a string\r\n * 'Hello World!' produces 'Hello W...'.\r\n * @param {string} str The string to truncate.\r\n * @param {number} chars Max number of characters.\r\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\r\n * characters from being cut off in the middle.\r\n * @return {string} The truncated `str` string.\r\n */\r\ngoog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.unescapeEntities(str);\r\n }\r\n\r\n if (str.length > chars) {\r\n str = str.substring(0, chars - 3) + '...';\r\n }\r\n\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.htmlEscape(str);\r\n }\r\n\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Truncate a string in the middle, adding \"...\" if necessary,\r\n * and favoring the beginning of the string.\r\n * @param {string} str The string to truncate the middle of.\r\n * @param {number} chars Max number of characters.\r\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\r\n * characters from being cutoff in the middle.\r\n * @param {number=} opt_trailingChars Optional number of trailing characters to\r\n * leave at the end of the string, instead of truncating as close to the\r\n * middle as possible.\r\n * @return {string} A truncated copy of `str`.\r\n */\r\ngoog.string.truncateMiddle = function(\r\n str, chars, opt_protectEscapedCharacters, opt_trailingChars) {\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.unescapeEntities(str);\r\n }\r\n\r\n if (opt_trailingChars && str.length > chars) {\r\n if (opt_trailingChars > chars) {\r\n opt_trailingChars = chars;\r\n }\r\n var endPoint = str.length - opt_trailingChars;\r\n var startPoint = chars - opt_trailingChars;\r\n str = str.substring(0, startPoint) + '...' + str.substring(endPoint);\r\n } else if (str.length > chars) {\r\n // Favor the beginning of the string:\r\n var half = Math.floor(chars / 2);\r\n var endPos = str.length - half;\r\n half += chars % 2;\r\n str = str.substring(0, half) + '...' + str.substring(endPos);\r\n }\r\n\r\n if (opt_protectEscapedCharacters) {\r\n str = goog.string.htmlEscape(str);\r\n }\r\n\r\n return str;\r\n};\r\n\r\n\r\n/**\r\n * Special chars that need to be escaped for goog.string.quote.\r\n * @private {!Object<string, string>}\r\n */\r\ngoog.string.specialEscapeChars_ = {\r\n '\\0': '\\\\0',\r\n '\\b': '\\\\b',\r\n '\\f': '\\\\f',\r\n '\\n': '\\\\n',\r\n '\\r': '\\\\r',\r\n '\\t': '\\\\t',\r\n '\\x0B': '\\\\x0B', // '\\v' is not supported in JScript\r\n '\"': '\\\\\"',\r\n '\\\\': '\\\\\\\\',\r\n // To support the use case of embedding quoted strings inside of script\r\n // tags, we have to make sure HTML comments and opening/closing script tags do\r\n // not appear in the resulting string. The specific strings that must be\r\n // escaped are documented at:\r\n // http://www.w3.org/TR/html51/semantics.html#restrictions-for-contents-of-script-elements\r\n '<': '\\x3c'\r\n};\r\n\r\n\r\n/**\r\n * Character mappings used internally for goog.string.escapeChar.\r\n * @private {!Object<string, string>}\r\n */\r\ngoog.string.jsEscapeCache_ = {\r\n '\\'': '\\\\\\''\r\n};\r\n\r\n\r\n/**\r\n * Encloses a string in double quotes and escapes characters so that the\r\n * string is a valid JS string. The resulting string is safe to embed in\r\n * `<script>` tags as \"<\" is escaped.\r\n * @param {string} s The string to quote.\r\n * @return {string} A copy of `s` surrounded by double quotes.\r\n */\r\ngoog.string.quote = function(s) {\r\n s = String(s);\r\n var sb = ['\"'];\r\n for (var i = 0; i < s.length; i++) {\r\n var ch = s.charAt(i);\r\n var cc = ch.charCodeAt(0);\r\n sb[i + 1] = goog.string.specialEscapeChars_[ch] ||\r\n ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));\r\n }\r\n sb.push('\"');\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Takes a string and returns the escaped string for that input string.\r\n * @param {string} str The string to escape.\r\n * @return {string} An escaped string representing `str`.\r\n */\r\ngoog.string.escapeString = function(str) {\r\n var sb = [];\r\n for (var i = 0; i < str.length; i++) {\r\n sb[i] = goog.string.escapeChar(str.charAt(i));\r\n }\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Takes a character and returns the escaped string for that character. For\r\n * example escapeChar(String.fromCharCode(15)) -> \"\\\\x0E\".\r\n * @param {string} c The character to escape.\r\n * @return {string} An escaped string representing `c`.\r\n */\r\ngoog.string.escapeChar = function(c) {\r\n if (c in goog.string.jsEscapeCache_) {\r\n return goog.string.jsEscapeCache_[c];\r\n }\r\n\r\n if (c in goog.string.specialEscapeChars_) {\r\n return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];\r\n }\r\n\r\n var rv = c;\r\n var cc = c.charCodeAt(0);\r\n if (cc > 31 && cc < 127) {\r\n rv = c;\r\n } else {\r\n // tab is 9 but handled above\r\n if (cc < 256) {\r\n rv = '\\\\x';\r\n if (cc < 16 || cc > 256) {\r\n rv += '0';\r\n }\r\n } else {\r\n rv = '\\\\u';\r\n if (cc < 4096) { // \\u1000\r\n rv += '0';\r\n }\r\n }\r\n rv += cc.toString(16).toUpperCase();\r\n }\r\n\r\n return goog.string.jsEscapeCache_[c] = rv;\r\n};\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n */\r\ngoog.string.contains = goog.string.internal.contains;\r\n\r\n\r\n/**\r\n * Determines whether a string contains a substring, ignoring case.\r\n * @param {string} str The string to search.\r\n * @param {string} subString The substring to search for.\r\n * @return {boolean} Whether `str` contains `subString`.\r\n */\r\ngoog.string.caseInsensitiveContains =\r\n goog.string.internal.caseInsensitiveContains;\r\n\r\n\r\n/**\r\n * Returns the non-overlapping occurrences of ss in s.\r\n * If either s or ss evalutes to false, then returns zero.\r\n * @param {string} s The string to look in.\r\n * @param {string} ss The string to look for.\r\n * @return {number} Number of occurrences of ss in s.\r\n */\r\ngoog.string.countOf = function(s, ss) {\r\n return s && ss ? s.split(ss).length - 1 : 0;\r\n};\r\n\r\n\r\n/**\r\n * Removes a substring of a specified length at a specific\r\n * index in a string.\r\n * @param {string} s The base string from which to remove.\r\n * @param {number} index The index at which to remove the substring.\r\n * @param {number} stringLength The length of the substring to remove.\r\n * @return {string} A copy of `s` with the substring removed or the full\r\n * string if nothing is removed or the input is invalid.\r\n */\r\ngoog.string.removeAt = function(s, index, stringLength) {\r\n var resultStr = s;\r\n // If the index is greater or equal to 0 then remove substring\r\n if (index >= 0 && index < s.length && stringLength > 0) {\r\n resultStr = s.substr(0, index) +\r\n s.substr(index + stringLength, s.length - index - stringLength);\r\n }\r\n return resultStr;\r\n};\r\n\r\n\r\n/**\r\n * Removes the first occurrence of a substring from a string.\r\n * @param {string} str The base string from which to remove.\r\n * @param {string} substr The string to remove.\r\n * @return {string} A copy of `str` with `substr` removed or the\r\n * full string if nothing is removed.\r\n */\r\ngoog.string.remove = function(str, substr) {\r\n return str.replace(substr, '');\r\n};\r\n\r\n\r\n/**\r\n * Removes all occurrences of a substring from a string.\r\n * @param {string} s The base string from which to remove.\r\n * @param {string} ss The string to remove.\r\n * @return {string} A copy of `s` with `ss` removed or the full\r\n * string if nothing is removed.\r\n */\r\ngoog.string.removeAll = function(s, ss) {\r\n var re = new RegExp(goog.string.regExpEscape(ss), 'g');\r\n return s.replace(re, '');\r\n};\r\n\r\n\r\n/**\r\n * Replaces all occurrences of a substring of a string with a new substring.\r\n * @param {string} s The base string from which to remove.\r\n * @param {string} ss The string to replace.\r\n * @param {string} replacement The replacement string.\r\n * @return {string} A copy of `s` with `ss` replaced by\r\n * `replacement` or the original string if nothing is replaced.\r\n */\r\ngoog.string.replaceAll = function(s, ss, replacement) {\r\n var re = new RegExp(goog.string.regExpEscape(ss), 'g');\r\n return s.replace(re, replacement.replace(/\\$/g, '$$$$'));\r\n};\r\n\r\n\r\n/**\r\n * Escapes characters in the string that are not safe to use in a RegExp.\r\n * @param {*} s The string to escape. If not a string, it will be casted\r\n * to one.\r\n * @return {string} A RegExp safe, escaped copy of `s`.\r\n */\r\ngoog.string.regExpEscape = function(s) {\r\n return String(s)\r\n .replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\r\n .replace(/\\x08/g, '\\\\x08');\r\n};\r\n\r\n\r\n/**\r\n * Repeats a string n times.\r\n * @param {string} string The string to repeat.\r\n * @param {number} length The number of times to repeat.\r\n * @return {string} A string containing `length` repetitions of\r\n * `string`.\r\n */\r\ngoog.string.repeat = (String.prototype.repeat) ? function(string, length) {\r\n // The native method is over 100 times faster than the alternative.\r\n return string.repeat(length);\r\n} : function(string, length) {\r\n return new Array(length + 1).join(string);\r\n};\r\n\r\n\r\n/**\r\n * Pads number to given length and optionally rounds it to a given precision.\r\n * For example:\r\n * <pre>padNumber(1.25, 2, 3) -> '01.250'\r\n * padNumber(1.25, 2) -> '01.25'\r\n * padNumber(1.25, 2, 1) -> '01.3'\r\n * padNumber(1.25, 0) -> '1.25'</pre>\r\n *\r\n * @param {number} num The number to pad.\r\n * @param {number} length The desired length.\r\n * @param {number=} opt_precision The desired precision.\r\n * @return {string} `num` as a string with the given options.\r\n */\r\ngoog.string.padNumber = function(num, length, opt_precision) {\r\n var s = goog.isDef(opt_precision) ? num.toFixed(opt_precision) : String(num);\r\n var index = s.indexOf('.');\r\n if (index == -1) {\r\n index = s.length;\r\n }\r\n return goog.string.repeat('0', Math.max(0, length - index)) + s;\r\n};\r\n\r\n\r\n/**\r\n * Returns a string representation of the given object, with\r\n * null and undefined being returned as the empty string.\r\n *\r\n * @param {*} obj The object to convert.\r\n * @return {string} A string representation of the `obj`.\r\n */\r\ngoog.string.makeSafe = function(obj) {\r\n return obj == null ? '' : String(obj);\r\n};\r\n\r\n\r\n/**\r\n * Concatenates string expressions. This is useful\r\n * since some browsers are very inefficient when it comes to using plus to\r\n * concat strings. Be careful when using null and undefined here since\r\n * these will not be included in the result. If you need to represent these\r\n * be sure to cast the argument to a String first.\r\n * For example:\r\n * <pre>buildString('a', 'b', 'c', 'd') -> 'abcd'\r\n * buildString(null, undefined) -> ''\r\n * </pre>\r\n * @param {...*} var_args A list of strings to concatenate. If not a string,\r\n * it will be casted to one.\r\n * @return {string} The concatenation of `var_args`.\r\n */\r\ngoog.string.buildString = function(var_args) {\r\n return Array.prototype.join.call(arguments, '');\r\n};\r\n\r\n\r\n/**\r\n * Returns a string with at least 64-bits of randomness.\r\n *\r\n * Doesn't trust JavaScript's random function entirely. Uses a combination of\r\n * random and current timestamp, and then encodes the string in base-36 to\r\n * make it shorter.\r\n *\r\n * @return {string} A random string, e.g. sn1s7vb4gcic.\r\n */\r\ngoog.string.getRandomString = function() {\r\n var x = 2147483648;\r\n return Math.floor(Math.random() * x).toString(36) +\r\n Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);\r\n};\r\n\r\n\r\n/**\r\n * Compares two version numbers.\r\n *\r\n * @param {string|number} version1 Version of first item.\r\n * @param {string|number} version2 Version of second item.\r\n *\r\n * @return {number} 1 if `version1` is higher.\r\n * 0 if arguments are equal.\r\n * -1 if `version2` is higher.\r\n */\r\ngoog.string.compareVersions = goog.string.internal.compareVersions;\r\n\r\n\r\n/**\r\n * String hash function similar to java.lang.String.hashCode().\r\n * The hash code for a string is computed as\r\n * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\r\n * where s[i] is the ith character of the string and n is the length of\r\n * the string. We mod the result to make it between 0 (inclusive) and 2^32\r\n * (exclusive).\r\n * @param {string} str A string.\r\n * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32\r\n * (exclusive). The empty string returns 0.\r\n */\r\ngoog.string.hashCode = function(str) {\r\n var result = 0;\r\n for (var i = 0; i < str.length; ++i) {\r\n // Normalize to 4 byte range, 0 ... 2^32.\r\n result = (31 * result + str.charCodeAt(i)) >>> 0;\r\n }\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * The most recent unique ID. |0 is equivalent to Math.floor in this case.\r\n * @type {number}\r\n * @private\r\n */\r\ngoog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;\r\n\r\n\r\n/**\r\n * Generates and returns a string which is unique in the current document.\r\n * This is useful, for example, to create unique IDs for DOM elements.\r\n * @return {string} A unique id.\r\n */\r\ngoog.string.createUniqueString = function() {\r\n return 'goog_' + goog.string.uniqueStringCounter_++;\r\n};\r\n\r\n\r\n/**\r\n * Converts the supplied string to a number, which may be Infinity or NaN.\r\n * This function strips whitespace: (toNumber(' 123') === 123)\r\n * This function accepts scientific notation: (toNumber('1e1') === 10)\r\n *\r\n * This is better than JavaScript's built-in conversions because, sadly:\r\n * (Number(' ') === 0) and (parseFloat('123a') === 123)\r\n *\r\n * @param {string} str The string to convert.\r\n * @return {number} The number the supplied string represents, or NaN.\r\n */\r\ngoog.string.toNumber = function(str) {\r\n var num = Number(str);\r\n if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {\r\n return NaN;\r\n }\r\n return num;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the given string is lower camel case (e.g. \"isFooBar\").\r\n *\r\n * Note that this assumes the string is entirely letters.\r\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\r\n *\r\n * @param {string} str String to test.\r\n * @return {boolean} Whether the string is lower camel case.\r\n */\r\ngoog.string.isLowerCamelCase = function(str) {\r\n return /^[a-z]+([A-Z][a-z]*)*$/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the given string is upper camel case (e.g. \"FooBarBaz\").\r\n *\r\n * Note that this assumes the string is entirely letters.\r\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\r\n *\r\n * @param {string} str String to test.\r\n * @return {boolean} Whether the string is upper camel case.\r\n */\r\ngoog.string.isUpperCamelCase = function(str) {\r\n return /^([A-Z][a-z]*)+$/.test(str);\r\n};\r\n\r\n\r\n/**\r\n * Converts a string from selector-case to camelCase (e.g. from\r\n * \"multi-part-string\" to \"multiPartString\"), useful for converting\r\n * CSS selectors and HTML dataset keys to their equivalent JS properties.\r\n * @param {string} str The string in selector-case form.\r\n * @return {string} The string in camelCase form.\r\n */\r\ngoog.string.toCamelCase = function(str) {\r\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\r\n return match.toUpperCase();\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Converts a string from camelCase to selector-case (e.g. from\r\n * \"multiPartString\" to \"multi-part-string\"), useful for converting JS\r\n * style and dataset properties to equivalent CSS selectors and HTML keys.\r\n * @param {string} str The string in camelCase form.\r\n * @return {string} The string in selector-case form.\r\n */\r\ngoog.string.toSelectorCase = function(str) {\r\n return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();\r\n};\r\n\r\n\r\n/**\r\n * Converts a string into TitleCase. First character of the string is always\r\n * capitalized in addition to the first letter of every subsequent word.\r\n * Words are delimited by one or more whitespaces by default. Custom delimiters\r\n * can optionally be specified to replace the default, which doesn't preserve\r\n * whitespace delimiters and instead must be explicitly included if needed.\r\n *\r\n * Default delimiter => \" \":\r\n * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'\r\n * goog.string.toTitleCase('one two three') => 'One Two Three'\r\n * goog.string.toTitleCase(' one two ') => ' One Two '\r\n * goog.string.toTitleCase('one_two_three') => 'One_two_three'\r\n * goog.string.toTitleCase('one-two-three') => 'One-two-three'\r\n *\r\n * Custom delimiter => \"_-.\":\r\n * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'\r\n * goog.string.toTitleCase('one two three', '_-.') => 'One two three'\r\n * goog.string.toTitleCase(' one two ', '_-.') => ' one two '\r\n * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'\r\n * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'\r\n * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'\r\n * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'\r\n * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'\r\n *\r\n * @param {string} str String value in camelCase form.\r\n * @param {string=} opt_delimiters Custom delimiter character set used to\r\n * distinguish words in the string value. Each character represents a\r\n * single delimiter. When provided, default whitespace delimiter is\r\n * overridden and must be explicitly included if needed.\r\n * @return {string} String value in TitleCase form.\r\n */\r\ngoog.string.toTitleCase = function(str, opt_delimiters) {\r\n var delimiters = goog.isString(opt_delimiters) ?\r\n goog.string.regExpEscape(opt_delimiters) :\r\n '\\\\s';\r\n\r\n // For IE8, we need to prevent using an empty character set. Otherwise,\r\n // incorrect matching will occur.\r\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\r\n\r\n var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\r\n return str.replace(regexp, function(all, p1, p2) {\r\n return p1 + p2.toUpperCase();\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Capitalizes a string, i.e. converts the first letter to uppercase\r\n * and all other letters to lowercase, e.g.:\r\n *\r\n * goog.string.capitalize('one') => 'One'\r\n * goog.string.capitalize('ONE') => 'One'\r\n * goog.string.capitalize('one two') => 'One two'\r\n *\r\n * Note that this function does not trim initial whitespace.\r\n *\r\n * @param {string} str String value to capitalize.\r\n * @return {string} String value with first letter in uppercase.\r\n */\r\ngoog.string.capitalize = function(str) {\r\n return String(str.charAt(0)).toUpperCase() +\r\n String(str.substr(1)).toLowerCase();\r\n};\r\n\r\n\r\n/**\r\n * Parse a string in decimal or hexidecimal ('0xFFFF') form.\r\n *\r\n * To parse a particular radix, please use parseInt(string, radix) directly. See\r\n * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt\r\n *\r\n * This is a wrapper for the built-in parseInt function that will only parse\r\n * numbers as base 10 or base 16. Some JS implementations assume strings\r\n * starting with \"0\" are intended to be octal. ES3 allowed but discouraged\r\n * this behavior. ES5 forbids it. This function emulates the ES5 behavior.\r\n *\r\n * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj\r\n *\r\n * @param {string|number|null|undefined} value The value to be parsed.\r\n * @return {number} The number, parsed. If the string failed to parse, this\r\n * will be NaN.\r\n */\r\ngoog.string.parseInt = function(value) {\r\n // Force finite numbers to strings.\r\n if (isFinite(value)) {\r\n value = String(value);\r\n }\r\n\r\n if (goog.isString(value)) {\r\n // If the string starts with '0x' or '-0x', parse as hex.\r\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\r\n }\r\n\r\n return NaN;\r\n};\r\n\r\n\r\n/**\r\n * Splits a string on a separator a limited number of times.\r\n *\r\n * This implementation is more similar to Python or Java, where the limit\r\n * parameter specifies the maximum number of splits rather than truncating\r\n * the number of results.\r\n *\r\n * See http://docs.python.org/2/library/stdtypes.html#str.split\r\n * See JavaDoc: http://goo.gl/F2AsY\r\n * See Mozilla reference: http://goo.gl/dZdZs\r\n *\r\n * @param {string} str String to split.\r\n * @param {string} separator The separator.\r\n * @param {number} limit The limit to the number of splits. The resulting array\r\n * will have a maximum length of limit+1. Negative numbers are the same\r\n * as zero.\r\n * @return {!Array<string>} The string, split.\r\n */\r\ngoog.string.splitLimit = function(str, separator, limit) {\r\n var parts = str.split(separator);\r\n var returnVal = [];\r\n\r\n // Only continue doing this while we haven't hit the limit and we have\r\n // parts left.\r\n while (limit > 0 && parts.length) {\r\n returnVal.push(parts.shift());\r\n limit--;\r\n }\r\n\r\n // If there are remaining parts, append them to the end.\r\n if (parts.length) {\r\n returnVal.push(parts.join(separator));\r\n }\r\n\r\n return returnVal;\r\n};\r\n\r\n\r\n/**\r\n * Finds the characters to the right of the last instance of any separator\r\n *\r\n * This function is similar to goog.string.path.baseName, except it can take a\r\n * list of characters to split the string on. It will return the rightmost\r\n * grouping of characters to the right of any separator as a left-to-right\r\n * oriented string.\r\n *\r\n * @see goog.string.path.baseName\r\n * @param {string} str The string\r\n * @param {string|!Array<string>} separators A list of separator characters\r\n * @return {string} The last part of the string with respect to the separators\r\n */\r\ngoog.string.lastComponent = function(str, separators) {\r\n if (!separators) {\r\n return str;\r\n } else if (typeof separators == 'string') {\r\n separators = [separators];\r\n }\r\n\r\n var lastSeparatorIndex = -1;\r\n for (var i = 0; i < separators.length; i++) {\r\n if (separators[i] == '') {\r\n continue;\r\n }\r\n var currentSeparatorIndex = str.lastIndexOf(separators[i]);\r\n if (currentSeparatorIndex > lastSeparatorIndex) {\r\n lastSeparatorIndex = currentSeparatorIndex;\r\n }\r\n }\r\n if (lastSeparatorIndex == -1) {\r\n return str;\r\n }\r\n return str.slice(lastSeparatorIndex + 1);\r\n};\r\n\r\n\r\n/**\r\n * Computes the Levenshtein edit distance between two strings.\r\n * @param {string} a\r\n * @param {string} b\r\n * @return {number} The edit distance between the two strings.\r\n */\r\ngoog.string.editDistance = function(a, b) {\r\n var v0 = [];\r\n var v1 = [];\r\n\r\n if (a == b) {\r\n return 0;\r\n }\r\n\r\n if (!a.length || !b.length) {\r\n return Math.max(a.length, b.length);\r\n }\r\n\r\n for (var i = 0; i < b.length + 1; i++) {\r\n v0[i] = i;\r\n }\r\n\r\n for (var i = 0; i < a.length; i++) {\r\n v1[0] = i + 1;\r\n\r\n for (var j = 0; j < b.length; j++) {\r\n var cost = Number(a[i] != b[j]);\r\n // Cost for the substring is the minimum of adding one character, removing\r\n // one character, or a swap.\r\n v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);\r\n }\r\n\r\n for (var j = 0; j < v0.length; j++) {\r\n v0[j] = v1[j];\r\n }\r\n }\r\n\r\n return v1[b.length];\r\n};\r\n","// Copyright 2008 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Simple utilities for dealing with URI strings.\r\n *\r\n * This is intended to be a lightweight alternative to constructing goog.Uri\r\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\r\n * of how much of its functionality you use, this is designed to be a set of\r\n * mostly-independent utilities so that the compiler includes only what is\r\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\r\n * 1.5k post-gzip. To ensure the savings remain, future developers should\r\n * avoid adding new functionality to existing functions, but instead create\r\n * new ones and factor out shared code.\r\n *\r\n * Many of these utilities have limited functionality, tailored to common\r\n * cases. The query parameter utilities assume that the parameter keys are\r\n * already encoded, since most keys are compile-time alphanumeric strings. The\r\n * query parameter mutation utilities also do not tolerate fragment identifiers.\r\n *\r\n * By design, these functions can be slower than goog.Uri equivalents.\r\n * Repeated calls to some of functions may be quadratic in behavior for IE,\r\n * although the effect is somewhat limited given the 2kb limit.\r\n *\r\n * One advantage of the limited functionality here is that this approach is\r\n * less sensitive to differences in URI encodings than goog.Uri, since these\r\n * functions operate on strings directly, rather than decoding them and\r\n * then re-encoding.\r\n *\r\n * Uses features of RFC 3986 for parsing/formatting URIs:\r\n * http://www.ietf.org/rfc/rfc3986.txt\r\n *\r\n * @author gboyer@google.com (Garrett Boyer) - The \"lightened\" design.\r\n * @author msamuel@google.com (Mike Samuel) - Domain knowledge and regexes.\r\n */\r\n\r\ngoog.provide('goog.uri.utils');\r\ngoog.provide('goog.uri.utils.ComponentIndex');\r\ngoog.provide('goog.uri.utils.QueryArray');\r\ngoog.provide('goog.uri.utils.QueryValue');\r\ngoog.provide('goog.uri.utils.StandardQueryParam');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * Character codes inlined to avoid object allocations due to charCode.\r\n * @enum {number}\r\n * @private\r\n */\r\ngoog.uri.utils.CharCode_ = {\r\n AMPERSAND: 38,\r\n EQUAL: 61,\r\n HASH: 35,\r\n QUESTION: 63\r\n};\r\n\r\n\r\n/**\r\n * Builds a URI string from already-encoded parts.\r\n *\r\n * No encoding is performed. Any component may be omitted as either null or\r\n * undefined.\r\n *\r\n * @param {?string=} opt_scheme The scheme such as 'http'.\r\n * @param {?string=} opt_userInfo The user name before the '@'.\r\n * @param {?string=} opt_domain The domain such as 'www.google.com', already\r\n * URI-encoded.\r\n * @param {(string|number|null)=} opt_port The port number.\r\n * @param {?string=} opt_path The path, already URI-encoded. If it is not\r\n * empty, it must begin with a slash.\r\n * @param {?string=} opt_queryData The URI-encoded query data.\r\n * @param {?string=} opt_fragment The URI-encoded fragment identifier.\r\n * @return {string} The fully combined URI.\r\n */\r\ngoog.uri.utils.buildFromEncodedParts = function(\r\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,\r\n opt_fragment) {\r\n var out = '';\r\n\r\n if (opt_scheme) {\r\n out += opt_scheme + ':';\r\n }\r\n\r\n if (opt_domain) {\r\n out += '//';\r\n\r\n if (opt_userInfo) {\r\n out += opt_userInfo + '@';\r\n }\r\n\r\n out += opt_domain;\r\n\r\n if (opt_port) {\r\n out += ':' + opt_port;\r\n }\r\n }\r\n\r\n if (opt_path) {\r\n out += opt_path;\r\n }\r\n\r\n if (opt_queryData) {\r\n out += '?' + opt_queryData;\r\n }\r\n\r\n if (opt_fragment) {\r\n out += '#' + opt_fragment;\r\n }\r\n\r\n return out;\r\n};\r\n\r\n\r\n/**\r\n * A regular expression for breaking a URI into its component parts.\r\n *\r\n * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B\r\n * As the \"first-match-wins\" algorithm is identical to the \"greedy\"\r\n * disambiguation method used by POSIX regular expressions, it is natural and\r\n * commonplace to use a regular expression for parsing the potential five\r\n * components of a URI reference.\r\n *\r\n * The following line is the regular expression for breaking-down a\r\n * well-formed URI reference into its components.\r\n *\r\n * <pre>\r\n * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\r\n * 12 3 4 5 6 7 8 9\r\n * </pre>\r\n *\r\n * The numbers in the second line above are only to assist readability; they\r\n * indicate the reference points for each subexpression (i.e., each paired\r\n * parenthesis). We refer to the value matched for subexpression <n> as $<n>.\r\n * For example, matching the above expression to\r\n * <pre>\r\n * http://www.ics.uci.edu/pub/ietf/uri/#Related\r\n * </pre>\r\n * results in the following subexpression matches:\r\n * <pre>\r\n * $1 = http:\r\n * $2 = http\r\n * $3 = //www.ics.uci.edu\r\n * $4 = www.ics.uci.edu\r\n * $5 = /pub/ietf/uri/\r\n * $6 = <undefined>\r\n * $7 = <undefined>\r\n * $8 = #Related\r\n * $9 = Related\r\n * </pre>\r\n * where <undefined> indicates that the component is not present, as is the\r\n * case for the query component in the above example. Therefore, we can\r\n * determine the value of the five components as\r\n * <pre>\r\n * scheme = $2\r\n * authority = $4\r\n * path = $5\r\n * query = $7\r\n * fragment = $9\r\n * </pre>\r\n *\r\n * The regular expression has been modified slightly to expose the\r\n * userInfo, domain, and port separately from the authority.\r\n * The modified version yields\r\n * <pre>\r\n * $1 = http scheme\r\n * $2 = <undefined> userInfo -\\\r\n * $3 = www.ics.uci.edu domain | authority\r\n * $4 = <undefined> port -/\r\n * $5 = /pub/ietf/uri/ path\r\n * $6 = <undefined> query without ?\r\n * $7 = Related fragment without #\r\n * </pre>\r\n * @type {!RegExp}\r\n * @private\r\n */\r\ngoog.uri.utils.splitRe_ = new RegExp(\r\n '^' +\r\n '(?:' +\r\n '([^:/?#.]+)' + // scheme - ignore special characters\r\n // used by other URL parts such as :,\r\n // ?, /, #, and .\r\n ':)?' +\r\n '(?://' +\r\n '(?:([^/?#]*)@)?' + // userInfo\r\n '([^/#?]*?)' + // domain\r\n '(?::([0-9]+))?' + // port\r\n '(?=[/#?]|$)' + // authority-terminating character\r\n ')?' +\r\n '([^?#]+)?' + // path\r\n '(?:\\\\?([^#]*))?' + // query\r\n '(?:#([\\\\s\\\\S]*))?' + // fragment\r\n '$');\r\n\r\n\r\n/**\r\n * The index of each URI component in the return value of goog.uri.utils.split.\r\n * @enum {number}\r\n */\r\ngoog.uri.utils.ComponentIndex = {\r\n SCHEME: 1,\r\n USER_INFO: 2,\r\n DOMAIN: 3,\r\n PORT: 4,\r\n PATH: 5,\r\n QUERY_DATA: 6,\r\n FRAGMENT: 7\r\n};\r\n\r\n\r\n/**\r\n * Splits a URI into its component parts.\r\n *\r\n * Each component can be accessed via the component indices; for example:\r\n * <pre>\r\n * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];\r\n * </pre>\r\n *\r\n * @param {string} uri The URI string to examine.\r\n * @return {!Array<string|undefined>} Each component still URI-encoded.\r\n * Each component that is present will contain the encoded value, whereas\r\n * components that are not present will be undefined or empty, depending\r\n * on the browser's regular expression implementation. Never null, since\r\n * arbitrary strings may still look like path names.\r\n */\r\ngoog.uri.utils.split = function(uri) {\r\n // See @return comment -- never null.\r\n return /** @type {!Array<string|undefined>} */ (\r\n uri.match(goog.uri.utils.splitRe_));\r\n};\r\n\r\n\r\n/**\r\n * @param {?string} uri A possibly null string.\r\n * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986\r\n * reserved characters will not be removed.\r\n * @return {?string} The string URI-decoded, or null if uri is null.\r\n * @private\r\n */\r\ngoog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {\r\n if (!uri) {\r\n return uri;\r\n }\r\n\r\n return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);\r\n};\r\n\r\n\r\n/**\r\n * Gets a URI component by index.\r\n *\r\n * It is preferred to use the getPathEncoded() variety of functions ahead,\r\n * since they are more readable.\r\n *\r\n * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The still-encoded component, or null if the component\r\n * is not present.\r\n * @private\r\n */\r\ngoog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {\r\n // Convert undefined, null, and empty string into null.\r\n return goog.uri.utils.split(uri)[componentIndex] || null;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The protocol or scheme, or null if none. Does not\r\n * include trailing colons or slashes.\r\n */\r\ngoog.uri.utils.getScheme = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.SCHEME, uri);\r\n};\r\n\r\n\r\n/**\r\n * Gets the effective scheme for the URL. If the URL is relative then the\r\n * scheme is derived from the page's location.\r\n * @param {string} uri The URI to examine.\r\n * @return {string} The protocol or scheme, always lower case.\r\n */\r\ngoog.uri.utils.getEffectiveScheme = function(uri) {\r\n var scheme = goog.uri.utils.getScheme(uri);\r\n if (!scheme && goog.global.self && goog.global.self.location) {\r\n var protocol = goog.global.self.location.protocol;\r\n scheme = protocol.substr(0, protocol.length - 1);\r\n }\r\n // NOTE: When called from a web worker in Firefox 3.5, location may be null.\r\n // All other browsers with web workers support self.location from the worker.\r\n return scheme ? scheme.toLowerCase() : '';\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The user name still encoded, or null if none.\r\n */\r\ngoog.uri.utils.getUserInfoEncoded = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.USER_INFO, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded user info, or null if none.\r\n */\r\ngoog.uri.utils.getUserInfo = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getUserInfoEncoded(uri));\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The domain name still encoded, or null if none.\r\n */\r\ngoog.uri.utils.getDomainEncoded = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.DOMAIN, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded domain, or null if none.\r\n */\r\ngoog.uri.utils.getDomain = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?number} The port number, or null if none.\r\n */\r\ngoog.uri.utils.getPort = function(uri) {\r\n // Coerce to a number. If the result of getComponentByIndex_ is null or\r\n // non-numeric, the number coersion yields NaN. This will then return\r\n // null for all non-numeric cases (though also zero, which isn't a relevant\r\n // port number).\r\n return Number(\r\n goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.PORT, uri)) ||\r\n null;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The path still encoded, or null if none. Includes the\r\n * leading slash, if any.\r\n */\r\ngoog.uri.utils.getPathEncoded = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.PATH, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded path, or null if none. Includes the leading\r\n * slash, if any.\r\n */\r\ngoog.uri.utils.getPath = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The query data still encoded, or null if none. Does not\r\n * include the question mark itself.\r\n */\r\ngoog.uri.utils.getQueryData = function(uri) {\r\n return goog.uri.utils.getComponentByIndex_(\r\n goog.uri.utils.ComponentIndex.QUERY_DATA, uri);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The fragment identifier, or null if none. Does not\r\n * include the hash mark itself.\r\n */\r\ngoog.uri.utils.getFragmentEncoded = function(uri) {\r\n // The hash mark may not appear in any other part of the URL.\r\n var hashIndex = uri.indexOf('#');\r\n return hashIndex < 0 ? null : uri.substr(hashIndex + 1);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @param {?string} fragment The encoded fragment identifier, or null if none.\r\n * Does not include the hash mark itself.\r\n * @return {string} The URI with the fragment set.\r\n */\r\ngoog.uri.utils.setFragmentEncoded = function(uri, fragment) {\r\n return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri The URI to examine.\r\n * @return {?string} The decoded fragment identifier, or null if none. Does\r\n * not include the hash mark.\r\n */\r\ngoog.uri.utils.getFragment = function(uri) {\r\n return goog.uri.utils.decodeIfPossible_(\r\n goog.uri.utils.getFragmentEncoded(uri));\r\n};\r\n\r\n\r\n/**\r\n * Extracts everything up to the port of the URI.\r\n * @param {string} uri The URI string.\r\n * @return {string} Everything up to and including the port.\r\n */\r\ngoog.uri.utils.getHost = function(uri) {\r\n var pieces = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n pieces[goog.uri.utils.ComponentIndex.SCHEME],\r\n pieces[goog.uri.utils.ComponentIndex.USER_INFO],\r\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\r\n pieces[goog.uri.utils.ComponentIndex.PORT]);\r\n};\r\n\r\n\r\n/**\r\n * Returns the origin for a given URL.\r\n * @param {string} uri The URI string.\r\n * @return {string} Everything up to and including the port.\r\n */\r\ngoog.uri.utils.getOrigin = function(uri) {\r\n var pieces = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,\r\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\r\n pieces[goog.uri.utils.ComponentIndex.PORT]);\r\n};\r\n\r\n\r\n/**\r\n * Extracts the path of the URL and everything after.\r\n * @param {string} uri The URI string.\r\n * @return {string} The URI, starting at the path and including the query\r\n * parameters and fragment identifier.\r\n */\r\ngoog.uri.utils.getPathAndAfter = function(uri) {\r\n var pieces = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],\r\n pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],\r\n pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);\r\n};\r\n\r\n\r\n/**\r\n * Gets the URI with the fragment identifier removed.\r\n * @param {string} uri The URI to examine.\r\n * @return {string} Everything preceding the hash mark.\r\n */\r\ngoog.uri.utils.removeFragment = function(uri) {\r\n // The hash mark may not appear in any other part of the URL.\r\n var hashIndex = uri.indexOf('#');\r\n return hashIndex < 0 ? uri : uri.substr(0, hashIndex);\r\n};\r\n\r\n\r\n/**\r\n * Ensures that two URI's have the exact same domain, scheme, and port.\r\n *\r\n * Unlike the version in goog.Uri, this checks protocol, and therefore is\r\n * suitable for checking against the browser's same-origin policy.\r\n *\r\n * @param {string} uri1 The first URI.\r\n * @param {string} uri2 The second URI.\r\n * @return {boolean} Whether they have the same scheme, domain and port.\r\n */\r\ngoog.uri.utils.haveSameDomain = function(uri1, uri2) {\r\n var pieces1 = goog.uri.utils.split(uri1);\r\n var pieces2 = goog.uri.utils.split(uri2);\r\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\r\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\r\n pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==\r\n pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&\r\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\r\n pieces2[goog.uri.utils.ComponentIndex.PORT];\r\n};\r\n\r\n\r\n/**\r\n * Asserts that there are no fragment or query identifiers, only in uncompiled\r\n * mode.\r\n * @param {string} uri The URI to examine.\r\n * @private\r\n */\r\ngoog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {\r\n goog.asserts.assert(\r\n uri.indexOf('#') < 0 && uri.indexOf('?') < 0,\r\n 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',\r\n uri);\r\n};\r\n\r\n\r\n/**\r\n * Supported query parameter values by the parameter serializing utilities.\r\n *\r\n * If a value is null or undefined, the key-value pair is skipped, as an easy\r\n * way to omit parameters conditionally. Non-array parameters are converted\r\n * to a string and URI encoded. Array values are expanded into multiple\r\n * &key=value pairs, with each element stringized and URI-encoded.\r\n *\r\n * @typedef {*}\r\n */\r\ngoog.uri.utils.QueryValue;\r\n\r\n\r\n/**\r\n * An array representing a set of query parameters with alternating keys\r\n * and values.\r\n *\r\n * Keys are assumed to be URI encoded already and live at even indices. See\r\n * goog.uri.utils.QueryValue for details on how parameter values are encoded.\r\n *\r\n * Example:\r\n * <pre>\r\n * var data = [\r\n * // Simple param: ?name=BobBarker\r\n * 'name', 'BobBarker',\r\n * // Conditional param -- may be omitted entirely.\r\n * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,\r\n * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null\r\n * 'house', ['LosAngeles', 'NewYork', null]\r\n * ];\r\n * </pre>\r\n *\r\n * @typedef {!Array<string|goog.uri.utils.QueryValue>}\r\n */\r\ngoog.uri.utils.QueryArray;\r\n\r\n\r\n/**\r\n * Parses encoded query parameters and calls callback function for every\r\n * parameter found in the string.\r\n *\r\n * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an\r\n * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means\r\n * that “…&=&…” and “…&&…” will result in an empty key and value.\r\n *\r\n * @param {string} encodedQuery Encoded query string excluding question mark at\r\n * the beginning.\r\n * @param {function(string, string)} callback Function called for every\r\n * parameter found in query string. The first argument (name) will not be\r\n * urldecoded (so the function is consistent with buildQueryData), but the\r\n * second will. If the parameter has no value (i.e. “=” was not present)\r\n * the second argument (value) will be an empty string.\r\n */\r\ngoog.uri.utils.parseQueryData = function(encodedQuery, callback) {\r\n if (!encodedQuery) {\r\n return;\r\n }\r\n var pairs = encodedQuery.split('&');\r\n for (var i = 0; i < pairs.length; i++) {\r\n var indexOfEquals = pairs[i].indexOf('=');\r\n var name = null;\r\n var value = null;\r\n if (indexOfEquals >= 0) {\r\n name = pairs[i].substring(0, indexOfEquals);\r\n value = pairs[i].substring(indexOfEquals + 1);\r\n } else {\r\n name = pairs[i];\r\n }\r\n callback(name, value ? goog.string.urlDecode(value) : '');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Split the URI into 3 parts where the [1] is the queryData without a leading\r\n * '?'. For example, the URI http://foo.com/bar?a=b#abc returns\r\n * ['http://foo.com/bar','a=b','#abc'].\r\n * @param {string} uri The URI to parse.\r\n * @return {!Array<string>} An array representation of uri of length 3 where the\r\n * middle value is the queryData without a leading '?'.\r\n * @private\r\n */\r\ngoog.uri.utils.splitQueryData_ = function(uri) {\r\n // Find the query data and hash.\r\n var hashIndex = uri.indexOf('#');\r\n if (hashIndex < 0) {\r\n hashIndex = uri.length;\r\n }\r\n var questionIndex = uri.indexOf('?');\r\n var queryData;\r\n if (questionIndex < 0 || questionIndex > hashIndex) {\r\n questionIndex = hashIndex;\r\n queryData = '';\r\n } else {\r\n queryData = uri.substring(questionIndex + 1, hashIndex);\r\n }\r\n return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)];\r\n};\r\n\r\n\r\n/**\r\n * Join an array created by splitQueryData_ back into a URI.\r\n * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.\r\n * @return {string} The joined URI.\r\n * @private\r\n */\r\ngoog.uri.utils.joinQueryData_ = function(parts) {\r\n return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];\r\n};\r\n\r\n\r\n/**\r\n * @param {string} queryData\r\n * @param {string} newData\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.uri.utils.appendQueryData_ = function(queryData, newData) {\r\n if (!newData) {\r\n return queryData;\r\n }\r\n return queryData ? queryData + '&' + newData : newData;\r\n};\r\n\r\n\r\n/**\r\n * @param {string} uri\r\n * @param {string} queryData\r\n * @return {string}\r\n * @private\r\n */\r\ngoog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {\r\n if (!queryData) {\r\n return uri;\r\n }\r\n var parts = goog.uri.utils.splitQueryData_(uri);\r\n parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);\r\n return goog.uri.utils.joinQueryData_(parts);\r\n};\r\n\r\n\r\n/**\r\n * Appends key=value pairs to an array, supporting multi-valued objects.\r\n * @param {*} key The key prefix.\r\n * @param {goog.uri.utils.QueryValue} value The value to serialize.\r\n * @param {!Array<string>} pairs The array to which the 'key=value' strings\r\n * should be appended.\r\n * @private\r\n */\r\ngoog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {\r\n goog.asserts.assertString(key);\r\n if (goog.isArray(value)) {\r\n // Convince the compiler it's an array.\r\n goog.asserts.assertArray(value);\r\n for (var j = 0; j < value.length; j++) {\r\n // Convert to string explicitly, to short circuit the null and array\r\n // logic in this function -- this ensures that null and undefined get\r\n // written as literal 'null' and 'undefined', and arrays don't get\r\n // expanded out but instead encoded in the default way.\r\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\r\n }\r\n } else if (value != null) {\r\n // Skip a top-level null or undefined entirely.\r\n pairs.push(\r\n key +\r\n // Check for empty string. Zero gets encoded into the url as literal\r\n // strings. For empty string, skip the equal sign, to be consistent\r\n // with UriBuilder.java.\r\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Builds a query data string from a sequence of alternating keys and values.\r\n * Currently generates \"&key&\" for empty args.\r\n *\r\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\r\n * Alternating keys and values. See the QueryArray typedef.\r\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\r\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\r\n */\r\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\r\n goog.asserts.assert(\r\n Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,\r\n 'goog.uri.utils: Key/value lists must be even in length.');\r\n\r\n var params = [];\r\n for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {\r\n var key = /** @type {string} */ (keysAndValues[i]);\r\n goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);\r\n }\r\n return params.join('&');\r\n};\r\n\r\n\r\n/**\r\n * Builds a query data string from a map.\r\n * Currently generates \"&key&\" for empty args.\r\n *\r\n * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys\r\n * are URI-encoded parameter keys, and the values are arbitrary types\r\n * or arrays. Keys with a null value are dropped.\r\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\r\n */\r\ngoog.uri.utils.buildQueryDataFromMap = function(map) {\r\n var params = [];\r\n for (var key in map) {\r\n goog.uri.utils.appendKeyValuePairs_(key, map[key], params);\r\n }\r\n return params.join('&');\r\n};\r\n\r\n\r\n/**\r\n * Appends URI parameters to an existing URI.\r\n *\r\n * The variable arguments may contain alternating keys and values. Keys are\r\n * assumed to be already URI encoded. The values should not be URI-encoded,\r\n * and will instead be encoded by this function.\r\n * <pre>\r\n * appendParams('http://www.foo.com?existing=true',\r\n * 'key1', 'value1',\r\n * 'key2', 'value?willBeEncoded',\r\n * 'key3', ['valueA', 'valueB', 'valueC'],\r\n * 'key4', null);\r\n * result: 'http://www.foo.com?existing=true&' +\r\n * 'key1=value1&' +\r\n * 'key2=value%3FwillBeEncoded&' +\r\n * 'key3=valueA&key3=valueB&key3=valueC'\r\n * </pre>\r\n *\r\n * A single call to this function will not exhibit quadratic behavior in IE,\r\n * whereas multiple repeated calls may, although the effect is limited by\r\n * fact that URL's generally can't exceed 2kb.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}\r\n * var_args\r\n * An array or argument list conforming to goog.uri.utils.QueryArray.\r\n * @return {string} The URI with all query parameters added.\r\n */\r\ngoog.uri.utils.appendParams = function(uri, var_args) {\r\n var queryData = arguments.length == 2 ?\r\n goog.uri.utils.buildQueryData(arguments[1], 0) :\r\n goog.uri.utils.buildQueryData(arguments, 1);\r\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\r\n};\r\n\r\n\r\n/**\r\n * Appends query parameters from a map.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are\r\n * URI-encoded parameter keys, and the values are arbitrary types or arrays.\r\n * Keys with a null value are dropped.\r\n * @return {string} The new parameters.\r\n */\r\ngoog.uri.utils.appendParamsFromMap = function(uri, map) {\r\n var queryData = goog.uri.utils.buildQueryDataFromMap(map);\r\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\r\n};\r\n\r\n\r\n/**\r\n * Appends a single URI parameter.\r\n *\r\n * Repeated calls to this can exhibit quadratic behavior in IE6 due to the\r\n * way string append works, though it should be limited given the 2kb limit.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {string} key The key, which must already be URI encoded.\r\n * @param {*=} opt_value The value, which will be stringized and encoded\r\n * (assumed not already to be encoded). If omitted, undefined, or null, the\r\n * key will be added as a valueless parameter.\r\n * @return {string} The URI with the query parameter added.\r\n */\r\ngoog.uri.utils.appendParam = function(uri, key, opt_value) {\r\n var value = goog.isDefAndNotNull(opt_value) ?\r\n '=' + goog.string.urlEncode(opt_value) :\r\n '';\r\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\r\n};\r\n\r\n\r\n/**\r\n * Finds the next instance of a query parameter with the specified name.\r\n *\r\n * Does not instantiate any objects.\r\n *\r\n * @param {string} uri The URI to search. May contain a fragment identifier\r\n * if opt_hashIndex is specified.\r\n * @param {number} startIndex The index to begin searching for the key at. A\r\n * match may be found even if this is one character after the ampersand.\r\n * @param {string} keyEncoded The URI-encoded key.\r\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\r\n * mark is present, it should be its index, otherwise it should be the\r\n * length of the string.\r\n * @return {number} The position of the first character in the key's name,\r\n * immediately after either a question mark or a dot.\r\n * @private\r\n */\r\ngoog.uri.utils.findParam_ = function(\r\n uri, startIndex, keyEncoded, hashOrEndIndex) {\r\n var index = startIndex;\r\n var keyLength = keyEncoded.length;\r\n\r\n // Search for the key itself and post-filter for surronuding punctuation,\r\n // rather than expensively building a regexp.\r\n while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&\r\n index < hashOrEndIndex) {\r\n var precedingChar = uri.charCodeAt(index - 1);\r\n // Ensure that the preceding character is '&' or '?'.\r\n if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||\r\n precedingChar == goog.uri.utils.CharCode_.QUESTION) {\r\n // Ensure the following character is '&', '=', '#', or NaN\r\n // (end of string).\r\n var followingChar = uri.charCodeAt(index + keyLength);\r\n if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||\r\n followingChar == goog.uri.utils.CharCode_.AMPERSAND ||\r\n followingChar == goog.uri.utils.CharCode_.HASH) {\r\n return index;\r\n }\r\n }\r\n index += keyLength + 1;\r\n }\r\n\r\n return -1;\r\n};\r\n\r\n\r\n/**\r\n * Regular expression for finding a hash mark or end of string.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.uri.utils.hashOrEndRe_ = /#|$/;\r\n\r\n\r\n/**\r\n * Determines if the URI contains a specific key.\r\n *\r\n * Performs no object instantiations.\r\n *\r\n * @param {string} uri The URI to process. May contain a fragment\r\n * identifier.\r\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\r\n * @return {boolean} Whether the key is present.\r\n */\r\ngoog.uri.utils.hasParam = function(uri, keyEncoded) {\r\n return goog.uri.utils.findParam_(\r\n uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;\r\n};\r\n\r\n\r\n/**\r\n * Gets the first value of a query parameter.\r\n * @param {string} uri The URI to process. May contain a fragment.\r\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\r\n * @return {?string} The first value of the parameter (URI-decoded), or null\r\n * if the parameter is not found.\r\n */\r\ngoog.uri.utils.getParamValue = function(uri, keyEncoded) {\r\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\r\n var foundIndex =\r\n goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);\r\n\r\n if (foundIndex < 0) {\r\n return null;\r\n } else {\r\n var endPosition = uri.indexOf('&', foundIndex);\r\n if (endPosition < 0 || endPosition > hashOrEndIndex) {\r\n endPosition = hashOrEndIndex;\r\n }\r\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\r\n foundIndex += keyEncoded.length + 1;\r\n // Use substr, because it (unlike substring) will return empty string\r\n // if foundIndex > endPosition.\r\n return goog.string.urlDecode(\r\n uri.substr(foundIndex, endPosition - foundIndex));\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Gets all values of a query parameter.\r\n * @param {string} uri The URI to process. May contain a fragment.\r\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\r\n * @return {!Array<string>} All URI-decoded values with the given key.\r\n * If the key is not found, this will have length 0, but never be null.\r\n */\r\ngoog.uri.utils.getParamValues = function(uri, keyEncoded) {\r\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\r\n var position = 0;\r\n var foundIndex;\r\n var result = [];\r\n\r\n while ((foundIndex = goog.uri.utils.findParam_(\r\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\r\n // Find where this parameter ends, either the '&' or the end of the\r\n // query parameters.\r\n position = uri.indexOf('&', foundIndex);\r\n if (position < 0 || position > hashOrEndIndex) {\r\n position = hashOrEndIndex;\r\n }\r\n\r\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\r\n foundIndex += keyEncoded.length + 1;\r\n // Use substr, because it (unlike substring) will return empty string\r\n // if foundIndex > position.\r\n result.push(\r\n goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex)));\r\n }\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Regexp to find trailing question marks and ampersands.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;\r\n\r\n\r\n/**\r\n * Removes all instances of a query parameter.\r\n * @param {string} uri The URI to process. Must not contain a fragment.\r\n * @param {string} keyEncoded The URI-encoded key.\r\n * @return {string} The URI with all instances of the parameter removed.\r\n */\r\ngoog.uri.utils.removeParam = function(uri, keyEncoded) {\r\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\r\n var position = 0;\r\n var foundIndex;\r\n var buffer = [];\r\n\r\n // Look for a query parameter.\r\n while ((foundIndex = goog.uri.utils.findParam_(\r\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\r\n // Get the portion of the query string up to, but not including, the ?\r\n // or & starting the parameter.\r\n buffer.push(uri.substring(position, foundIndex));\r\n // Progress to immediately after the '&'. If not found, go to the end.\r\n // Avoid including the hash mark.\r\n position = Math.min(\r\n (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);\r\n }\r\n\r\n // Append everything that is remaining.\r\n buffer.push(uri.substr(position));\r\n\r\n // Join the buffer, and remove trailing punctuation that remains.\r\n return buffer.join('').replace(\r\n goog.uri.utils.trailingQueryPunctuationRe_, '$1');\r\n};\r\n\r\n\r\n/**\r\n * Replaces all existing definitions of a parameter with a single definition.\r\n *\r\n * Repeated calls to this can exhibit quadratic behavior due to the need to\r\n * find existing instances and reconstruct the string, though it should be\r\n * limited given the 2kb limit. Consider using appendParams or setParamsFromMap\r\n * to update multiple parameters in bulk.\r\n *\r\n * @param {string} uri The original URI, which may already have query data.\r\n * @param {string} keyEncoded The key, which must already be URI encoded.\r\n * @param {*} value The value, which will be stringized and encoded (assumed\r\n * not already to be encoded).\r\n * @return {string} The URI with the query parameter added.\r\n */\r\ngoog.uri.utils.setParam = function(uri, keyEncoded, value) {\r\n return goog.uri.utils.appendParam(\r\n goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);\r\n};\r\n\r\n\r\n/**\r\n * Effeciently set or remove multiple query parameters in a URI. Order of\r\n * unchanged parameters will not be modified, all updated parameters will be\r\n * appended to the end of the query. Params with values of null or undefined are\r\n * removed.\r\n *\r\n * @param {string} uri The URI to process.\r\n * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of\r\n * parameters to update. If null or undefined, the param will be removed.\r\n * @return {string} An updated URI where the query data has been updated with\r\n * the params.\r\n */\r\ngoog.uri.utils.setParamsFromMap = function(uri, params) {\r\n var parts = goog.uri.utils.splitQueryData_(uri);\r\n var queryData = parts[1];\r\n var buffer = [];\r\n if (queryData) {\r\n goog.array.forEach(queryData.split('&'), function(pair) {\r\n var indexOfEquals = pair.indexOf('=');\r\n var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair;\r\n if (!params.hasOwnProperty(name)) {\r\n buffer.push(pair);\r\n }\r\n });\r\n }\r\n parts[1] = goog.uri.utils.appendQueryData_(\r\n buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));\r\n return goog.uri.utils.joinQueryData_(parts);\r\n};\r\n\r\n\r\n/**\r\n * Generates a URI path using a given URI and a path with checks to\r\n * prevent consecutive \"//\". The baseUri passed in must not contain\r\n * query or fragment identifiers. The path to append may not contain query or\r\n * fragment identifiers.\r\n *\r\n * @param {string} baseUri URI to use as the base.\r\n * @param {string} path Path to append.\r\n * @return {string} Updated URI.\r\n */\r\ngoog.uri.utils.appendPath = function(baseUri, path) {\r\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\r\n\r\n // Remove any trailing '/'\r\n if (goog.string.endsWith(baseUri, '/')) {\r\n baseUri = baseUri.substr(0, baseUri.length - 1);\r\n }\r\n // Remove any leading '/'\r\n if (goog.string.startsWith(path, '/')) {\r\n path = path.substr(1);\r\n }\r\n return goog.string.buildString(baseUri, '/', path);\r\n};\r\n\r\n\r\n/**\r\n * Replaces the path.\r\n * @param {string} uri URI to use as the base.\r\n * @param {string} path New path.\r\n * @return {string} Updated URI.\r\n */\r\ngoog.uri.utils.setPath = function(uri, path) {\r\n // Add any missing '/'.\r\n if (!goog.string.startsWith(path, '/')) {\r\n path = '/' + path;\r\n }\r\n var parts = goog.uri.utils.split(uri);\r\n return goog.uri.utils.buildFromEncodedParts(\r\n parts[goog.uri.utils.ComponentIndex.SCHEME],\r\n parts[goog.uri.utils.ComponentIndex.USER_INFO],\r\n parts[goog.uri.utils.ComponentIndex.DOMAIN],\r\n parts[goog.uri.utils.ComponentIndex.PORT], path,\r\n parts[goog.uri.utils.ComponentIndex.QUERY_DATA],\r\n parts[goog.uri.utils.ComponentIndex.FRAGMENT]);\r\n};\r\n\r\n\r\n/**\r\n * Standard supported query parameters.\r\n * @enum {string}\r\n */\r\ngoog.uri.utils.StandardQueryParam = {\r\n\r\n /** Unused parameter for unique-ifying. */\r\n RANDOM: 'zx'\r\n};\r\n\r\n\r\n/**\r\n * Sets the zx parameter of a URI to a random value.\r\n * @param {string} uri Any URI.\r\n * @return {string} That URI with the \"zx\" parameter added or replaced to\r\n * contain a random string.\r\n */\r\ngoog.uri.utils.makeUnique = function(uri) {\r\n return goog.uri.utils.setParam(\r\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\r\n goog.string.getRandomString());\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Class for parsing and formatting URIs.\r\n *\r\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\r\n * create a new instance of the goog.Uri object from Uri parts.\r\n *\r\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\r\n *\r\n * Implements RFC 3986 for parsing/formatting URIs.\r\n * http://www.ietf.org/rfc/rfc3986.txt\r\n *\r\n * Some changes have been made to the interface (more like .NETs), though the\r\n * internal representation is now of un-encoded parts, this will change the\r\n * behavior slightly.\r\n *\r\n * @author msamuel@google.com (Mike Samuel)\r\n */\r\n\r\ngoog.provide('goog.Uri');\r\ngoog.provide('goog.Uri.QueryData');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.string');\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.Map');\r\ngoog.require('goog.uri.utils');\r\ngoog.require('goog.uri.utils.ComponentIndex');\r\ngoog.require('goog.uri.utils.StandardQueryParam');\r\n\r\n\r\n\r\n/**\r\n * This class contains setters and getters for the parts of the URI.\r\n * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part\r\n * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the\r\n * decoded path, <code>/foo bar</code>.\r\n *\r\n * Reserved characters (see RFC 3986 section 2.2) can be present in\r\n * their percent-encoded form in scheme, domain, and path URI components and\r\n * will not be auto-decoded. For example:\r\n * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will\r\n * return <code>relative/path%2fto/resource</code>.\r\n *\r\n * The constructor accepts an optional unparsed, raw URI string. The parser\r\n * is relaxed, so special characters that aren't escaped but don't cause\r\n * ambiguities will not cause parse failures.\r\n *\r\n * All setters return <code>this</code> and so may be chained, a la\r\n * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.\r\n *\r\n * @param {*=} opt_uri Optional string URI to parse\r\n * (use goog.Uri.create() to create a URI from parts), or if\r\n * a goog.Uri is passed, a clone is created.\r\n * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore\r\n * the case of the parameter name.\r\n *\r\n * @throws URIError If opt_uri is provided and URI is malformed (that is,\r\n * if decodeURIComponent fails on any of the URI components).\r\n * @constructor\r\n * @struct\r\n */\r\ngoog.Uri = function(opt_uri, opt_ignoreCase) {\r\n /**\r\n * Scheme such as \"http\".\r\n * @private {string}\r\n */\r\n this.scheme_ = '';\r\n\r\n /**\r\n * User credentials in the form \"username:password\".\r\n * @private {string}\r\n */\r\n this.userInfo_ = '';\r\n\r\n /**\r\n * Domain part, e.g. \"www.google.com\".\r\n * @private {string}\r\n */\r\n this.domain_ = '';\r\n\r\n /**\r\n * Port, e.g. 8080.\r\n * @private {?number}\r\n */\r\n this.port_ = null;\r\n\r\n /**\r\n * Path, e.g. \"/tests/img.png\".\r\n * @private {string}\r\n */\r\n this.path_ = '';\r\n\r\n /**\r\n * The fragment without the #.\r\n * @private {string}\r\n */\r\n this.fragment_ = '';\r\n\r\n /**\r\n * Whether or not this Uri should be treated as Read Only.\r\n * @private {boolean}\r\n */\r\n this.isReadOnly_ = false;\r\n\r\n /**\r\n * Whether or not to ignore case when comparing query params.\r\n * @private {boolean}\r\n */\r\n this.ignoreCase_ = false;\r\n\r\n /**\r\n * Object representing query data.\r\n * @private {!goog.Uri.QueryData}\r\n */\r\n this.queryData_;\r\n\r\n // Parse in the uri string\r\n var m;\r\n if (opt_uri instanceof goog.Uri) {\r\n this.ignoreCase_ =\r\n goog.isDef(opt_ignoreCase) ? opt_ignoreCase : opt_uri.getIgnoreCase();\r\n this.setScheme(opt_uri.getScheme());\r\n this.setUserInfo(opt_uri.getUserInfo());\r\n this.setDomain(opt_uri.getDomain());\r\n this.setPort(opt_uri.getPort());\r\n this.setPath(opt_uri.getPath());\r\n this.setQueryData(opt_uri.getQueryData().clone());\r\n this.setFragment(opt_uri.getFragment());\r\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\r\n this.ignoreCase_ = !!opt_ignoreCase;\r\n\r\n // Set the parts -- decoding as we do so.\r\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\r\n // whereas in other browsers they will be undefined.\r\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\r\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\r\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\r\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\r\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\r\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\r\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\r\n\r\n } else {\r\n this.ignoreCase_ = !!opt_ignoreCase;\r\n this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Parameter name added to stop caching.\r\n * @type {string}\r\n */\r\ngoog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;\r\n\r\n\r\n/**\r\n * @return {string} The string form of the url.\r\n * @override\r\n */\r\ngoog.Uri.prototype.toString = function() {\r\n var out = [];\r\n\r\n var scheme = this.getScheme();\r\n if (scheme) {\r\n out.push(\r\n goog.Uri.encodeSpecialChars_(\r\n scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\r\n ':');\r\n }\r\n\r\n var domain = this.getDomain();\r\n if (domain || scheme == 'file') {\r\n out.push('//');\r\n\r\n var userInfo = this.getUserInfo();\r\n if (userInfo) {\r\n out.push(\r\n goog.Uri.encodeSpecialChars_(\r\n userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\r\n '@');\r\n }\r\n\r\n out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));\r\n\r\n var port = this.getPort();\r\n if (port != null) {\r\n out.push(':', String(port));\r\n }\r\n }\r\n\r\n var path = this.getPath();\r\n if (path) {\r\n if (this.hasDomain() && path.charAt(0) != '/') {\r\n out.push('/');\r\n }\r\n out.push(\r\n goog.Uri.encodeSpecialChars_(\r\n path, path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :\r\n goog.Uri.reDisallowedInRelativePath_,\r\n true));\r\n }\r\n\r\n var query = this.getEncodedQuery();\r\n if (query) {\r\n out.push('?', query);\r\n }\r\n\r\n var fragment = this.getFragment();\r\n if (fragment) {\r\n out.push(\r\n '#', goog.Uri.encodeSpecialChars_(\r\n fragment, goog.Uri.reDisallowedInFragment_));\r\n }\r\n return out.join('');\r\n};\r\n\r\n\r\n/**\r\n * Resolves the given relative URI (a goog.Uri object), using the URI\r\n * represented by this instance as the base URI.\r\n *\r\n * There are several kinds of relative URIs:<br>\r\n * 1. foo - replaces the last part of the path, the whole query and fragment<br>\r\n * 2. /foo - replaces the path, the query and fragment<br>\r\n * 3. //foo - replaces everything from the domain on. foo is a domain name<br>\r\n * 4. ?foo - replace the query and fragment<br>\r\n * 5. #foo - replace the fragment only\r\n *\r\n * Additionally, if relative URI has a non-empty path, all \"..\" and \".\"\r\n * segments will be resolved, as described in RFC 3986.\r\n *\r\n * @param {!goog.Uri} relativeUri The relative URI to resolve.\r\n * @return {!goog.Uri} The resolved URI.\r\n */\r\ngoog.Uri.prototype.resolve = function(relativeUri) {\r\n\r\n var absoluteUri = this.clone();\r\n\r\n // we satisfy these conditions by looking for the first part of relativeUri\r\n // that is not blank and applying defaults to the rest\r\n\r\n var overridden = relativeUri.hasScheme();\r\n\r\n if (overridden) {\r\n absoluteUri.setScheme(relativeUri.getScheme());\r\n } else {\r\n overridden = relativeUri.hasUserInfo();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setUserInfo(relativeUri.getUserInfo());\r\n } else {\r\n overridden = relativeUri.hasDomain();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setDomain(relativeUri.getDomain());\r\n } else {\r\n overridden = relativeUri.hasPort();\r\n }\r\n\r\n var path = relativeUri.getPath();\r\n if (overridden) {\r\n absoluteUri.setPort(relativeUri.getPort());\r\n } else {\r\n overridden = relativeUri.hasPath();\r\n if (overridden) {\r\n // resolve path properly\r\n if (path.charAt(0) != '/') {\r\n // path is relative\r\n if (this.hasDomain() && !this.hasPath()) {\r\n // RFC 3986, section 5.2.3, case 1\r\n path = '/' + path;\r\n } else {\r\n // RFC 3986, section 5.2.3, case 2\r\n var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');\r\n if (lastSlashIndex != -1) {\r\n path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;\r\n }\r\n }\r\n }\r\n path = goog.Uri.removeDotSegments(path);\r\n }\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setPath(path);\r\n } else {\r\n overridden = relativeUri.hasQuery();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setQueryData(relativeUri.getQueryData().clone());\r\n } else {\r\n overridden = relativeUri.hasFragment();\r\n }\r\n\r\n if (overridden) {\r\n absoluteUri.setFragment(relativeUri.getFragment());\r\n }\r\n\r\n return absoluteUri;\r\n};\r\n\r\n\r\n/**\r\n * Clones the URI instance.\r\n * @return {!goog.Uri} New instance of the URI object.\r\n */\r\ngoog.Uri.prototype.clone = function() {\r\n return new goog.Uri(this);\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The encoded scheme/protocol for the URI.\r\n */\r\ngoog.Uri.prototype.getScheme = function() {\r\n return this.scheme_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the scheme/protocol.\r\n * @throws URIError If opt_decode is true and newScheme is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newScheme New scheme value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setScheme = function(newScheme, opt_decode) {\r\n this.enforceReadOnly();\r\n this.scheme_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;\r\n\r\n // remove an : at the end of the scheme so somebody can pass in\r\n // window.location.protocol\r\n if (this.scheme_) {\r\n this.scheme_ = this.scheme_.replace(/:$/, '');\r\n }\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the scheme has been set.\r\n */\r\ngoog.Uri.prototype.hasScheme = function() {\r\n return !!this.scheme_;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded user info.\r\n */\r\ngoog.Uri.prototype.getUserInfo = function() {\r\n return this.userInfo_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the userInfo.\r\n * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newUserInfo New userInfo value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {\r\n this.enforceReadOnly();\r\n this.userInfo_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the user info has been set.\r\n */\r\ngoog.Uri.prototype.hasUserInfo = function() {\r\n return !!this.userInfo_;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded domain.\r\n */\r\ngoog.Uri.prototype.getDomain = function() {\r\n return this.domain_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the domain.\r\n * @throws URIError If opt_decode is true and newDomain is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newDomain New domain value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setDomain = function(newDomain, opt_decode) {\r\n this.enforceReadOnly();\r\n this.domain_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the domain has been set.\r\n */\r\ngoog.Uri.prototype.hasDomain = function() {\r\n return !!this.domain_;\r\n};\r\n\r\n\r\n/**\r\n * @return {?number} The port number.\r\n */\r\ngoog.Uri.prototype.getPort = function() {\r\n return this.port_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the port number.\r\n * @param {*} newPort Port number. Will be explicitly casted to a number.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setPort = function(newPort) {\r\n this.enforceReadOnly();\r\n\r\n if (newPort) {\r\n newPort = Number(newPort);\r\n if (isNaN(newPort) || newPort < 0) {\r\n throw new Error('Bad port number ' + newPort);\r\n }\r\n this.port_ = newPort;\r\n } else {\r\n this.port_ = null;\r\n }\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the port has been set.\r\n */\r\ngoog.Uri.prototype.hasPort = function() {\r\n return this.port_ != null;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded path.\r\n */\r\ngoog.Uri.prototype.getPath = function() {\r\n return this.path_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the path.\r\n * @throws URIError If opt_decode is true and newPath is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newPath New path value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setPath = function(newPath, opt_decode) {\r\n this.enforceReadOnly();\r\n this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the path has been set.\r\n */\r\ngoog.Uri.prototype.hasPath = function() {\r\n return !!this.path_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the query string has been set.\r\n */\r\ngoog.Uri.prototype.hasQuery = function() {\r\n return this.queryData_.toString() !== '';\r\n};\r\n\r\n\r\n/**\r\n * Sets the query data.\r\n * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * Applies only if queryData is a string.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setQueryData = function(queryData, opt_decode) {\r\n this.enforceReadOnly();\r\n\r\n if (queryData instanceof goog.Uri.QueryData) {\r\n this.queryData_ = queryData;\r\n this.queryData_.setIgnoreCase(this.ignoreCase_);\r\n } else {\r\n if (!opt_decode) {\r\n // QueryData accepts encoded query string, so encode it if\r\n // opt_decode flag is not true.\r\n queryData = goog.Uri.encodeSpecialChars_(\r\n queryData, goog.Uri.reDisallowedInQuery_);\r\n }\r\n this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_);\r\n }\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Sets the URI query.\r\n * @param {string} newQuery New query value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setQuery = function(newQuery, opt_decode) {\r\n return this.setQueryData(newQuery, opt_decode);\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The encoded URI query, not including the ?.\r\n */\r\ngoog.Uri.prototype.getEncodedQuery = function() {\r\n return this.queryData_.toString();\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The decoded URI query, not including the ?.\r\n */\r\ngoog.Uri.prototype.getDecodedQuery = function() {\r\n return this.queryData_.toDecodedString();\r\n};\r\n\r\n\r\n/**\r\n * Returns the query data.\r\n * @return {!goog.Uri.QueryData} QueryData object.\r\n */\r\ngoog.Uri.prototype.getQueryData = function() {\r\n return this.queryData_;\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The encoded URI query, not including the ?.\r\n *\r\n * Warning: This method, unlike other getter methods, returns encoded\r\n * value, instead of decoded one.\r\n */\r\ngoog.Uri.prototype.getQuery = function() {\r\n return this.getEncodedQuery();\r\n};\r\n\r\n\r\n/**\r\n * Sets the value of the named query parameters, clearing previous values for\r\n * that key.\r\n *\r\n * @param {string} key The parameter to set.\r\n * @param {*} value The new value. Value does not need to be encoded.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setParameterValue = function(key, value) {\r\n this.enforceReadOnly();\r\n this.queryData_.set(key, value);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Sets the values of the named query parameters, clearing previous values for\r\n * that key. Not new values will currently be moved to the end of the query\r\n * string.\r\n *\r\n * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])\r\n * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>\r\n *\r\n * @param {string} key The parameter to set.\r\n * @param {*} values The new values. If values is a single\r\n * string then it will be treated as the sole value. Values do not need to\r\n * be encoded.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setParameterValues = function(key, values) {\r\n this.enforceReadOnly();\r\n\r\n if (!goog.isArray(values)) {\r\n values = [String(values)];\r\n }\r\n\r\n this.queryData_.setValues(key, values);\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\r\n * query parameter values.\r\n * @param {string} name The parameter to get values for.\r\n * @return {!Array<?>} The values for a given cgi parameter as a list of\r\n * decoded query parameter values.\r\n */\r\ngoog.Uri.prototype.getParameterValues = function(name) {\r\n return this.queryData_.getValues(name);\r\n};\r\n\r\n\r\n/**\r\n * Returns the first value for a given cgi parameter or undefined if the given\r\n * parameter name does not appear in the query string.\r\n * @param {string} paramName Unescaped parameter name.\r\n * @return {string|undefined} The first value for a given cgi parameter or\r\n * undefined if the given parameter name does not appear in the query\r\n * string.\r\n */\r\ngoog.Uri.prototype.getParameterValue = function(paramName) {\r\n return /** @type {string|undefined} */ (this.queryData_.get(paramName));\r\n};\r\n\r\n\r\n/**\r\n * @return {string} The URI fragment, not including the #.\r\n */\r\ngoog.Uri.prototype.getFragment = function() {\r\n return this.fragment_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the URI fragment.\r\n * @throws URIError If opt_decode is true and newFragment is malformed (that is,\r\n * if decodeURIComponent fails).\r\n * @param {string} newFragment New fragment value.\r\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.setFragment = function(newFragment, opt_decode) {\r\n this.enforceReadOnly();\r\n this.fragment_ =\r\n opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the URI has a fragment set.\r\n */\r\ngoog.Uri.prototype.hasFragment = function() {\r\n return !!this.fragment_;\r\n};\r\n\r\n\r\n/**\r\n * Returns true if this has the same domain as that of uri2.\r\n * @param {!goog.Uri} uri2 The URI object to compare to.\r\n * @return {boolean} true if same domain; false otherwise.\r\n */\r\ngoog.Uri.prototype.hasSameDomainAs = function(uri2) {\r\n return ((!this.hasDomain() && !uri2.hasDomain()) ||\r\n this.getDomain() == uri2.getDomain()) &&\r\n ((!this.hasPort() && !uri2.hasPort()) ||\r\n this.getPort() == uri2.getPort());\r\n};\r\n\r\n\r\n/**\r\n * Adds a random parameter to the Uri.\r\n * @return {!goog.Uri} Reference to this Uri object.\r\n */\r\ngoog.Uri.prototype.makeUnique = function() {\r\n this.enforceReadOnly();\r\n this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());\r\n\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Removes the named query parameter.\r\n *\r\n * @param {string} key The parameter to remove.\r\n * @return {!goog.Uri} Reference to this URI object.\r\n */\r\ngoog.Uri.prototype.removeParameter = function(key) {\r\n this.enforceReadOnly();\r\n this.queryData_.remove(key);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether Uri is read only. If this goog.Uri is read-only,\r\n * enforceReadOnly_ will be called at the start of any function that may modify\r\n * this Uri.\r\n * @param {boolean} isReadOnly whether this goog.Uri should be read only.\r\n * @return {!goog.Uri} Reference to this Uri object.\r\n */\r\ngoog.Uri.prototype.setReadOnly = function(isReadOnly) {\r\n this.isReadOnly_ = isReadOnly;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the URI is read only.\r\n */\r\ngoog.Uri.prototype.isReadOnly = function() {\r\n return this.isReadOnly_;\r\n};\r\n\r\n\r\n/**\r\n * Checks if this Uri has been marked as read only, and if so, throws an error.\r\n * This should be called whenever any modifying function is called.\r\n */\r\ngoog.Uri.prototype.enforceReadOnly = function() {\r\n if (this.isReadOnly_) {\r\n throw new Error('Tried to modify a read-only Uri');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Sets whether to ignore case.\r\n * NOTE: If there are already key/value pairs in the QueryData, and\r\n * ignoreCase_ is set to false, the keys will all be lower-cased.\r\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\r\n * @return {!goog.Uri} Reference to this Uri object.\r\n */\r\ngoog.Uri.prototype.setIgnoreCase = function(ignoreCase) {\r\n this.ignoreCase_ = ignoreCase;\r\n if (this.queryData_) {\r\n this.queryData_.setIgnoreCase(ignoreCase);\r\n }\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether to ignore case.\r\n */\r\ngoog.Uri.prototype.getIgnoreCase = function() {\r\n return this.ignoreCase_;\r\n};\r\n\r\n\r\n//==============================================================================\r\n// Static members\r\n//==============================================================================\r\n\r\n\r\n/**\r\n * Creates a uri from the string form. Basically an alias of new goog.Uri().\r\n * If a Uri object is passed to parse then it will return a clone of the object.\r\n *\r\n * @throws URIError If parsing the URI is malformed. The passed URI components\r\n * should all be parseable by decodeURIComponent.\r\n * @param {*} uri Raw URI string or instance of Uri\r\n * object.\r\n * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter\r\n * names in #getParameterValue.\r\n * @return {!goog.Uri} The new URI object.\r\n */\r\ngoog.Uri.parse = function(uri, opt_ignoreCase) {\r\n return uri instanceof goog.Uri ? uri.clone() :\r\n new goog.Uri(uri, opt_ignoreCase);\r\n};\r\n\r\n\r\n/**\r\n * Creates a new goog.Uri object from unencoded parts.\r\n *\r\n * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.\r\n * @param {?string=} opt_userInfo username:password.\r\n * @param {?string=} opt_domain www.google.com.\r\n * @param {?number=} opt_port 9830.\r\n * @param {?string=} opt_path /some/path/to/a/file.html.\r\n * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.\r\n * @param {?string=} opt_fragment The fragment without the #.\r\n * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in\r\n * #getParameterValue.\r\n *\r\n * @return {!goog.Uri} The new URI object.\r\n */\r\ngoog.Uri.create = function(\r\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,\r\n opt_fragment, opt_ignoreCase) {\r\n\r\n var uri = new goog.Uri(null, opt_ignoreCase);\r\n\r\n // Only set the parts if they are defined and not empty strings.\r\n opt_scheme && uri.setScheme(opt_scheme);\r\n opt_userInfo && uri.setUserInfo(opt_userInfo);\r\n opt_domain && uri.setDomain(opt_domain);\r\n opt_port && uri.setPort(opt_port);\r\n opt_path && uri.setPath(opt_path);\r\n opt_query && uri.setQueryData(opt_query);\r\n opt_fragment && uri.setFragment(opt_fragment);\r\n\r\n return uri;\r\n};\r\n\r\n\r\n/**\r\n * Resolves a relative Uri against a base Uri, accepting both strings and\r\n * Uri objects.\r\n *\r\n * @param {*} base Base Uri.\r\n * @param {*} rel Relative Uri.\r\n * @return {!goog.Uri} Resolved uri.\r\n */\r\ngoog.Uri.resolve = function(base, rel) {\r\n if (!(base instanceof goog.Uri)) {\r\n base = goog.Uri.parse(base);\r\n }\r\n\r\n if (!(rel instanceof goog.Uri)) {\r\n rel = goog.Uri.parse(rel);\r\n }\r\n\r\n return base.resolve(rel);\r\n};\r\n\r\n\r\n/**\r\n * Removes dot segments in given path component, as described in\r\n * RFC 3986, section 5.2.4.\r\n *\r\n * @param {string} path A non-empty path component.\r\n * @return {string} Path component with removed dot segments.\r\n */\r\ngoog.Uri.removeDotSegments = function(path) {\r\n if (path == '..' || path == '.') {\r\n return '';\r\n\r\n } else if (\r\n !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {\r\n // This optimization detects uris which do not contain dot-segments,\r\n // and as a consequence do not require any processing.\r\n return path;\r\n\r\n } else {\r\n var leadingSlash = goog.string.startsWith(path, '/');\r\n var segments = path.split('/');\r\n var out = [];\r\n\r\n for (var pos = 0; pos < segments.length;) {\r\n var segment = segments[pos++];\r\n\r\n if (segment == '.') {\r\n if (leadingSlash && pos == segments.length) {\r\n out.push('');\r\n }\r\n } else if (segment == '..') {\r\n if (out.length > 1 || out.length == 1 && out[0] != '') {\r\n out.pop();\r\n }\r\n if (leadingSlash && pos == segments.length) {\r\n out.push('');\r\n }\r\n } else {\r\n out.push(segment);\r\n leadingSlash = true;\r\n }\r\n }\r\n\r\n return out.join('/');\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Decodes a value or returns the empty string if it isn't defined or empty.\r\n * @throws URIError If decodeURIComponent fails to decode val.\r\n * @param {string|undefined} val Value to decode.\r\n * @param {boolean=} opt_preserveReserved If true, restricted characters will\r\n * not be decoded.\r\n * @return {string} Decoded value.\r\n * @private\r\n */\r\ngoog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {\r\n // Don't use UrlDecode() here because val is not a query parameter.\r\n if (!val) {\r\n return '';\r\n }\r\n\r\n // decodeURI has the same output for '%2f' and '%252f'. We double encode %25\r\n // so that we can distinguish between the 2 inputs. This is later undone by\r\n // removeDoubleEncoding_.\r\n return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :\r\n decodeURIComponent(val);\r\n};\r\n\r\n\r\n/**\r\n * If unescapedPart is non null, then escapes any characters in it that aren't\r\n * valid characters in a url and also escapes any special characters that\r\n * appear in extra.\r\n *\r\n * @param {*} unescapedPart The string to encode.\r\n * @param {RegExp} extra A character set of characters in [\\01-\\177].\r\n * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent\r\n * encoding.\r\n * @return {?string} null iff unescapedPart == null.\r\n * @private\r\n */\r\ngoog.Uri.encodeSpecialChars_ = function(\r\n unescapedPart, extra, opt_removeDoubleEncoding) {\r\n if (goog.isString(unescapedPart)) {\r\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\r\n if (opt_removeDoubleEncoding) {\r\n // encodeURI double-escapes %XX sequences used to represent restricted\r\n // characters in some URI components, remove the double escaping here.\r\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\r\n }\r\n return encoded;\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\r\n * @param {string} ch One character string.\r\n * @return {string} Encoded string.\r\n * @private\r\n */\r\ngoog.Uri.encodeChar_ = function(ch) {\r\n var n = ch.charCodeAt(0);\r\n return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);\r\n};\r\n\r\n\r\n/**\r\n * Removes double percent-encoding from a string.\r\n * @param {string} doubleEncodedString String\r\n * @return {string} String with double encoding removed.\r\n * @private\r\n */\r\ngoog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {\r\n return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');\r\n};\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in the scheme or\r\n * userInfo part of the URI.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\\/\\?@]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in a relative path.\r\n * Colon is included due to RFC 3986 3.3.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInRelativePath_ = /[\\#\\?:]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in an absolute path.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInAbsolutePath_ = /[\\#\\?]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in the query.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInQuery_ = /[\\#\\?@]/g;\r\n\r\n\r\n/**\r\n * Regular expression for characters that are disallowed in the fragment.\r\n * @type {RegExp}\r\n * @private\r\n */\r\ngoog.Uri.reDisallowedInFragment_ = /#/g;\r\n\r\n\r\n/**\r\n * Checks whether two URIs have the same domain.\r\n * @param {string} uri1String First URI string.\r\n * @param {string} uri2String Second URI string.\r\n * @return {boolean} true if the two URIs have the same domain; false otherwise.\r\n */\r\ngoog.Uri.haveSameDomain = function(uri1String, uri2String) {\r\n // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.\r\n // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.\r\n var pieces1 = goog.uri.utils.split(uri1String);\r\n var pieces2 = goog.uri.utils.split(uri2String);\r\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\r\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\r\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\r\n pieces2[goog.uri.utils.ComponentIndex.PORT];\r\n};\r\n\r\n\r\n\r\n/**\r\n * Class used to represent URI query parameters. It is essentially a hash of\r\n * name-value pairs, though a name can be present more than once.\r\n *\r\n * Has the same interface as the collections in goog.structs.\r\n *\r\n * @param {?string=} opt_query Optional encoded query string to parse into\r\n * the object.\r\n * @param {goog.Uri=} opt_uri Optional uri object that should have its\r\n * cache invalidated when this object updates. Deprecated -- this\r\n * is no longer required.\r\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\r\n * name in #get.\r\n * @constructor\r\n * @struct\r\n * @final\r\n */\r\ngoog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) {\r\n /**\r\n * The map containing name/value or name/array-of-values pairs.\r\n * May be null if it requires parsing from the query string.\r\n *\r\n * We need to use a Map because we cannot guarantee that the key names will\r\n * not be problematic for IE.\r\n *\r\n * @private {?goog.structs.Map<string, !Array<*>>}\r\n */\r\n this.keyMap_ = null;\r\n\r\n /**\r\n * The number of params, or null if it requires computing.\r\n * @private {?number}\r\n */\r\n this.count_ = null;\r\n\r\n /**\r\n * Encoded query string, or null if it requires computing from the key map.\r\n * @private {?string}\r\n */\r\n this.encodedQuery_ = opt_query || null;\r\n\r\n /**\r\n * If true, ignore the case of the parameter name in #get.\r\n * @private {boolean}\r\n */\r\n this.ignoreCase_ = !!opt_ignoreCase;\r\n};\r\n\r\n\r\n/**\r\n * If the underlying key map is not yet initialized, it parses the\r\n * query string and fills the map with parsed data.\r\n * @private\r\n */\r\ngoog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {\r\n if (!this.keyMap_) {\r\n this.keyMap_ = new goog.structs.Map();\r\n this.count_ = 0;\r\n if (this.encodedQuery_) {\r\n var self = this;\r\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\r\n self.add(goog.string.urlDecode(name), value);\r\n });\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Creates a new query data instance from a map of names and values.\r\n *\r\n * @param {!goog.structs.Map<string, ?>|!Object} map Map of string parameter\r\n * names to parameter value. If parameter value is an array, it is\r\n * treated as if the key maps to each individual value in the\r\n * array.\r\n * @param {goog.Uri=} opt_uri URI object that should have its cache\r\n * invalidated when this object updates.\r\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\r\n * name in #get.\r\n * @return {!goog.Uri.QueryData} The populated query data instance.\r\n */\r\ngoog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) {\r\n var keys = goog.structs.getKeys(map);\r\n if (typeof keys == 'undefined') {\r\n throw new Error('Keys are undefined');\r\n }\r\n\r\n var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);\r\n var values = goog.structs.getValues(map);\r\n for (var i = 0; i < keys.length; i++) {\r\n var key = keys[i];\r\n var value = values[i];\r\n if (!goog.isArray(value)) {\r\n queryData.add(key, value);\r\n } else {\r\n queryData.setValues(key, value);\r\n }\r\n }\r\n return queryData;\r\n};\r\n\r\n\r\n/**\r\n * Creates a new query data instance from parallel arrays of parameter names\r\n * and values. Allows for duplicate parameter names. Throws an error if the\r\n * lengths of the arrays differ.\r\n *\r\n * @param {!Array<string>} keys Parameter names.\r\n * @param {!Array<?>} values Parameter values.\r\n * @param {goog.Uri=} opt_uri URI object that should have its cache\r\n * invalidated when this object updates.\r\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\r\n * name in #get.\r\n * @return {!goog.Uri.QueryData} The populated query data instance.\r\n */\r\ngoog.Uri.QueryData.createFromKeysValues = function(\r\n keys, values, opt_uri, opt_ignoreCase) {\r\n if (keys.length != values.length) {\r\n throw new Error('Mismatched lengths for keys/values');\r\n }\r\n var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase);\r\n for (var i = 0; i < keys.length; i++) {\r\n queryData.add(keys[i], values[i]);\r\n }\r\n return queryData;\r\n};\r\n\r\n\r\n/**\r\n * @return {?number} The number of parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.getCount = function() {\r\n this.ensureKeyMapInitialized_();\r\n return this.count_;\r\n};\r\n\r\n\r\n/**\r\n * Adds a key value pair.\r\n * @param {string} key Name.\r\n * @param {*} value Value.\r\n * @return {!goog.Uri.QueryData} Instance of this object.\r\n */\r\ngoog.Uri.QueryData.prototype.add = function(key, value) {\r\n this.ensureKeyMapInitialized_();\r\n this.invalidateCache_();\r\n\r\n key = this.getKeyName_(key);\r\n var values = this.keyMap_.get(key);\r\n if (!values) {\r\n this.keyMap_.set(key, (values = []));\r\n }\r\n values.push(value);\r\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Removes all the params with the given key.\r\n * @param {string} key Name.\r\n * @return {boolean} Whether any parameter was removed.\r\n */\r\ngoog.Uri.QueryData.prototype.remove = function(key) {\r\n this.ensureKeyMapInitialized_();\r\n\r\n key = this.getKeyName_(key);\r\n if (this.keyMap_.containsKey(key)) {\r\n this.invalidateCache_();\r\n\r\n // Decrement parameter count.\r\n this.count_ =\r\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\r\n return this.keyMap_.remove(key);\r\n }\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Clears the parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.clear = function() {\r\n this.invalidateCache_();\r\n this.keyMap_ = null;\r\n this.count_ = 0;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether we have any parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.isEmpty = function() {\r\n this.ensureKeyMapInitialized_();\r\n return this.count_ == 0;\r\n};\r\n\r\n\r\n/**\r\n * Whether there is a parameter with the given name\r\n * @param {string} key The parameter name to check for.\r\n * @return {boolean} Whether there is a parameter with the given name.\r\n */\r\ngoog.Uri.QueryData.prototype.containsKey = function(key) {\r\n this.ensureKeyMapInitialized_();\r\n key = this.getKeyName_(key);\r\n return this.keyMap_.containsKey(key);\r\n};\r\n\r\n\r\n/**\r\n * Whether there is a parameter with the given value.\r\n * @param {*} value The value to check for.\r\n * @return {boolean} Whether there is a parameter with the given value.\r\n */\r\ngoog.Uri.QueryData.prototype.containsValue = function(value) {\r\n // NOTE(arv): This solution goes through all the params even if it was the\r\n // first param. We can get around this by not reusing code or by switching to\r\n // iterators.\r\n var vals = this.getValues();\r\n return goog.array.contains(vals, value);\r\n};\r\n\r\n\r\n/**\r\n * Runs a callback on every key-value pair in the map, including duplicate keys.\r\n * This won't maintain original order when duplicate keys are interspersed (like\r\n * getKeys() / getValues()).\r\n * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f\r\n * @param {SCOPE=} opt_scope The value of \"this\" inside f.\r\n * @template SCOPE\r\n */\r\ngoog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {\r\n this.ensureKeyMapInitialized_();\r\n this.keyMap_.forEach(function(values, key) {\r\n goog.array.forEach(values, function(value) {\r\n f.call(opt_scope, value, key, this);\r\n }, this);\r\n }, this);\r\n};\r\n\r\n\r\n/**\r\n * Returns all the keys of the parameters. If a key is used multiple times\r\n * it will be included multiple times in the returned array\r\n * @return {!Array<string>} All the keys of the parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.getKeys = function() {\r\n this.ensureKeyMapInitialized_();\r\n // We need to get the values to know how many keys to add.\r\n var vals = this.keyMap_.getValues();\r\n var keys = this.keyMap_.getKeys();\r\n var rv = [];\r\n for (var i = 0; i < keys.length; i++) {\r\n var val = vals[i];\r\n for (var j = 0; j < val.length; j++) {\r\n rv.push(keys[i]);\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Returns all the values of the parameters with the given name. If the query\r\n * data has no such key this will return an empty array. If no key is given\r\n * all values wil be returned.\r\n * @param {string=} opt_key The name of the parameter to get the values for.\r\n * @return {!Array<?>} All the values of the parameters with the given name.\r\n */\r\ngoog.Uri.QueryData.prototype.getValues = function(opt_key) {\r\n this.ensureKeyMapInitialized_();\r\n var rv = [];\r\n if (goog.isString(opt_key)) {\r\n if (this.containsKey(opt_key)) {\r\n rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key)));\r\n }\r\n } else {\r\n // Return all values.\r\n var values = this.keyMap_.getValues();\r\n for (var i = 0; i < values.length; i++) {\r\n rv = goog.array.concat(rv, values[i]);\r\n }\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Sets a key value pair and removes all other keys with the same value.\r\n *\r\n * @param {string} key Name.\r\n * @param {*} value Value.\r\n * @return {!goog.Uri.QueryData} Instance of this object.\r\n */\r\ngoog.Uri.QueryData.prototype.set = function(key, value) {\r\n this.ensureKeyMapInitialized_();\r\n this.invalidateCache_();\r\n\r\n // TODO(chrishenry): This could be better written as\r\n // this.remove(key), this.add(key, value), but that would reorder\r\n // the key (since the key is first removed and then added at the\r\n // end) and we would have to fix unit tests that depend on key\r\n // ordering.\r\n key = this.getKeyName_(key);\r\n if (this.containsKey(key)) {\r\n this.count_ =\r\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\r\n }\r\n this.keyMap_.set(key, [value]);\r\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Returns the first value associated with the key. If the query data has no\r\n * such key this will return undefined or the optional default.\r\n * @param {string} key The name of the parameter to get the value for.\r\n * @param {*=} opt_default The default value to return if the query data\r\n * has no such key.\r\n * @return {*} The first string value associated with the key, or opt_default\r\n * if there's no value.\r\n */\r\ngoog.Uri.QueryData.prototype.get = function(key, opt_default) {\r\n if (!key) {\r\n return opt_default;\r\n }\r\n var values = this.getValues(key);\r\n return values.length > 0 ? String(values[0]) : opt_default;\r\n};\r\n\r\n\r\n/**\r\n * Sets the values for a key. If the key already exists, this will\r\n * override all of the existing values that correspond to the key.\r\n * @param {string} key The key to set values for.\r\n * @param {!Array<?>} values The values to set.\r\n */\r\ngoog.Uri.QueryData.prototype.setValues = function(key, values) {\r\n this.remove(key);\r\n\r\n if (values.length > 0) {\r\n this.invalidateCache_();\r\n this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));\r\n this.count_ = goog.asserts.assertNumber(this.count_) + values.length;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {string} Encoded query string.\r\n * @override\r\n */\r\ngoog.Uri.QueryData.prototype.toString = function() {\r\n if (this.encodedQuery_) {\r\n return this.encodedQuery_;\r\n }\r\n\r\n if (!this.keyMap_) {\r\n return '';\r\n }\r\n\r\n var sb = [];\r\n\r\n // In the past, we use this.getKeys() and this.getVals(), but that\r\n // generates a lot of allocations as compared to simply iterating\r\n // over the keys.\r\n var keys = this.keyMap_.getKeys();\r\n for (var i = 0; i < keys.length; i++) {\r\n var key = keys[i];\r\n var encodedKey = goog.string.urlEncode(key);\r\n var val = this.getValues(key);\r\n for (var j = 0; j < val.length; j++) {\r\n var param = encodedKey;\r\n // Ensure that null and undefined are encoded into the url as\r\n // literal strings.\r\n if (val[j] !== '') {\r\n param += '=' + goog.string.urlEncode(val[j]);\r\n }\r\n sb.push(param);\r\n }\r\n }\r\n\r\n return this.encodedQuery_ = sb.join('&');\r\n};\r\n\r\n\r\n/**\r\n * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on\r\n * any of the URI components).\r\n * @return {string} Decoded query string.\r\n */\r\ngoog.Uri.QueryData.prototype.toDecodedString = function() {\r\n return goog.Uri.decodeOrEmpty_(this.toString());\r\n};\r\n\r\n\r\n/**\r\n * Invalidate the cache.\r\n * @private\r\n */\r\ngoog.Uri.QueryData.prototype.invalidateCache_ = function() {\r\n this.encodedQuery_ = null;\r\n};\r\n\r\n\r\n/**\r\n * Removes all keys that are not in the provided list. (Modifies this object.)\r\n * @param {Array<string>} keys The desired keys.\r\n * @return {!goog.Uri.QueryData} a reference to this object.\r\n */\r\ngoog.Uri.QueryData.prototype.filterKeys = function(keys) {\r\n this.ensureKeyMapInitialized_();\r\n this.keyMap_.forEach(function(value, key) {\r\n if (!goog.array.contains(keys, key)) {\r\n this.remove(key);\r\n }\r\n }, this);\r\n return this;\r\n};\r\n\r\n\r\n/**\r\n * Clone the query data instance.\r\n * @return {!goog.Uri.QueryData} New instance of the QueryData object.\r\n */\r\ngoog.Uri.QueryData.prototype.clone = function() {\r\n var rv = new goog.Uri.QueryData();\r\n rv.encodedQuery_ = this.encodedQuery_;\r\n if (this.keyMap_) {\r\n rv.keyMap_ = this.keyMap_.clone();\r\n rv.count_ = this.count_;\r\n }\r\n return rv;\r\n};\r\n\r\n\r\n/**\r\n * Helper function to get the key name from a JavaScript object. Converts\r\n * the object to a string, and to lower case if necessary.\r\n * @private\r\n * @param {*} arg The object to get a key name from.\r\n * @return {string} valid key name which can be looked up in #keyMap_.\r\n */\r\ngoog.Uri.QueryData.prototype.getKeyName_ = function(arg) {\r\n var keyName = String(arg);\r\n if (this.ignoreCase_) {\r\n keyName = keyName.toLowerCase();\r\n }\r\n return keyName;\r\n};\r\n\r\n\r\n/**\r\n * Ignore case in parameter names.\r\n * NOTE: If there are already key/value pairs in the QueryData, and\r\n * ignoreCase_ is set to false, the keys will all be lower-cased.\r\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\r\n */\r\ngoog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {\r\n var resetKeys = ignoreCase && !this.ignoreCase_;\r\n if (resetKeys) {\r\n this.ensureKeyMapInitialized_();\r\n this.invalidateCache_();\r\n this.keyMap_.forEach(function(value, key) {\r\n var lowerCase = key.toLowerCase();\r\n if (key != lowerCase) {\r\n this.remove(key);\r\n this.setValues(lowerCase, value);\r\n }\r\n }, this);\r\n }\r\n this.ignoreCase_ = ignoreCase;\r\n};\r\n\r\n\r\n/**\r\n * Extends a query data object with another query data or map like object. This\r\n * operates 'in-place', it does not create a new QueryData object.\r\n *\r\n * @param {...(?goog.Uri.QueryData|?goog.structs.Map<?, ?>|?Object)} var_args\r\n * The object from which key value pairs will be copied. Note: does not\r\n * accept null.\r\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\r\n * types of parameters.\r\n */\r\ngoog.Uri.QueryData.prototype.extend = function(var_args) {\r\n for (var i = 0; i < arguments.length; i++) {\r\n var data = arguments[i];\r\n goog.structs.forEach(\r\n data, function(value, key) { this.add(key, value); }, this);\r\n }\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Base TestChannel implementation.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.BaseTestChannel');\r\n\r\ngoog.require('goog.labs.net.webChannel.Channel');\r\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\ngoog.require('goog.labs.net.webChannel.requestStats');\r\ngoog.require('goog.net.WebChannel');\r\n\r\ngoog.forwardDeclare('goog.labs.net.webChannel.WebChannelBase');\r\n\r\n\r\n\r\n/**\r\n * A TestChannel is used during the first part of channel negotiation\r\n * with the server to create the channel. It helps us determine whether we're\r\n * behind a buffering proxy.\r\n *\r\n * @constructor\r\n * @struct\r\n * @param {!goog.labs.net.webChannel.Channel} channel The channel\r\n * that owns this test channel.\r\n * @param {!goog.labs.net.webChannel.WebChannelDebug} channelDebug A\r\n * WebChannelDebug instance to use for logging.\r\n * @implements {goog.labs.net.webChannel.Channel}\r\n */\r\ngoog.labs.net.webChannel.BaseTestChannel = function(channel, channelDebug) {\r\n /**\r\n * The channel that owns this test channel\r\n * @private {!goog.labs.net.webChannel.Channel}\r\n */\r\n this.channel_ = channel;\r\n\r\n /**\r\n * The channel debug to use for logging\r\n * @private {!goog.labs.net.webChannel.WebChannelDebug}\r\n */\r\n this.channelDebug_ = channelDebug;\r\n\r\n /**\r\n * Extra HTTP headers to add to all the requests sent to the server.\r\n * @private {Object}\r\n */\r\n this.extraHeaders_ = null;\r\n\r\n /**\r\n * The test request.\r\n * @private {goog.labs.net.webChannel.ChannelRequest}\r\n */\r\n this.request_ = null;\r\n\r\n /**\r\n * Whether we have received the first result as an intermediate result. This\r\n * helps us determine whether we're behind a buffering proxy.\r\n * @private {boolean}\r\n */\r\n this.receivedIntermediateResult_ = false;\r\n\r\n /**\r\n * The relative path for test requests.\r\n * @private {?string}\r\n */\r\n this.path_ = null;\r\n\r\n /**\r\n * The last status code received.\r\n * @private {number}\r\n */\r\n this.lastStatusCode_ = -1;\r\n\r\n /**\r\n * A subdomain prefix for using a subdomain in IE for the backchannel\r\n * requests.\r\n * @private {?string}\r\n */\r\n this.hostPrefix_ = null;\r\n\r\n /**\r\n * The effective client protocol as indicated by the initial handshake\r\n * response via the x-client-wire-protocol header.\r\n *\r\n * @private {?string}\r\n */\r\n this.clientProtocol_ = null;\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannel = goog.net.WebChannel;\r\nvar BaseTestChannel = goog.labs.net.webChannel.BaseTestChannel;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\nvar ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\r\nvar requestStats = goog.labs.net.webChannel.requestStats;\r\nvar Channel = goog.labs.net.webChannel.Channel;\r\n\r\n\r\n/**\r\n * Enum type for the test channel state machine\r\n * @enum {number}\r\n * @private\r\n */\r\nBaseTestChannel.State_ = {\r\n /**\r\n * The state for the TestChannel state machine where we making the\r\n * initial call to get the server configured parameters.\r\n */\r\n INIT: 0,\r\n\r\n /**\r\n * The state for the TestChannel state machine where we're checking to\r\n * se if we're behind a buffering proxy.\r\n */\r\n CONNECTION_TESTING: 1\r\n};\r\n\r\n\r\n/**\r\n * The state of the state machine for this object.\r\n *\r\n * @private {?BaseTestChannel.State_}\r\n */\r\nBaseTestChannel.prototype.state_ = null;\r\n\r\n\r\n/**\r\n * Sets extra HTTP headers to add to all the requests sent to the server.\r\n *\r\n * @param {Object} extraHeaders The HTTP headers.\r\n */\r\nBaseTestChannel.prototype.setExtraHeaders = function(extraHeaders) {\r\n this.extraHeaders_ = extraHeaders;\r\n};\r\n\r\n\r\n/**\r\n * Starts the test channel. This initiates connections to the server.\r\n *\r\n * @param {string} path The relative uri for the test connection.\r\n */\r\nBaseTestChannel.prototype.connect = function(path) {\r\n this.path_ = path;\r\n var sendDataUri = this.channel_.getForwardChannelUri(this.path_);\r\n\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_ONE_START);\r\n\r\n // If the channel already has the result of the handshake, then skip it.\r\n var handshakeResult = this.channel_.getConnectionState().handshakeResult;\r\n if (goog.isDefAndNotNull(handshakeResult)) {\r\n this.hostPrefix_ = this.channel_.correctHostPrefix(handshakeResult[0]);\r\n this.state_ = BaseTestChannel.State_.CONNECTION_TESTING;\r\n this.checkBufferingProxy_();\r\n return;\r\n }\r\n\r\n // the first request returns server specific parameters\r\n sendDataUri.setParameterValues('MODE', 'init');\r\n\r\n // http-session-id to be generated as the response\r\n if (!this.channel_.getBackgroundChannelTest() &&\r\n this.channel_.getHttpSessionIdParam()) {\r\n sendDataUri.setParameterValues(WebChannel.X_HTTP_SESSION_ID,\r\n this.channel_.getHttpSessionIdParam());\r\n }\r\n\r\n this.request_ = ChannelRequest.createChannelRequest(this, this.channelDebug_);\r\n\r\n this.request_.setExtraHeaders(this.extraHeaders_);\r\n\r\n this.request_.xmlHttpGet(\r\n sendDataUri, false /* decodeChunks */, null /* hostPrefix */);\r\n this.state_ = BaseTestChannel.State_.INIT;\r\n};\r\n\r\n\r\n/**\r\n * Begins the second stage of the test channel where we test to see if we're\r\n * behind a buffering proxy. The server sends back a multi-chunked response\r\n * with the first chunk containing the content '1' and then two seconds later\r\n * sending the second chunk containing the content '2'. Depending on how we\r\n * receive the content, we can tell if we're behind a buffering proxy.\r\n * @private\r\n */\r\nBaseTestChannel.prototype.checkBufferingProxy_ = function() {\r\n this.channelDebug_.debug('TestConnection: starting stage 2');\r\n\r\n // If the test result is already available, skip its execution.\r\n var bufferingProxyResult =\r\n this.channel_.getConnectionState().bufferingProxyResult;\r\n if (goog.isDefAndNotNull(bufferingProxyResult)) {\r\n this.channelDebug_.debug(function() {\r\n return 'TestConnection: skipping stage 2, precomputed result is ' +\r\n bufferingProxyResult ?\r\n 'Buffered' :\r\n 'Unbuffered';\r\n });\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_START);\r\n if (bufferingProxyResult) { // Buffered/Proxy connection\r\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\r\n this.channel_.testConnectionFinished(this, false);\r\n } else { // Unbuffered/NoProxy connection\r\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\r\n this.channel_.testConnectionFinished(this, true);\r\n }\r\n return; // Skip the test\r\n }\r\n this.request_ = ChannelRequest.createChannelRequest(this, this.channelDebug_);\r\n this.request_.setExtraHeaders(this.extraHeaders_);\r\n var recvDataUri = this.channel_.getBackChannelUri(\r\n this.hostPrefix_,\r\n /** @type {string} */ (this.path_));\r\n\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_START);\r\n recvDataUri.setParameterValues('TYPE', 'xmlhttp');\r\n\r\n var param = this.channel_.getHttpSessionIdParam();\r\n var value = this.channel_.getHttpSessionId();\r\n if (param && value) {\r\n recvDataUri.setParameterValue(param, value);\r\n }\r\n\r\n this.request_.xmlHttpGet(\r\n recvDataUri, false /** decodeChunks */, this.hostPrefix_);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.createXhrIo = function(hostPrefix) {\r\n return this.channel_.createXhrIo(hostPrefix);\r\n};\r\n\r\n\r\n/**\r\n * Aborts the test channel.\r\n */\r\nBaseTestChannel.prototype.abort = function() {\r\n if (this.request_) {\r\n this.request_.cancel();\r\n this.request_ = null;\r\n }\r\n this.lastStatusCode_ = -1;\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the test channel is closed. The ChannelRequest object expects\r\n * this method to be implemented on its handler.\r\n *\r\n * @return {boolean} Whether the channel is closed.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.isClosed = function() {\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Callback from ChannelRequest for when new data is received\r\n *\r\n * @param {ChannelRequest} req The request object.\r\n * @param {string} responseText The text of the response.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.onRequestData = function(req, responseText) {\r\n this.lastStatusCode_ = req.getLastStatusCode();\r\n if (this.state_ == BaseTestChannel.State_.INIT) {\r\n this.channelDebug_.debug('TestConnection: Got data for stage 1');\r\n\r\n this.applyControlHeaders_(req);\r\n\r\n if (!responseText) {\r\n this.channelDebug_.debug('TestConnection: Null responseText');\r\n // The server should always send text; something is wrong here\r\n this.channel_.testConnectionFailure(this, ChannelRequest.Error.BAD_DATA);\r\n return;\r\n }\r\n\r\n\r\n try {\r\n var channel = /** @type {!goog.labs.net.webChannel.WebChannelBase} */ (\r\n this.channel_);\r\n var respArray = channel.getWireCodec().decodeMessage(responseText);\r\n } catch (e) {\r\n this.channelDebug_.dumpException(e);\r\n this.channel_.testConnectionFailure(this, ChannelRequest.Error.BAD_DATA);\r\n return;\r\n }\r\n this.hostPrefix_ = this.channel_.correctHostPrefix(respArray[0]);\r\n } else if (this.state_ == BaseTestChannel.State_.CONNECTION_TESTING) {\r\n if (this.receivedIntermediateResult_) {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_DATA_TWO);\r\n } else {\r\n // '11111' is used instead of '1' to prevent a small amount of buffering\r\n // by Safari.\r\n if (responseText == '11111') {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_DATA_ONE);\r\n this.receivedIntermediateResult_ = true;\r\n if (this.checkForEarlyNonBuffered_()) {\r\n // If early chunk detection is on, and we passed the tests,\r\n // assume HTTP_OK, cancel the test and turn on noproxy mode.\r\n this.lastStatusCode_ = 200;\r\n this.request_.cancel();\r\n this.channelDebug_.debug(\r\n 'Test connection succeeded; using streaming connection');\r\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\r\n this.channel_.testConnectionFinished(this, true);\r\n }\r\n } else {\r\n requestStats.notifyStatEvent(\r\n requestStats.Stat.TEST_STAGE_TWO_DATA_BOTH);\r\n this.receivedIntermediateResult_ = false;\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Callback from ChannelRequest that indicates a request has completed.\r\n *\r\n * @param {!ChannelRequest} req The request object.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.onRequestComplete = function(req) {\r\n this.lastStatusCode_ = this.request_.getLastStatusCode();\r\n if (!this.request_.getSuccess()) {\r\n this.channelDebug_.debug(\r\n 'TestConnection: request failed, in state ' + this.state_);\r\n if (this.state_ == BaseTestChannel.State_.INIT) {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_ONE_FAILED);\r\n } else if (this.state_ == BaseTestChannel.State_.CONNECTION_TESTING) {\r\n requestStats.notifyStatEvent(requestStats.Stat.TEST_STAGE_TWO_FAILED);\r\n }\r\n this.channel_.testConnectionFailure(\r\n this,\r\n /** @type {ChannelRequest.Error} */\r\n (this.request_.getLastError()));\r\n return;\r\n }\r\n\r\n if (this.state_ == BaseTestChannel.State_.INIT) {\r\n this.state_ = BaseTestChannel.State_.CONNECTION_TESTING;\r\n\r\n this.channelDebug_.debug(\r\n 'TestConnection: request complete for initial check');\r\n\r\n this.checkBufferingProxy_();\r\n } else if (this.state_ == BaseTestChannel.State_.CONNECTION_TESTING) {\r\n this.channelDebug_.debug('TestConnection: request complete for stage 2');\r\n\r\n var goodConn = this.receivedIntermediateResult_;\r\n if (goodConn) {\r\n this.channelDebug_.debug(\r\n 'Test connection succeeded; using streaming connection');\r\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\r\n this.channel_.testConnectionFinished(this, true);\r\n } else {\r\n this.channelDebug_.debug('Test connection failed; not using streaming');\r\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\r\n this.channel_.testConnectionFinished(this, false);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Apply any control headers from the initial handshake response.\r\n *\r\n * @param {!ChannelRequest} req The request object.\r\n * @private\r\n */\r\nBaseTestChannel.prototype.applyControlHeaders_ = function(req) {\r\n if (this.channel_.getBackgroundChannelTest()) {\r\n return;\r\n }\r\n\r\n var xhr = req.getXhr();\r\n if (xhr) {\r\n var protocolHeader = xhr.getStreamingResponseHeader(\r\n WebChannel.X_CLIENT_WIRE_PROTOCOL);\r\n this.clientProtocol_ = protocolHeader ? protocolHeader : null;\r\n\r\n if (this.channel_.getHttpSessionIdParam()) {\r\n var httpSessionIdHeader = xhr.getStreamingResponseHeader(\r\n WebChannel.X_HTTP_SESSION_ID);\r\n if (httpSessionIdHeader) {\r\n this.channel_.setHttpSessionId(httpSessionIdHeader);\r\n } else {\r\n this.channelDebug_.warning(\r\n 'Missing X_HTTP_SESSION_ID in the handshake response');\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {?string} The client protocol as recorded with the init handshake\r\n * request.\r\n */\r\nBaseTestChannel.prototype.getClientProtocol = function() {\r\n return this.clientProtocol_;\r\n};\r\n\r\n\r\n/**\r\n * Returns the last status code received for a request.\r\n * @return {number} The last status code received for a request.\r\n */\r\nBaseTestChannel.prototype.getLastStatusCode = function() {\r\n return this.lastStatusCode_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether we should be using secondary domains when the\r\n * server instructs us to do so.\r\n * @override\r\n */\r\nBaseTestChannel.prototype.shouldUseSecondaryDomains = function() {\r\n return this.channel_.shouldUseSecondaryDomains();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.isActive = function() {\r\n return this.channel_.isActive();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} True if test stage 2 detected a non-buffered\r\n * channel early and early no buffering detection is enabled.\r\n * @private\r\n */\r\nBaseTestChannel.prototype.checkForEarlyNonBuffered_ = function() {\r\n return ChannelRequest.supportsXhrStreaming();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getForwardChannelUri = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getBackChannelUri = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.correctHostPrefix = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.createDataUri = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.testConnectionFinished = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.testConnectionFailure = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getConnectionState = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.setHttpSessionIdParam = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getHttpSessionIdParam = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.setHttpSessionId = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getHttpSessionId = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nBaseTestChannel.prototype.getBackgroundChannelTest = goog.abstractMethod;\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview This class manages the network connectivity state.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.ConnectionState');\r\n\r\n\r\n\r\n/**\r\n * The connectivity state of the channel.\r\n *\r\n * @constructor\r\n * @struct\r\n */\r\ngoog.labs.net.webChannel.ConnectionState = function() {\r\n /**\r\n * Handshake result.\r\n * @type {Array<string>}\r\n */\r\n this.handshakeResult = null;\r\n\r\n /**\r\n * The result of checking if there is a buffering proxy in the network.\r\n * True means the connection is buffered, False means unbuffered,\r\n * null means that the result is not available.\r\n * @type {?boolean}\r\n */\r\n this.bufferingProxyResult = null;\r\n};\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Datastructure: Set.\r\n *\r\n * @author arv@google.com (Erik Arvidsson)\r\n *\r\n * This class implements a set data structure. Adding and removing is O(1). It\r\n * supports both object and primitive values. Be careful because you can add\r\n * both 1 and new Number(1), because these are not the same. You can even add\r\n * multiple new Number(1) because these are not equal.\r\n */\r\n\r\n\r\ngoog.provide('goog.structs.Set');\r\n\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.Collection');\r\ngoog.require('goog.structs.Map');\r\n\r\n/**\r\n * A set that can contain both primitives and objects. Adding and removing\r\n * elements is O(1). Primitives are treated as identical if they have the same\r\n * type and convert to the same string. Objects are treated as identical only\r\n * if they are references to the same object. WARNING: A goog.structs.Set can\r\n * contain both 1 and (new Number(1)), because they are not the same. WARNING:\r\n * Adding (new Number(1)) twice will yield two distinct elements, because they\r\n * are two different objects. WARNING: Any object that is added to a\r\n * goog.structs.Set will be modified! Because goog.getUid() is used to\r\n * identify objects, every object in the set will be mutated.\r\n * @param {Array<T>|Object<?,T>=} opt_values Initial values to start with.\r\n * @constructor\r\n * @implements {goog.structs.Collection<T>}\r\n * @final\r\n * @template T\r\n * @deprecated This type is misleading: use ES6 Set instead.\r\n */\r\ngoog.structs.Set = function(opt_values) {\r\n this.map_ = new goog.structs.Map;\r\n if (opt_values) {\r\n this.addAll(opt_values);\r\n }\r\n};\r\n\r\n/**\r\n * A function that returns a unique id.\r\n * @private @const {function(?Object): number}\r\n */\r\ngoog.structs.Set.getUid_ = goog.getUid;\r\n\r\n\r\n/**\r\n * Obtains a unique key for an element of the set. Primitives will yield the\r\n * same key if they have the same type and convert to the same string. Object\r\n * references will yield the same key only if they refer to the same object.\r\n * @param {*} val Object or primitive value to get a key for.\r\n * @return {string} A unique key for this value/object.\r\n * @private\r\n */\r\ngoog.structs.Set.getKey_ = function(val) {\r\n var type = typeof val;\r\n if (type == 'object' && val || type == 'function') {\r\n return 'o' + goog.structs.Set.getUid_(/** @type {Object} */ (val));\r\n } else {\r\n return type.substr(0, 1) + val;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of elements in the set.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.getCount = function() {\r\n return this.map_.getCount();\r\n};\r\n\r\n\r\n/**\r\n * Add a primitive or an object to the set.\r\n * @param {T} element The primitive or object to add.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.add = function(element) {\r\n this.map_.set(goog.structs.Set.getKey_(element), element);\r\n};\r\n\r\n\r\n/**\r\n * Adds all the values in the given collection to this set.\r\n * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection\r\n * containing the elements to add.\r\n */\r\ngoog.structs.Set.prototype.addAll = function(col) {\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n this.add(values[i]);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes all values in the given collection from this set.\r\n * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection\r\n * containing the elements to remove.\r\n */\r\ngoog.structs.Set.prototype.removeAll = function(col) {\r\n var values = goog.structs.getValues(col);\r\n var l = values.length;\r\n for (var i = 0; i < l; i++) {\r\n this.remove(values[i]);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes the given element from this set.\r\n * @param {T} element The primitive or object to remove.\r\n * @return {boolean} Whether the element was found and removed.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.remove = function(element) {\r\n return this.map_.remove(goog.structs.Set.getKey_(element));\r\n};\r\n\r\n\r\n/**\r\n * Removes all elements from this set.\r\n */\r\ngoog.structs.Set.prototype.clear = function() {\r\n this.map_.clear();\r\n};\r\n\r\n\r\n/**\r\n * Tests whether this set is empty.\r\n * @return {boolean} True if there are no elements in this set.\r\n */\r\ngoog.structs.Set.prototype.isEmpty = function() {\r\n return this.map_.isEmpty();\r\n};\r\n\r\n\r\n/**\r\n * Tests whether this set contains the given element.\r\n * @param {T} element The primitive or object to test for.\r\n * @return {boolean} True if this set contains the given element.\r\n * @override\r\n */\r\ngoog.structs.Set.prototype.contains = function(element) {\r\n return this.map_.containsKey(goog.structs.Set.getKey_(element));\r\n};\r\n\r\n\r\n/**\r\n * Tests whether this set contains all the values in a given collection.\r\n * Repeated elements in the collection are ignored, e.g. (new\r\n * goog.structs.Set([1, 2])).containsAll([1, 1]) is True.\r\n * @param {goog.structs.Collection<T>|Object} col A collection-like object.\r\n * @return {boolean} True if the set contains all elements.\r\n */\r\ngoog.structs.Set.prototype.containsAll = function(col) {\r\n return goog.structs.every(col, this.contains, this);\r\n};\r\n\r\n\r\n/**\r\n * Finds all values that are present in both this set and the given collection.\r\n * @param {Array<S>|Object<?,S>} col A collection.\r\n * @return {!goog.structs.Set<T|S>} A new set containing all the values\r\n * (primitives or objects) present in both this set and the given\r\n * collection.\r\n * @template S\r\n */\r\ngoog.structs.Set.prototype.intersection = function(col) {\r\n var result = new goog.structs.Set();\r\n\r\n var values = goog.structs.getValues(col);\r\n for (var i = 0; i < values.length; i++) {\r\n var value = values[i];\r\n if (this.contains(value)) {\r\n result.add(value);\r\n }\r\n }\r\n\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Finds all values that are present in this set and not in the given\r\n * collection.\r\n * @param {Array<T>|goog.structs.Collection<T>|Object<?,T>} col A collection.\r\n * @return {!goog.structs.Set} A new set containing all the values\r\n * (primitives or objects) present in this set but not in the given\r\n * collection.\r\n */\r\ngoog.structs.Set.prototype.difference = function(col) {\r\n var result = this.clone();\r\n result.removeAll(col);\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Returns an array containing all the elements in this set.\r\n * @return {!Array<T>} An array containing all the elements in this set.\r\n */\r\ngoog.structs.Set.prototype.getValues = function() {\r\n return this.map_.getValues();\r\n};\r\n\r\n\r\n/**\r\n * Creates a shallow clone of this set.\r\n * @return {!goog.structs.Set<T>} A new set containing all the same elements as\r\n * this set.\r\n */\r\ngoog.structs.Set.prototype.clone = function() {\r\n return new goog.structs.Set(this);\r\n};\r\n\r\n\r\n/**\r\n * Tests whether the given collection consists of the same elements as this set,\r\n * regardless of order, without repetition. Primitives are treated as equal if\r\n * they have the same type and convert to the same string; objects are treated\r\n * as equal if they are references to the same object. This operation is O(n).\r\n * @param {goog.structs.Collection<T>|Object} col A collection.\r\n * @return {boolean} True if the given collection consists of the same elements\r\n * as this set, regardless of order, without repetition.\r\n */\r\ngoog.structs.Set.prototype.equals = function(col) {\r\n return this.getCount() == goog.structs.getCount(col) && this.isSubsetOf(col);\r\n};\r\n\r\n\r\n/**\r\n * Tests whether the given collection contains all the elements in this set.\r\n * Primitives are treated as equal if they have the same type and convert to the\r\n * same string; objects are treated as equal if they are references to the same\r\n * object. This operation is O(n).\r\n * @param {goog.structs.Collection<T>|Object} col A collection.\r\n * @return {boolean} True if this set is a subset of the given collection.\r\n */\r\ngoog.structs.Set.prototype.isSubsetOf = function(col) {\r\n var colCount = goog.structs.getCount(col);\r\n if (this.getCount() > colCount) {\r\n return false;\r\n }\r\n // TODO(user) Find the minimal collection size where the conversion makes\r\n // the contains() method faster.\r\n if (!(col instanceof goog.structs.Set) && colCount > 5) {\r\n // Convert to a goog.structs.Set so that goog.structs.contains runs in\r\n // O(1) time instead of O(n) time.\r\n col = new goog.structs.Set(col);\r\n }\r\n return goog.structs.every(\r\n this, function(value) { return goog.structs.contains(col, value); });\r\n};\r\n\r\n\r\n/**\r\n * Returns an iterator that iterates over the elements in this set.\r\n * @param {boolean=} opt_keys This argument is ignored.\r\n * @return {!goog.iter.Iterator} An iterator over the elements in this set.\r\n */\r\ngoog.structs.Set.prototype.__iterator__ = function(opt_keys) {\r\n return this.map_.__iterator__(false);\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Interface and shared data structures for implementing\r\n * different wire protocol versions.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.Wire');\r\n\r\ngoog.forwardDeclare('goog.structs.Map');\r\n\r\n\r\n\r\n/**\r\n * The interface class.\r\n *\r\n * @interface\r\n */\r\ngoog.labs.net.webChannel.Wire = function() {};\r\n\r\n\r\ngoog.scope(function() {\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\n\r\n\r\n/**\r\n * The latest protocol version that this class supports. We request this version\r\n * from the server when opening the connection. Should match\r\n * LATEST_CHANNEL_VERSION on the server code.\r\n * @type {number}\r\n */\r\nWire.LATEST_CHANNEL_VERSION = 8;\r\n\r\n\r\n/**\r\n * The JSON field key for the raw data wrapper object.\r\n * @type {string}\r\n */\r\nWire.RAW_DATA_KEY = '__data__';\r\n\r\n\r\n\r\n/**\r\n * Simple container class for a (mapId, map) pair.\r\n * @param {number} mapId The id for this map.\r\n * @param {!Object|!goog.structs.Map} map The map itself.\r\n * @param {!Object=} opt_context The context associated with the map.\r\n * @constructor\r\n * @struct\r\n */\r\nWire.QueuedMap = function(mapId, map, opt_context) {\r\n /**\r\n * The id for this map.\r\n * @type {number}\r\n */\r\n this.mapId = mapId;\r\n\r\n /**\r\n * The map itself.\r\n * @type {!Object|!goog.structs.Map}\r\n */\r\n this.map = map;\r\n\r\n /**\r\n * The context for the map.\r\n * @type {Object}\r\n */\r\n this.context = opt_context || null;\r\n};\r\n\r\n\r\n/**\r\n * @return {number|undefined} the size of the raw JSON message or\r\n * undefined if the message is not encoded as a raw JSON message\r\n */\r\nWire.QueuedMap.prototype.getRawDataSize = function() {\r\n if (Wire.RAW_DATA_KEY in this.map) {\r\n var data = this.map[Wire.RAW_DATA_KEY];\r\n if (goog.isString(data)) {\r\n return data.length;\r\n }\r\n }\r\n\r\n return undefined;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview A pool of forward channel requests to enable real-time\r\n * messaging from the client to server.\r\n */\r\n\r\ngoog.module('goog.labs.net.webChannel.ForwardChannelRequestPool');\r\n\r\ngoog.module.declareLegacyNamespace();\r\n\r\nvar ChannelRequest = goog.require('goog.labs.net.webChannel.ChannelRequest');\r\nvar Set = goog.require('goog.structs.Set');\r\nvar Wire = goog.require('goog.labs.net.webChannel.Wire');\r\nvar array = goog.require('goog.array');\r\nvar googString = goog.require('goog.string');\r\n\r\n\r\n/**\r\n * This class represents the state of all forward channel requests.\r\n *\r\n * @param {number=} opt_maxPoolSize The maximum pool size.\r\n *\r\n * @struct @constructor @final\r\n */\r\nvar ForwardChannelRequestPool = function(opt_maxPoolSize) {\r\n /**\r\n * The max pool size as configured.\r\n *\r\n * @private {number}\r\n */\r\n this.maxPoolSizeConfigured_ =\r\n opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;\r\n\r\n /**\r\n * The current size limit of the request pool. This limit is meant to be\r\n * read-only after the channel is fully opened.\r\n *\r\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\r\n * configurable.\r\n *\r\n * @private {number}\r\n */\r\n this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?\r\n this.maxPoolSizeConfigured_ :\r\n 1;\r\n\r\n /**\r\n * The container for all the pending request objects.\r\n *\r\n * @private {Set<ChannelRequest>}\r\n */\r\n this.requestPool_ = null;\r\n\r\n if (this.maxSize_ > 1) {\r\n this.requestPool_ = new Set();\r\n }\r\n\r\n /**\r\n * The single request object when the pool size is limited to one.\r\n *\r\n * @private {ChannelRequest}\r\n */\r\n this.request_ = null;\r\n\r\n /**\r\n * Saved pending messages when the pool is cancelled.\r\n *\r\n * @private {!Array<Wire.QueuedMap>}\r\n */\r\n this.pendingMessages_ = [];\r\n};\r\n\r\n\r\n/**\r\n * The default size limit of the request pool.\r\n *\r\n * @private {number}\r\n */\r\nForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;\r\n\r\n\r\n/**\r\n * @return {boolean} True if SPDY or HTTP2 is enabled. Uses chrome-specific APIs\r\n * as a fallback and will always return false for other browsers where\r\n * PerformanceNavigationTiming is not available.\r\n * @private\r\n */\r\nForwardChannelRequestPool.isSpdyOrHttp2Enabled_ = function() {\r\n if (goog.global.PerformanceNavigationTiming) {\r\n var entrys = /** @type {!Array<!PerformanceNavigationTiming>} */ (\r\n goog.global.performance.getEntriesByType('navigation'));\r\n return entrys.length > 0 &&\r\n (entrys[0].nextHopProtocol == 'hq' ||\r\n entrys[0].nextHopProtocol == 'h2');\r\n }\r\n return !!(\r\n goog.global.chrome && goog.global.chrome.loadTimes &&\r\n goog.global.chrome.loadTimes() &&\r\n goog.global.chrome.loadTimes().wasFetchedViaSpdy);\r\n};\r\n\r\n\r\n/**\r\n * Once we know the client protocol (from the handshake), check if we need\r\n * enable the request pool accordingly. This is more robust than using\r\n * browser-internal APIs (specific to Chrome).\r\n *\r\n * @param {string} clientProtocol The client protocol\r\n */\r\nForwardChannelRequestPool.prototype.applyClientProtocol = function(\r\n clientProtocol) {\r\n if (this.requestPool_) {\r\n return;\r\n }\r\n\r\n if (googString.contains(clientProtocol, 'spdy') ||\r\n googString.contains(clientProtocol, 'quic') ||\r\n googString.contains(clientProtocol, 'h2')) {\r\n this.maxSize_ = this.maxPoolSizeConfigured_;\r\n this.requestPool_ = new Set();\r\n if (this.request_) {\r\n this.addRequest(this.request_);\r\n this.request_ = null;\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} True if the pool is full.\r\n */\r\nForwardChannelRequestPool.prototype.isFull = function() {\r\n if (this.request_) {\r\n return true;\r\n }\r\n\r\n if (this.requestPool_) {\r\n return this.requestPool_.getCount() >= this.maxSize_;\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The current size limit.\r\n */\r\nForwardChannelRequestPool.prototype.getMaxSize = function() {\r\n return this.maxSize_;\r\n};\r\n\r\n\r\n/**\r\n * @return {number} The number of pending requests in the pool.\r\n */\r\nForwardChannelRequestPool.prototype.getRequestCount = function() {\r\n if (this.request_) {\r\n return 1;\r\n }\r\n\r\n if (this.requestPool_) {\r\n return this.requestPool_.getCount();\r\n }\r\n\r\n return 0;\r\n};\r\n\r\n\r\n/**\r\n * @param {ChannelRequest} req The channel request.\r\n * @return {boolean} True if the request is a included inside the pool.\r\n */\r\nForwardChannelRequestPool.prototype.hasRequest = function(req) {\r\n if (this.request_) {\r\n return this.request_ == req;\r\n }\r\n\r\n if (this.requestPool_) {\r\n return this.requestPool_.contains(req);\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Adds a new request to the pool.\r\n *\r\n * @param {!ChannelRequest} req The new channel request.\r\n */\r\nForwardChannelRequestPool.prototype.addRequest = function(req) {\r\n if (this.requestPool_) {\r\n this.requestPool_.add(req);\r\n } else {\r\n this.request_ = req;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Removes the given request from the pool.\r\n *\r\n * @param {ChannelRequest} req The channel request.\r\n * @return {boolean} Whether the request has been removed from the pool.\r\n */\r\nForwardChannelRequestPool.prototype.removeRequest = function(req) {\r\n if (this.request_ && this.request_ == req) {\r\n this.request_ = null;\r\n return true;\r\n }\r\n\r\n if (this.requestPool_ && this.requestPool_.contains(req)) {\r\n this.requestPool_.remove(req);\r\n return true;\r\n }\r\n\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Clears the pool and cancel all the pending requests.\r\n */\r\nForwardChannelRequestPool.prototype.cancel = function() {\r\n // save any pending messages\r\n this.pendingMessages_ = this.getPendingMessages();\r\n\r\n if (this.request_) {\r\n this.request_.cancel();\r\n this.request_ = null;\r\n return;\r\n }\r\n\r\n if (this.requestPool_ && !this.requestPool_.isEmpty()) {\r\n array.forEach(this.requestPool_.getValues(), function(val) {\r\n val.cancel();\r\n });\r\n this.requestPool_.clear();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether there are any pending requests.\r\n */\r\nForwardChannelRequestPool.prototype.hasPendingRequest = function() {\r\n return (this.request_ != null) ||\r\n (this.requestPool_ != null && !this.requestPool_.isEmpty());\r\n};\r\n\r\n\r\n/**\r\n * @return {!Array<Wire.QueuedMap>} All the pending messages from the pool,\r\n * as a new array.\r\n */\r\nForwardChannelRequestPool.prototype.getPendingMessages = function() {\r\n if (this.request_ != null) {\r\n return this.pendingMessages_.concat(this.request_.getPendingMessages());\r\n }\r\n\r\n if (this.requestPool_ != null && !this.requestPool_.isEmpty()) {\r\n var result = this.pendingMessages_;\r\n array.forEach(this.requestPool_.getValues(), function(val) {\r\n result = result.concat(val.getPendingMessages());\r\n });\r\n return result;\r\n }\r\n\r\n return array.clone(this.pendingMessages_);\r\n};\r\n\r\n\r\n/**\r\n * Records pending messages, e.g. when a request receives a failed response.\r\n *\r\n * @param {!Array<Wire.QueuedMap>} messages Pending messages.\r\n */\r\nForwardChannelRequestPool.prototype.addPendingMessages = function(messages) {\r\n this.pendingMessages_ = this.pendingMessages_.concat(messages);\r\n};\r\n\r\n\r\n/**\r\n * Clears any recorded pending messages.\r\n */\r\nForwardChannelRequestPool.prototype.clearPendingMessages = function() {\r\n this.pendingMessages_.length = 0;\r\n};\r\n\r\n\r\n/**\r\n * Cancels all pending requests and force the completion of channel requests.\r\n *\r\n * Need go through the standard onRequestComplete logic to expose the max-retry\r\n * failure in the standard way.\r\n *\r\n * @param {function(!ChannelRequest)} onComplete The completion callback.\r\n * @return {boolean} true if any request has been forced to complete.\r\n */\r\nForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {\r\n if (this.request_ != null) {\r\n this.request_.cancel();\r\n onComplete(this.request_);\r\n return true;\r\n }\r\n\r\n if (this.requestPool_ && !this.requestPool_.isEmpty()) {\r\n array.forEach(this.requestPool_.getValues(), function(val) {\r\n val.cancel();\r\n onComplete(val);\r\n });\r\n return true;\r\n }\r\n\r\n return false;\r\n};\r\n\r\nexports = ForwardChannelRequestPool;\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Definition of various formatters for logging. Please minimize\r\n * dependencies this file has on other closure classes as any dependency it\r\n * takes won't be able to use the logging infrastructure.\r\n *\r\n */\r\n\r\ngoog.provide('goog.debug.Formatter');\r\ngoog.provide('goog.debug.HtmlFormatter');\r\ngoog.provide('goog.debug.TextFormatter');\r\n\r\ngoog.require('goog.debug');\r\ngoog.require('goog.debug.Logger');\r\ngoog.require('goog.debug.RelativeTimeProvider');\r\ngoog.require('goog.html.SafeHtml');\r\ngoog.require('goog.html.SafeUrl');\r\ngoog.require('goog.html.uncheckedconversions');\r\ngoog.require('goog.string.Const');\r\n\r\n\r\n\r\n/**\r\n * Base class for Formatters. A Formatter is used to format a LogRecord into\r\n * something that can be displayed to the user.\r\n *\r\n * @param {string=} opt_prefix The prefix to place before text records.\r\n * @constructor\r\n */\r\ngoog.debug.Formatter = function(opt_prefix) {\r\n this.prefix_ = opt_prefix || '';\r\n\r\n /**\r\n * A provider that returns the relative start time.\r\n * @type {goog.debug.RelativeTimeProvider}\r\n * @private\r\n */\r\n this.startTimeProvider_ =\r\n goog.debug.RelativeTimeProvider.getDefaultInstance();\r\n};\r\n\r\n\r\n/**\r\n * Whether to append newlines to the end of formatted log records.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.appendNewline = true;\r\n\r\n\r\n/**\r\n * Whether to show absolute time in the DebugWindow.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showAbsoluteTime = true;\r\n\r\n\r\n/**\r\n * Whether to show relative time in the DebugWindow.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showRelativeTime = true;\r\n\r\n\r\n/**\r\n * Whether to show the logger name in the DebugWindow.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showLoggerName = true;\r\n\r\n\r\n/**\r\n * Whether to show the logger exception text.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showExceptionText = false;\r\n\r\n\r\n/**\r\n * Whether to show the severity level.\r\n * @type {boolean}\r\n */\r\ngoog.debug.Formatter.prototype.showSeverityLevel = false;\r\n\r\n\r\n/**\r\n * Formats a record.\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {string} The formatted string.\r\n */\r\ngoog.debug.Formatter.prototype.formatRecord = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Formats a record as SafeHtml.\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {!goog.html.SafeHtml} The formatted string as SafeHtml.\r\n */\r\ngoog.debug.Formatter.prototype.formatRecordAsHtml = goog.abstractMethod;\r\n\r\n\r\n/**\r\n * Sets the start time provider. By default, this is the default instance\r\n * but can be changed.\r\n * @param {goog.debug.RelativeTimeProvider} provider The provider to use.\r\n */\r\ngoog.debug.Formatter.prototype.setStartTimeProvider = function(provider) {\r\n this.startTimeProvider_ = provider;\r\n};\r\n\r\n\r\n/**\r\n * Returns the start time provider. By default, this is the default instance\r\n * but can be changed.\r\n * @return {goog.debug.RelativeTimeProvider} The start time provider.\r\n */\r\ngoog.debug.Formatter.prototype.getStartTimeProvider = function() {\r\n return this.startTimeProvider_;\r\n};\r\n\r\n\r\n/**\r\n * Resets the start relative time.\r\n */\r\ngoog.debug.Formatter.prototype.resetRelativeTimeStart = function() {\r\n this.startTimeProvider_.reset();\r\n};\r\n\r\n\r\n/**\r\n * Returns a string for the time/date of the LogRecord.\r\n * @param {goog.debug.LogRecord} logRecord The record to get a time stamp for.\r\n * @return {string} A string representation of the time/date of the LogRecord.\r\n * @private\r\n */\r\ngoog.debug.Formatter.getDateTimeStamp_ = function(logRecord) {\r\n var time = new Date(logRecord.getMillis());\r\n return goog.debug.Formatter.getTwoDigitString_((time.getFullYear() - 2000)) +\r\n goog.debug.Formatter.getTwoDigitString_((time.getMonth() + 1)) +\r\n goog.debug.Formatter.getTwoDigitString_(time.getDate()) + ' ' +\r\n goog.debug.Formatter.getTwoDigitString_(time.getHours()) + ':' +\r\n goog.debug.Formatter.getTwoDigitString_(time.getMinutes()) + ':' +\r\n goog.debug.Formatter.getTwoDigitString_(time.getSeconds()) + '.' +\r\n goog.debug.Formatter.getTwoDigitString_(\r\n Math.floor(time.getMilliseconds() / 10));\r\n};\r\n\r\n\r\n/**\r\n * Returns the number as a two-digit string, meaning it prepends a 0 if the\r\n * number if less than 10.\r\n * @param {number} n The number to format.\r\n * @return {string} A two-digit string representation of `n`.\r\n * @private\r\n */\r\ngoog.debug.Formatter.getTwoDigitString_ = function(n) {\r\n if (n < 10) {\r\n return '0' + n;\r\n }\r\n return String(n);\r\n};\r\n\r\n\r\n/**\r\n * Returns a string for the number of seconds relative to the start time.\r\n * Prepads with spaces so that anything less than 1000 seconds takes up the\r\n * same number of characters for better formatting.\r\n * @param {goog.debug.LogRecord} logRecord The log to compare time to.\r\n * @param {number} relativeTimeStart The start time to compare to.\r\n * @return {string} The number of seconds of the LogRecord relative to the\r\n * start time.\r\n * @private\r\n */\r\ngoog.debug.Formatter.getRelativeTime_ = function(logRecord, relativeTimeStart) {\r\n var ms = logRecord.getMillis() - relativeTimeStart;\r\n var sec = ms / 1000;\r\n var str = sec.toFixed(3);\r\n\r\n var spacesToPrepend = 0;\r\n if (sec < 1) {\r\n spacesToPrepend = 2;\r\n } else {\r\n while (sec < 100) {\r\n spacesToPrepend++;\r\n sec *= 10;\r\n }\r\n }\r\n while (spacesToPrepend-- > 0) {\r\n str = ' ' + str;\r\n }\r\n return str;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Formatter that returns formatted html. See formatRecord for the classes\r\n * it uses for various types of formatted output.\r\n *\r\n * @param {string=} opt_prefix The prefix to place before text records.\r\n * @constructor\r\n * @extends {goog.debug.Formatter}\r\n */\r\ngoog.debug.HtmlFormatter = function(opt_prefix) {\r\n goog.debug.Formatter.call(this, opt_prefix);\r\n};\r\ngoog.inherits(goog.debug.HtmlFormatter, goog.debug.Formatter);\r\n\r\n\r\n/**\r\n * Exposes an exception that has been caught by a try...catch and outputs the\r\n * error as HTML with a stack trace.\r\n *\r\n * @param {*} err Error object or string.\r\n * @param {?Function=} fn If provided, when collecting the stack trace all\r\n * frames above the topmost call to this function, including that call,\r\n * will be left out of the stack trace.\r\n * @return {string} Details of exception, as HTML.\r\n */\r\ngoog.debug.HtmlFormatter.exposeException = function(err, fn) {\r\n var html = goog.debug.HtmlFormatter.exposeExceptionAsHtml(err, fn);\r\n return goog.html.SafeHtml.unwrap(html);\r\n};\r\n\r\n\r\n/**\r\n * Exposes an exception that has been caught by a try...catch and outputs the\r\n * error with a stack trace.\r\n *\r\n * @param {*} err Error object or string.\r\n * @param {?Function=} fn If provided, when collecting the stack trace all\r\n * frames above the topmost call to this function, including that call,\r\n * will be left out of the stack trace.\r\n * @return {!goog.html.SafeHtml} Details of exception.\r\n */\r\ngoog.debug.HtmlFormatter.exposeExceptionAsHtml = function(err, fn) {\r\n try {\r\n var e = goog.debug.normalizeErrorObject(err);\r\n // Create the error message\r\n var viewSourceUrl =\r\n goog.debug.HtmlFormatter.createViewSourceUrl_(e.fileName);\r\n var error = goog.html.SafeHtml.concat(\r\n goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n 'Message: ' + e.message + '\\nUrl: '),\r\n goog.html.SafeHtml.create(\r\n 'a', {href: viewSourceUrl, target: '_new'}, e.fileName),\r\n goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n '\\nLine: ' + e.lineNumber + '\\n\\nBrowser stack:\\n' + e.stack +\r\n '-> ' +\r\n '[end]\\n\\nJS stack traversal:\\n' + goog.debug.getStacktrace(fn) +\r\n '-> '));\r\n return error;\r\n } catch (e2) {\r\n return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n 'Exception trying to expose exception! You win, we lose. ' + e2);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @param {?string=} fileName\r\n * @return {!goog.html.SafeUrl} SafeUrl with view-source scheme, pointing at\r\n * fileName.\r\n * @private\r\n */\r\ngoog.debug.HtmlFormatter.createViewSourceUrl_ = function(fileName) {\r\n if (!goog.isDefAndNotNull(fileName)) {\r\n fileName = '';\r\n }\r\n if (!/^https?:\\/\\//i.test(fileName)) {\r\n return goog.html.SafeUrl.fromConstant(\r\n goog.string.Const.from('sanitizedviewsrc'));\r\n }\r\n var sanitizedFileName = goog.html.SafeUrl.sanitize(fileName);\r\n return goog.html.uncheckedconversions\r\n .safeUrlFromStringKnownToSatisfyTypeContract(\r\n goog.string.Const.from('view-source scheme plus HTTP/HTTPS URL'),\r\n 'view-source:' + goog.html.SafeUrl.unwrap(sanitizedFileName));\r\n};\r\n\r\n\r\n\r\n/**\r\n * Whether to show the logger exception text\r\n * @type {boolean}\r\n * @override\r\n */\r\ngoog.debug.HtmlFormatter.prototype.showExceptionText = true;\r\n\r\n\r\n/**\r\n * Formats a record\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {string} The formatted string as html.\r\n * @override\r\n */\r\ngoog.debug.HtmlFormatter.prototype.formatRecord = function(logRecord) {\r\n if (!logRecord) {\r\n return '';\r\n }\r\n // OK not to use goog.html.SafeHtml.unwrap() here.\r\n return this.formatRecordAsHtml(logRecord).getTypedStringValue();\r\n};\r\n\r\n\r\n/**\r\n * Formats a record.\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {!goog.html.SafeHtml} The formatted string as SafeHtml.\r\n * @override\r\n */\r\ngoog.debug.HtmlFormatter.prototype.formatRecordAsHtml = function(logRecord) {\r\n if (!logRecord) {\r\n return goog.html.SafeHtml.EMPTY;\r\n }\r\n\r\n var className;\r\n switch (logRecord.getLevel().value) {\r\n case goog.debug.Logger.Level.SHOUT.value:\r\n className = 'dbg-sh';\r\n break;\r\n case goog.debug.Logger.Level.SEVERE.value:\r\n className = 'dbg-sev';\r\n break;\r\n case goog.debug.Logger.Level.WARNING.value:\r\n className = 'dbg-w';\r\n break;\r\n case goog.debug.Logger.Level.INFO.value:\r\n className = 'dbg-i';\r\n break;\r\n case goog.debug.Logger.Level.FINE.value:\r\n default:\r\n className = 'dbg-f';\r\n break;\r\n }\r\n\r\n // HTML for user defined prefix, time, logger name, and severity.\r\n var sb = [];\r\n sb.push(this.prefix_, ' ');\r\n if (this.showAbsoluteTime) {\r\n sb.push('[', goog.debug.Formatter.getDateTimeStamp_(logRecord), '] ');\r\n }\r\n if (this.showRelativeTime) {\r\n sb.push(\r\n '[', goog.debug.Formatter.getRelativeTime_(\r\n logRecord, this.startTimeProvider_.get()),\r\n 's] ');\r\n }\r\n if (this.showLoggerName) {\r\n sb.push('[', logRecord.getLoggerName(), '] ');\r\n }\r\n if (this.showSeverityLevel) {\r\n sb.push('[', logRecord.getLevel().name, '] ');\r\n }\r\n var fullPrefixHtml =\r\n goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(sb.join(''));\r\n\r\n // HTML for exception text and log record.\r\n var exceptionHtml = goog.html.SafeHtml.EMPTY;\r\n if (this.showExceptionText && logRecord.getException()) {\r\n exceptionHtml = goog.html.SafeHtml.concat(\r\n goog.html.SafeHtml.BR,\r\n goog.debug.HtmlFormatter.exposeExceptionAsHtml(\r\n logRecord.getException()));\r\n }\r\n var logRecordHtml = goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n logRecord.getMessage());\r\n var recordAndExceptionHtml = goog.html.SafeHtml.create(\r\n 'span', {'class': className},\r\n goog.html.SafeHtml.concat(logRecordHtml, exceptionHtml));\r\n\r\n\r\n // Combine both pieces of HTML and, if needed, append a final newline.\r\n var html;\r\n if (this.appendNewline) {\r\n html = goog.html.SafeHtml.concat(\r\n fullPrefixHtml, recordAndExceptionHtml, goog.html.SafeHtml.BR);\r\n } else {\r\n html = goog.html.SafeHtml.concat(fullPrefixHtml, recordAndExceptionHtml);\r\n }\r\n return html;\r\n};\r\n\r\n\r\n\r\n/**\r\n * Formatter that returns formatted plain text\r\n *\r\n * @param {string=} opt_prefix The prefix to place before text records.\r\n * @constructor\r\n * @extends {goog.debug.Formatter}\r\n * @final\r\n */\r\ngoog.debug.TextFormatter = function(opt_prefix) {\r\n goog.debug.Formatter.call(this, opt_prefix);\r\n};\r\ngoog.inherits(goog.debug.TextFormatter, goog.debug.Formatter);\r\n\r\n\r\n/**\r\n * Formats a record as text\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {string} The formatted string.\r\n * @override\r\n */\r\ngoog.debug.TextFormatter.prototype.formatRecord = function(logRecord) {\r\n var sb = [];\r\n sb.push(this.prefix_, ' ');\r\n if (this.showAbsoluteTime) {\r\n sb.push('[', goog.debug.Formatter.getDateTimeStamp_(logRecord), '] ');\r\n }\r\n if (this.showRelativeTime) {\r\n sb.push(\r\n '[', goog.debug.Formatter.getRelativeTime_(\r\n logRecord, this.startTimeProvider_.get()),\r\n 's] ');\r\n }\r\n\r\n if (this.showLoggerName) {\r\n sb.push('[', logRecord.getLoggerName(), '] ');\r\n }\r\n if (this.showSeverityLevel) {\r\n sb.push('[', logRecord.getLevel().name, '] ');\r\n }\r\n sb.push(logRecord.getMessage());\r\n if (this.showExceptionText) {\r\n var exception = logRecord.getException();\r\n if (exception) {\r\n var exceptionText =\r\n exception instanceof Error ? exception.message : exception.toString();\r\n sb.push('\\n', exceptionText);\r\n }\r\n }\r\n if (this.appendNewline) {\r\n sb.push('\\n');\r\n }\r\n return sb.join('');\r\n};\r\n\r\n\r\n/**\r\n * Formats a record as text\r\n * @param {goog.debug.LogRecord} logRecord the logRecord to format.\r\n * @return {!goog.html.SafeHtml} The formatted string as SafeHtml. This is\r\n * just an HTML-escaped version of the text obtained from formatRecord().\r\n * @override\r\n */\r\ngoog.debug.TextFormatter.prototype.formatRecordAsHtml = function(logRecord) {\r\n return goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces(\r\n goog.debug.TextFormatter.prototype.formatRecord(logRecord));\r\n};\r\n","// Copyright 2012 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n\r\n/**\r\n * @fileoverview Defines a class for parsing JSON using the browser's built in\r\n * JSON library.\r\n */\r\n\r\ngoog.provide('goog.json.NativeJsonProcessor');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.json.Processor');\r\n\r\n\r\n\r\n/**\r\n * A class that parses and stringifies JSON using the browser's built-in JSON\r\n * library, if it is available.\r\n *\r\n * Note that the native JSON api has subtle differences across browsers, so\r\n * use this implementation with care. See json_test#assertSerialize\r\n * for details on the differences from goog.json.\r\n *\r\n * This implementation is signficantly faster than goog.json, at least on\r\n * Chrome. See json_perf.html for a perf test showing the difference.\r\n *\r\n * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during\r\n * serialization.\r\n * @param {?goog.json.Reviver=} opt_reviver An optional reviver to use during\r\n * parsing.\r\n * @constructor\r\n * @implements {goog.json.Processor}\r\n * @final\r\n */\r\ngoog.json.NativeJsonProcessor = function(opt_replacer, opt_reviver) {\r\n goog.asserts.assert(goog.isDef(goog.global['JSON']), 'JSON not defined');\r\n\r\n /**\r\n * @type {goog.json.Replacer|null|undefined}\r\n * @private\r\n */\r\n this.replacer_ = opt_replacer;\r\n\r\n /**\r\n * @type {goog.json.Reviver|null|undefined}\r\n * @private\r\n */\r\n this.reviver_ = opt_reviver;\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.json.NativeJsonProcessor.prototype.stringify = function(object) {\r\n return goog.global['JSON'].stringify(object, this.replacer_);\r\n};\r\n\r\n\r\n/** @override */\r\ngoog.json.NativeJsonProcessor.prototype.parse = function(s) {\r\n return goog.global['JSON'].parse(s, this.reviver_);\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Codec functions of the v8 wire protocol. Eventually we'd want\r\n * to support pluggable wire-format to improve wire efficiency and to enable\r\n * binary encoding. Such support will require an interface class, which\r\n * will be added later.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.WireV8');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.json');\r\ngoog.require('goog.json.NativeJsonProcessor');\r\ngoog.require('goog.labs.net.webChannel.Wire');\r\ngoog.require('goog.structs');\r\n\r\ngoog.forwardDeclare('goog.structs.Map');\r\n\r\n\r\n\r\n/**\r\n * The v8 codec class.\r\n *\r\n * @constructor\r\n * @struct\r\n */\r\ngoog.labs.net.webChannel.WireV8 = function() {\r\n /**\r\n * Parser for a response payload. The parser should return an array.\r\n * @private {!goog.string.Parser}\r\n */\r\n this.parser_ = new goog.json.NativeJsonProcessor();\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WireV8 = goog.labs.net.webChannel.WireV8;\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\n\r\n\r\n/**\r\n * Encodes a standalone message into the wire format.\r\n *\r\n * May throw exception if the message object contains any invalid elements.\r\n *\r\n * @param {!Object|!goog.structs.Map} message The message data.\r\n * V8 only support JS objects (or Map).\r\n * @param {!Array<string>} buffer The text buffer to write the message to.\r\n * @param {string=} opt_prefix The prefix for each field of the object.\r\n */\r\nWireV8.prototype.encodeMessage = function(message, buffer, opt_prefix) {\r\n var prefix = opt_prefix || '';\r\n try {\r\n goog.structs.forEach(message, function(value, key) {\r\n var encodedValue = value;\r\n if (goog.isObject(value)) {\r\n encodedValue = goog.json.serialize(value);\r\n } // keep the fast-path for primitive types\r\n buffer.push(prefix + key + '=' + encodeURIComponent(encodedValue));\r\n });\r\n } catch (ex) {\r\n // We send a map here because lots of the retry logic relies on map IDs,\r\n // so we have to send something (possibly redundant).\r\n buffer.push(\r\n prefix + 'type' +\r\n '=' + encodeURIComponent('_badmap'));\r\n throw ex;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Encodes all the buffered messages of the forward channel.\r\n *\r\n * @param {!Array<Wire.QueuedMap>} messageQueue The message data.\r\n * V8 only support JS objects.\r\n * @param {number} count The number of messages to be encoded.\r\n * @param {?function(!Object)} badMapHandler Callback for bad messages.\r\n * @return {string} the encoded messages\r\n */\r\nWireV8.prototype.encodeMessageQueue = function(\r\n messageQueue, count, badMapHandler) {\r\n var offset = -1;\r\n while (true) {\r\n var sb = ['count=' + count];\r\n // To save a bit of bandwidth, specify the base mapId and the rest as\r\n // offsets from it.\r\n if (offset == -1) {\r\n if (count > 0) {\r\n offset = messageQueue[0].mapId;\r\n sb.push('ofs=' + offset);\r\n } else {\r\n offset = 0;\r\n }\r\n } else {\r\n sb.push('ofs=' + offset);\r\n }\r\n var done = true;\r\n for (var i = 0; i < count; i++) {\r\n var mapId = messageQueue[i].mapId;\r\n var map = messageQueue[i].map;\r\n mapId -= offset;\r\n if (mapId < 0) {\r\n // redo the encoding in case of retry/reordering, plus extra space\r\n offset = Math.max(0, messageQueue[i].mapId - 100);\r\n done = false;\r\n continue;\r\n }\r\n try {\r\n this.encodeMessage(map, sb, 'req' + mapId + '_');\r\n } catch (ex) {\r\n if (badMapHandler) {\r\n badMapHandler(map);\r\n }\r\n }\r\n }\r\n if (done) {\r\n return sb.join('&');\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Decodes a standalone message received from the wire. May throw exception\r\n * if text is ill-formatted.\r\n *\r\n * Must be valid JSON as it is insecure to use eval() to decode JS literals;\r\n * and eval() is disallowed in Chrome apps too.\r\n *\r\n * Invalid JS literals include null array elements, quotas etc.\r\n *\r\n * @param {string} messageText The string content as received from the wire.\r\n * @return {*} The decoded message object.\r\n */\r\nWireV8.prototype.decodeMessage = function(messageText) {\r\n var response = this.parser_.parse(messageText);\r\n goog.asserts.assert(goog.isArray(response)); // throw exception\r\n return response;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utility functions for managing networking, such as\r\n * testing network connectivity.\r\n */\r\n\r\n\r\ngoog.provide('goog.labs.net.webChannel.netUtils');\r\n\r\ngoog.require('goog.Uri');\r\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\r\n\r\ngoog.scope(function() {\r\nvar netUtils = goog.labs.net.webChannel.netUtils;\r\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\r\n\r\n\r\n/**\r\n * Default timeout to allow for URI pings.\r\n * @type {number}\r\n */\r\nnetUtils.NETWORK_TIMEOUT = 10000;\r\n\r\n\r\n/**\r\n * Pings the network with an image URI to check if an error is a server error\r\n * or user's network error.\r\n *\r\n * The caller needs to add a 'rand' parameter to make sure the response is\r\n * not fulfilled by browser cache.\r\n *\r\n * @param {function(boolean)} callback The function to call back with results.\r\n * @param {goog.Uri=} opt_imageUri The URI (of an image) to use for the network\r\n * test.\r\n */\r\nnetUtils.testNetwork = function(callback, opt_imageUri) {\r\n var uri = opt_imageUri;\r\n if (!uri) {\r\n // default google.com image\r\n uri = new goog.Uri('//www.google.com/images/cleardot.gif');\r\n\r\n if (!(goog.global.location && goog.global.location.protocol == 'http')) {\r\n uri.setScheme('https'); // e.g. chrome-extension\r\n }\r\n uri.makeUnique();\r\n }\r\n\r\n netUtils.testLoadImage(uri.toString(), netUtils.NETWORK_TIMEOUT, callback);\r\n};\r\n\r\n\r\n/**\r\n * Test loading the given image, retrying if necessary.\r\n * @param {string} url URL to the image.\r\n * @param {number} timeout Milliseconds before giving up.\r\n * @param {function(boolean)} callback Function to call with results.\r\n * @param {number} retries The number of times to retry.\r\n * @param {!WebChannelDebug} channelDebug The debug object\r\n * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds\r\n * between retries - defaults to 0.\r\n */\r\nnetUtils.testLoadImageWithRetries = function(\r\n url, timeout, callback, retries, channelDebug, opt_pauseBetweenRetriesMS) {\r\n channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS);\r\n if (retries == 0) {\r\n // no more retries, give up\r\n callback(false);\r\n return;\r\n }\r\n\r\n var pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0;\r\n retries--;\r\n netUtils.testLoadImage(url, timeout, function(succeeded) {\r\n if (succeeded) {\r\n callback(true);\r\n } else {\r\n // try again\r\n goog.global.setTimeout(function() {\r\n netUtils.testLoadImageWithRetries(\r\n url, timeout, callback, retries, channelDebug, pauseBetweenRetries);\r\n }, pauseBetweenRetries);\r\n }\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Test loading the given image.\r\n * @param {string} url URL to the image.\r\n * @param {number} timeout Milliseconds before giving up.\r\n * @param {function(boolean)} callback Function to call with results.\r\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\r\n */\r\nnetUtils.testLoadImage = function(url, timeout, callback) {\r\n var channelDebug = new WebChannelDebug();\r\n channelDebug.debug('TestLoadImage: loading ' + url);\r\n if (goog.global.Image) {\r\n var img = new Image();\r\n img.onload = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: loaded',\r\n true, callback);\r\n img.onerror = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: error',\r\n false, callback);\r\n img.onabort = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: abort',\r\n false, callback);\r\n img.ontimeout = goog.partial(\r\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: timeout',\r\n false, callback);\r\n\r\n goog.global.setTimeout(function() {\r\n if (img.ontimeout) {\r\n img.ontimeout();\r\n }\r\n }, timeout);\r\n img.src = url;\r\n } else {\r\n // log ERROR_OTHER from environements where Image is not supported\r\n callback(false);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Wrap the image callback with debug and cleanup logic.\r\n * @param {!WebChannelDebug} channelDebug The WebChannelDebug object.\r\n * @param {!Image} img The image element.\r\n * @param {string} debugText The debug text.\r\n * @param {boolean} result The result of image loading.\r\n * @param {function(boolean)} callback The image callback.\r\n * @private\r\n */\r\nnetUtils.imageCallback_ = function(\r\n channelDebug, img, debugText, result, callback) {\r\n try {\r\n channelDebug.debug(debugText);\r\n netUtils.clearImageCallbacks_(img);\r\n callback(result);\r\n } catch (e) {\r\n channelDebug.dumpException(e);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Clears handlers to avoid memory leaks.\r\n * @param {Image} img The image to clear handlers from.\r\n * @private\r\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\r\n */\r\nnetUtils.clearImageCallbacks_ = function(img) {\r\n img.onload = null;\r\n img.onerror = null;\r\n img.onabort = null;\r\n img.ontimeout = null;\r\n};\r\n}); // goog.scope\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n\r\n/**\r\n * @fileoverview Utility to attempt native JSON processing, falling back to\r\n * goog.json if not available.\r\n *\r\n * This is intended as a drop-in for current users of goog.json who want\r\n * to take advantage of native JSON if present.\r\n *\r\n * @author nnaze@google.com (Nathan Naze)\r\n */\r\n\r\ngoog.provide('goog.json.hybrid');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.json');\r\n\r\n\r\n/**\r\n * Attempts to serialize the JSON string natively, falling back to\r\n * `goog.json.serialize` if unsuccessful.\r\n * @param {!Object} obj JavaScript object to serialize to JSON.\r\n * @return {string} Resulting JSON string.\r\n */\r\ngoog.json.hybrid.stringify =\r\n goog.json.USE_NATIVE_JSON ? goog.global['JSON']['stringify'] : function(\r\n obj) {\r\n if (goog.global.JSON) {\r\n try {\r\n return goog.global.JSON.stringify(obj);\r\n } catch (e) {\r\n // Native serialization failed. Fall through to retry with\r\n // goog.json.serialize.\r\n }\r\n }\r\n\r\n return goog.json.serialize(obj);\r\n };\r\n\r\n\r\n/**\r\n * Attempts to parse the JSON string natively, falling back to\r\n * the supplied `fallbackParser` if unsuccessful.\r\n * @param {string} jsonString JSON string to parse.\r\n * @param {function(string):Object} fallbackParser Fallback JSON parser used\r\n * if native\r\n * @return {?Object} Resulting JSON object.\r\n * @private\r\n */\r\ngoog.json.hybrid.parse_ = function(jsonString, fallbackParser) {\r\n if (goog.global.JSON) {\r\n try {\r\n var obj = goog.global.JSON.parse(jsonString);\r\n goog.asserts.assert(typeof obj == 'object');\r\n return /** @type {?Object} */ (obj);\r\n } catch (e) {\r\n // Native parse failed. Fall through to retry with goog.json.parse.\r\n }\r\n }\r\n\r\n return fallbackParser(jsonString);\r\n};\r\n\r\n\r\n/**\r\n * Attempts to parse the JSON string natively, falling back to\r\n * `goog.json.parse` if unsuccessful.\r\n * @param {string} jsonString JSON string to parse.\r\n * @return {?Object} Resulting JSON object.\r\n */\r\ngoog.json.hybrid.parse =\r\n goog.json.USE_NATIVE_JSON ? goog.global['JSON']['parse'] : function(\r\n jsonString) {\r\n return goog.json.hybrid.parse_(jsonString, goog.json.parse);\r\n };\r\n","// Copyright 2006 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Wrapper class for handling XmlHttpRequests.\r\n *\r\n * One off requests can be sent through goog.net.XhrIo.send() or an\r\n * instance can be created to send multiple requests. Each request uses its\r\n * own XmlHttpRequest object and handles clearing of the event callback to\r\n * ensure no leaks.\r\n *\r\n * XhrIo is event based, it dispatches events on success, failure, finishing,\r\n * ready-state change, or progress (download and upload).\r\n *\r\n * The ready-state or timeout event fires first, followed by\r\n * a generic completed event. Then the abort, error, or success event\r\n * is fired as appropriate. Progress events are fired as they are\r\n * received. Lastly, the ready event will fire to indicate that the\r\n * object may be used to make another request.\r\n *\r\n * The error event may also be called before completed and\r\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\r\n *\r\n * This class does not support multiple requests, queuing, or prioritization.\r\n *\r\n * When progress events are supported by the browser, and progress is\r\n * enabled via .setProgressEventsEnabled(true), the\r\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\r\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\r\n * will be fired for download and upload progress respectively.\r\n *\r\n */\r\n\r\n\r\ngoog.provide('goog.net.XhrIo');\r\ngoog.provide('goog.net.XhrIo.ResponseType');\r\n\r\ngoog.require('goog.Timer');\r\ngoog.require('goog.array');\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.debug.entryPointRegistry');\r\ngoog.require('goog.events.EventTarget');\r\ngoog.require('goog.json.hybrid');\r\ngoog.require('goog.log');\r\ngoog.require('goog.net.ErrorCode');\r\ngoog.require('goog.net.EventType');\r\ngoog.require('goog.net.HttpStatus');\r\ngoog.require('goog.net.XmlHttp');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.structs');\r\ngoog.require('goog.structs.Map');\r\ngoog.require('goog.uri.utils');\r\ngoog.require('goog.userAgent');\r\n\r\ngoog.forwardDeclare('goog.Uri');\r\n\r\ngoog.scope(function() {\r\n\r\n/**\r\n * Basic class for handling XMLHttpRequests.\r\n * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when\r\n * creating XMLHttpRequest objects.\r\n * @constructor\r\n * @extends {goog.events.EventTarget}\r\n */\r\ngoog.net.XhrIo = function(opt_xmlHttpFactory) {\r\n XhrIo.base(this, 'constructor');\r\n\r\n /**\r\n * Map of default headers to add to every request, use:\r\n * XhrIo.headers.set(name, value)\r\n * @type {!goog.structs.Map}\r\n */\r\n this.headers = new goog.structs.Map();\r\n\r\n /**\r\n * Optional XmlHttpFactory\r\n * @private {goog.net.XmlHttpFactory}\r\n */\r\n this.xmlHttpFactory_ = opt_xmlHttpFactory || null;\r\n\r\n /**\r\n * Whether XMLHttpRequest is active. A request is active from the time send()\r\n * is called until onReadyStateChange() is complete, or error() or abort()\r\n * is called.\r\n * @private {boolean}\r\n */\r\n this.active_ = false;\r\n\r\n /**\r\n * The XMLHttpRequest object that is being used for the transfer.\r\n * @private {?goog.net.XhrLike.OrNative}\r\n */\r\n this.xhr_ = null;\r\n\r\n /**\r\n * The options to use with the current XMLHttpRequest object.\r\n * @private {?Object}\r\n */\r\n this.xhrOptions_ = null;\r\n\r\n /**\r\n * Last URL that was requested.\r\n * @private {string|goog.Uri}\r\n */\r\n this.lastUri_ = '';\r\n\r\n /**\r\n * Method for the last request.\r\n * @private {string}\r\n */\r\n this.lastMethod_ = '';\r\n\r\n /**\r\n * Last error code.\r\n * @private {!goog.net.ErrorCode}\r\n */\r\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\r\n\r\n /**\r\n * Last error message.\r\n * @private {Error|string}\r\n */\r\n this.lastError_ = '';\r\n\r\n /**\r\n * Used to ensure that we don't dispatch an multiple ERROR events. This can\r\n * happen in IE when it does a synchronous load and one error is handled in\r\n * the ready statte change and one is handled due to send() throwing an\r\n * exception.\r\n * @private {boolean}\r\n */\r\n this.errorDispatched_ = false;\r\n\r\n /**\r\n * Used to make sure we don't fire the complete event from inside a send call.\r\n * @private {boolean}\r\n */\r\n this.inSend_ = false;\r\n\r\n /**\r\n * Used in determining if a call to {@link #onReadyStateChange_} is from\r\n * within a call to this.xhr_.open.\r\n * @private {boolean}\r\n */\r\n this.inOpen_ = false;\r\n\r\n /**\r\n * Used in determining if a call to {@link #onReadyStateChange_} is from\r\n * within a call to this.xhr_.abort.\r\n * @private {boolean}\r\n */\r\n this.inAbort_ = false;\r\n\r\n /**\r\n * Number of milliseconds after which an incomplete request will be aborted\r\n * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout\r\n * is set.\r\n * @private {number}\r\n */\r\n this.timeoutInterval_ = 0;\r\n\r\n /**\r\n * Timer to track request timeout.\r\n * @private {?number}\r\n */\r\n this.timeoutId_ = null;\r\n\r\n /**\r\n * The requested type for the response. The empty string means use the default\r\n * XHR behavior.\r\n * @private {goog.net.XhrIo.ResponseType}\r\n */\r\n this.responseType_ = ResponseType.DEFAULT;\r\n\r\n /**\r\n * Whether a \"credentialed\" request is to be sent (one that is aware of\r\n * cookies and authentication). This is applicable only for cross-domain\r\n * requests and more recent browsers that support this part of the HTTP Access\r\n * Control standard.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute\r\n *\r\n * @private {boolean}\r\n */\r\n this.withCredentials_ = false;\r\n\r\n /**\r\n * Whether progress events are enabled for this request. This is\r\n * disabled by default because setting a progress event handler\r\n * causes pre-flight OPTIONS requests to be sent for CORS requests,\r\n * even in cases where a pre-flight request would not otherwise be\r\n * sent.\r\n *\r\n * @see http://xhr.spec.whatwg.org/#security-considerations\r\n *\r\n * Note that this can cause problems for Firefox 22 and below, as an\r\n * older \"LSProgressEvent\" will be dispatched by the browser. That\r\n * progress event is no longer supported, and can lead to failures,\r\n * including throwing exceptions.\r\n *\r\n * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631\r\n * @see b/23469793\r\n *\r\n * @private {boolean}\r\n */\r\n this.progressEventsEnabled_ = false;\r\n\r\n /**\r\n * True if we can use XMLHttpRequest's timeout directly.\r\n * @private {boolean}\r\n */\r\n this.useXhr2Timeout_ = false;\r\n};\r\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\r\n\r\nvar XhrIo = goog.net.XhrIo;\r\n\r\n/**\r\n * Response types that may be requested for XMLHttpRequests.\r\n * @enum {string}\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute\r\n */\r\ngoog.net.XhrIo.ResponseType = {\r\n DEFAULT: '',\r\n TEXT: 'text',\r\n DOCUMENT: 'document',\r\n // Not supported as of Chrome 10.0.612.1 dev\r\n BLOB: 'blob',\r\n ARRAY_BUFFER: 'arraybuffer'\r\n};\r\n\r\nvar ResponseType = goog.net.XhrIo.ResponseType;\r\n\r\n\r\n/**\r\n * A reference to the XhrIo logger\r\n * @private {?goog.log.Logger}\r\n * @const\r\n */\r\ngoog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');\r\n\r\n\r\n/**\r\n * The Content-Type HTTP header name\r\n * @type {string}\r\n */\r\ngoog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';\r\n\r\n\r\n/**\r\n * The Content-Transfer-Encoding HTTP header name\r\n * @type {string}\r\n */\r\ngoog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';\r\n\r\n\r\n/**\r\n * The pattern matching the 'http' and 'https' URI schemes\r\n * @type {!RegExp}\r\n */\r\ngoog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;\r\n\r\n\r\n/**\r\n * The methods that typically come along with form data. We set different\r\n * headers depending on whether the HTTP action is one of these.\r\n * @type {!Array<string>}\r\n */\r\ngoog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];\r\n\r\n\r\n/**\r\n * The Content-Type HTTP header value for a url-encoded form\r\n * @type {string}\r\n */\r\ngoog.net.XhrIo.FORM_CONTENT_TYPE =\r\n 'application/x-www-form-urlencoded;charset=utf-8';\r\n\r\n\r\n/**\r\n * The XMLHttpRequest Level two timeout delay ms property name.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\r\n *\r\n * @private {string}\r\n * @const\r\n */\r\ngoog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';\r\n\r\n\r\n/**\r\n * The XMLHttpRequest Level two ontimeout handler property name.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\r\n *\r\n * @private {string}\r\n * @const\r\n */\r\ngoog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';\r\n\r\n\r\n/**\r\n * All non-disposed instances of goog.net.XhrIo created\r\n * by {@link goog.net.XhrIo.send} are in this Array.\r\n * @see goog.net.XhrIo.cleanup\r\n * @private {!Array<!goog.net.XhrIo>}\r\n */\r\ngoog.net.XhrIo.sendInstances_ = [];\r\n\r\n\r\n/**\r\n * Static send that creates a short lived instance of XhrIo to send the\r\n * request.\r\n * @see goog.net.XhrIo.cleanup\r\n * @param {string|goog.Uri} url Uri to make request to.\r\n * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function\r\n * for when request is complete.\r\n * @param {string=} opt_method Send method, default: GET.\r\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\r\n * opt_content Body data.\r\n * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the\r\n * request.\r\n * @param {number=} opt_timeoutInterval Number of milliseconds after which an\r\n * incomplete request will be aborted; 0 means no timeout is set.\r\n * @param {boolean=} opt_withCredentials Whether to send credentials with the\r\n * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.\r\n * @return {!goog.net.XhrIo} The sent XhrIo.\r\n */\r\ngoog.net.XhrIo.send = function(\r\n url, opt_callback, opt_method, opt_content, opt_headers,\r\n opt_timeoutInterval, opt_withCredentials) {\r\n var x = new goog.net.XhrIo();\r\n goog.net.XhrIo.sendInstances_.push(x);\r\n if (opt_callback) {\r\n x.listen(goog.net.EventType.COMPLETE, opt_callback);\r\n }\r\n x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);\r\n if (opt_timeoutInterval) {\r\n x.setTimeoutInterval(opt_timeoutInterval);\r\n }\r\n if (opt_withCredentials) {\r\n x.setWithCredentials(opt_withCredentials);\r\n }\r\n x.send(url, opt_method, opt_content, opt_headers);\r\n return x;\r\n};\r\n\r\n\r\n/**\r\n * Disposes all non-disposed instances of goog.net.XhrIo created by\r\n * {@link goog.net.XhrIo.send}.\r\n * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance\r\n * it creates when the request completes or fails. However, if\r\n * the request never completes, then the goog.net.XhrIo is not disposed.\r\n * This can occur if the window is unloaded before the request completes.\r\n * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo\r\n * it creates and make the client of {@link goog.net.XhrIo.send} be\r\n * responsible for disposing it in this case. However, this makes things\r\n * significantly more complicated for the client, and the whole point\r\n * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.\r\n * Clients of {@link goog.net.XhrIo.send} should call\r\n * {@link goog.net.XhrIo.cleanup} when doing final\r\n * cleanup on window unload.\r\n */\r\ngoog.net.XhrIo.cleanup = function() {\r\n var instances = goog.net.XhrIo.sendInstances_;\r\n while (instances.length) {\r\n instances.pop().dispose();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Installs exception protection for all entry point introduced by\r\n * goog.net.XhrIo instances which are not protected by\r\n * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},\r\n * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or\r\n * {@link goog.events.protectBrowserEventEntryPoint}.\r\n *\r\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\r\n * protect the entry point(s).\r\n */\r\ngoog.net.XhrIo.protectEntryPoints = function(errorHandler) {\r\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\r\n errorHandler.protectEntryPoint(\r\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\r\n};\r\n\r\n\r\n/**\r\n * Disposes of the specified goog.net.XhrIo created by\r\n * {@link goog.net.XhrIo.send} and removes it from\r\n * {@link goog.net.XhrIo.pendingStaticSendInstances_}.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.cleanupSend_ = function() {\r\n this.dispose();\r\n goog.array.remove(goog.net.XhrIo.sendInstances_, this);\r\n};\r\n\r\n\r\n/**\r\n * Returns the number of milliseconds after which an incomplete request will be\r\n * aborted, or 0 if no timeout is set.\r\n * @return {number} Timeout interval in milliseconds.\r\n */\r\ngoog.net.XhrIo.prototype.getTimeoutInterval = function() {\r\n return this.timeoutInterval_;\r\n};\r\n\r\n\r\n/**\r\n * Sets the number of milliseconds after which an incomplete request will be\r\n * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no\r\n * timeout is set.\r\n * @param {number} ms Timeout interval in milliseconds; 0 means none.\r\n */\r\ngoog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {\r\n this.timeoutInterval_ = Math.max(0, ms);\r\n};\r\n\r\n\r\n/**\r\n * Sets the desired type for the response. At time of writing, this is only\r\n * supported in very recent versions of WebKit (10.0.612.1 dev and later).\r\n *\r\n * If this is used, the response may only be accessed via {@link #getResponse}.\r\n *\r\n * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.\r\n */\r\ngoog.net.XhrIo.prototype.setResponseType = function(type) {\r\n this.responseType_ = type;\r\n};\r\n\r\n\r\n/**\r\n * Gets the desired type for the response.\r\n * @return {goog.net.XhrIo.ResponseType} The desired type for the response.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseType = function() {\r\n return this.responseType_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether a \"credentialed\" request that is aware of cookie and\r\n * authentication information should be made. This option is only supported by\r\n * browsers that support HTTP Access Control. As of this writing, this option\r\n * is not supported in IE.\r\n *\r\n * @param {boolean} withCredentials Whether this should be a \"credentialed\"\r\n * request.\r\n */\r\ngoog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {\r\n this.withCredentials_ = withCredentials;\r\n};\r\n\r\n\r\n/**\r\n * Gets whether a \"credentialed\" request is to be sent.\r\n * @return {boolean} The desired type for the response.\r\n */\r\ngoog.net.XhrIo.prototype.getWithCredentials = function() {\r\n return this.withCredentials_;\r\n};\r\n\r\n\r\n/**\r\n * Sets whether progress events are enabled for this request. Note\r\n * that progress events require pre-flight OPTIONS request handling\r\n * for CORS requests, and may cause trouble with older browsers. See\r\n * progressEventsEnabled_ for details.\r\n * @param {boolean} enabled Whether progress events should be enabled.\r\n */\r\ngoog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {\r\n this.progressEventsEnabled_ = enabled;\r\n};\r\n\r\n\r\n/**\r\n * Gets whether progress events are enabled.\r\n * @return {boolean} Whether progress events are enabled for this request.\r\n */\r\ngoog.net.XhrIo.prototype.getProgressEventsEnabled = function() {\r\n return this.progressEventsEnabled_;\r\n};\r\n\r\n\r\n/**\r\n * Instance send that actually uses XMLHttpRequest to make a server call.\r\n * @param {string|goog.Uri} url Uri to make request to.\r\n * @param {string=} opt_method Send method, default: GET.\r\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\r\n * opt_content Body data.\r\n * @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the\r\n * request.\r\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\r\n * types of parameters for opt_headers.\r\n */\r\ngoog.net.XhrIo.prototype.send = function(\r\n url, opt_method, opt_content, opt_headers) {\r\n if (this.xhr_) {\r\n throw new Error(\r\n '[goog.net.XhrIo] Object is active with another request=' +\r\n this.lastUri_ + '; newUri=' + url);\r\n }\r\n\r\n var method = opt_method ? opt_method.toUpperCase() : 'GET';\r\n\r\n this.lastUri_ = url;\r\n this.lastError_ = '';\r\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\r\n this.lastMethod_ = method;\r\n this.errorDispatched_ = false;\r\n this.active_ = true;\r\n\r\n // Use the factory to create the XHR object and options\r\n this.xhr_ = this.createXhr();\r\n this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :\r\n goog.net.XmlHttp.getOptions();\r\n\r\n // Set up the onreadystatechange callback\r\n this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);\r\n\r\n // Set up upload/download progress events, if progress events are supported.\r\n if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {\r\n this.xhr_.onprogress =\r\n goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);\r\n if (this.xhr_.upload) {\r\n this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);\r\n }\r\n }\r\n\r\n /**\r\n * Try to open the XMLHttpRequest (always async), if an error occurs here it\r\n * is generally permission denied\r\n */\r\n try {\r\n goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));\r\n this.inOpen_ = true;\r\n this.xhr_.open(method, String(url), true); // Always async!\r\n this.inOpen_ = false;\r\n } catch (err) {\r\n goog.log.fine(\r\n this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));\r\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\r\n return;\r\n }\r\n\r\n // We can't use null since this won't allow requests with form data to have a\r\n // content length specified which will cause some proxies to return a 411\r\n // error.\r\n var content = opt_content || '';\r\n\r\n var headers = this.headers.clone();\r\n\r\n // Add headers specific to this request\r\n if (opt_headers) {\r\n goog.structs.forEach(\r\n opt_headers, function(value, key) { headers.set(key, value); });\r\n }\r\n\r\n // Find whether a content type header is set, ignoring case.\r\n // HTTP header names are case-insensitive. See:\r\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\r\n var contentTypeKey =\r\n goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);\r\n\r\n var contentIsFormData =\r\n (goog.global['FormData'] && (content instanceof goog.global['FormData']));\r\n if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&\r\n !contentTypeKey && !contentIsFormData) {\r\n // For requests typically with form data, default to the url-encoded form\r\n // content type unless this is a FormData request. For FormData,\r\n // the browser will automatically add a multipart/form-data content type\r\n // with an appropriate multipart boundary.\r\n headers.set(\r\n goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);\r\n }\r\n\r\n // Add the headers to the Xhr object\r\n headers.forEach(function(value, key) {\r\n this.xhr_.setRequestHeader(key, value);\r\n }, this);\r\n\r\n if (this.responseType_) {\r\n this.xhr_.responseType = this.responseType_;\r\n }\r\n // Set xhr_.withCredentials only when the value is different, or else in\r\n // synchronous XMLHtppRequest.open Firefox will throw an exception.\r\n // https://bugzilla.mozilla.org/show_bug.cgi?id=736340\r\n if ('withCredentials' in this.xhr_ &&\r\n this.xhr_.withCredentials !== this.withCredentials_) {\r\n this.xhr_.withCredentials = this.withCredentials_;\r\n }\r\n\r\n /**\r\n * Try to send the request, or other wise report an error (404 not found).\r\n */\r\n try {\r\n this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.\r\n if (this.timeoutInterval_ > 0) {\r\n this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);\r\n goog.log.fine(\r\n this.logger_, this.formatMsg_(\r\n 'Will abort after ' + this.timeoutInterval_ +\r\n 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));\r\n if (this.useXhr2Timeout_) {\r\n this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;\r\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =\r\n goog.bind(this.timeout_, this);\r\n } else {\r\n this.timeoutId_ =\r\n goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);\r\n }\r\n }\r\n goog.log.fine(this.logger_, this.formatMsg_('Sending request'));\r\n this.inSend_ = true;\r\n this.xhr_.send(content);\r\n this.inSend_ = false;\r\n\r\n } catch (err) {\r\n goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));\r\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Determines if the argument is an XMLHttpRequest that supports the level 2\r\n * timeout value and event.\r\n *\r\n * Currently, FF 21.0 OS X has the fields but won't actually call the timeout\r\n * handler. Perhaps the confusion in the bug referenced below hasn't\r\n * entirely been resolved.\r\n *\r\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\r\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816\r\n *\r\n * @param {!goog.net.XhrLike.OrNative} xhr The request.\r\n * @return {boolean} True if the request supports level 2 timeout.\r\n * @private\r\n */\r\ngoog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {\r\n return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&\r\n goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&\r\n goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);\r\n};\r\n\r\n\r\n/**\r\n * @param {string} header An HTTP header key.\r\n * @return {boolean} Whether the key is a content type header (ignoring\r\n * case.\r\n * @private\r\n */\r\ngoog.net.XhrIo.isContentTypeHeader_ = function(header) {\r\n return goog.string.caseInsensitiveEquals(\r\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header);\r\n};\r\n\r\n\r\n/**\r\n * Creates a new XHR object.\r\n * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.\r\n * @protected\r\n */\r\ngoog.net.XhrIo.prototype.createXhr = function() {\r\n return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :\r\n goog.net.XmlHttp();\r\n};\r\n\r\n\r\n/**\r\n * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}\r\n * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts\r\n * the request.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.timeout_ = function() {\r\n if (typeof goog == 'undefined') {\r\n // If goog is undefined then the callback has occurred as the application\r\n // is unloading and will error. Thus we let it silently fail.\r\n } else if (this.xhr_) {\r\n this.lastError_ =\r\n 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';\r\n this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;\r\n goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));\r\n this.dispatchEvent(goog.net.EventType.TIMEOUT);\r\n this.abort(goog.net.ErrorCode.TIMEOUT);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Something errorred, so inactivate, fire error callback and clean up\r\n * @param {goog.net.ErrorCode} errorCode The error code.\r\n * @param {Error} err The error object.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.error_ = function(errorCode, err) {\r\n this.active_ = false;\r\n if (this.xhr_) {\r\n this.inAbort_ = true;\r\n this.xhr_.abort(); // Ensures XHR isn't hung (FF)\r\n this.inAbort_ = false;\r\n }\r\n this.lastError_ = err;\r\n this.lastErrorCode_ = errorCode;\r\n this.dispatchErrors_();\r\n this.cleanUpXhr_();\r\n};\r\n\r\n\r\n/**\r\n * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do\r\n * not dispatch multiple error events.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.dispatchErrors_ = function() {\r\n if (!this.errorDispatched_) {\r\n this.errorDispatched_ = true;\r\n this.dispatchEvent(goog.net.EventType.COMPLETE);\r\n this.dispatchEvent(goog.net.EventType.ERROR);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Abort the current XMLHttpRequest\r\n * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -\r\n * defaults to ABORT.\r\n */\r\ngoog.net.XhrIo.prototype.abort = function(opt_failureCode) {\r\n if (this.xhr_ && this.active_) {\r\n goog.log.fine(this.logger_, this.formatMsg_('Aborting'));\r\n this.active_ = false;\r\n this.inAbort_ = true;\r\n this.xhr_.abort();\r\n this.inAbort_ = false;\r\n this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;\r\n this.dispatchEvent(goog.net.EventType.COMPLETE);\r\n this.dispatchEvent(goog.net.EventType.ABORT);\r\n this.cleanUpXhr_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Nullifies all callbacks to reduce risks of leaks.\r\n * @override\r\n * @protected\r\n */\r\ngoog.net.XhrIo.prototype.disposeInternal = function() {\r\n if (this.xhr_) {\r\n // We explicitly do not call xhr_.abort() unless active_ is still true.\r\n // This is to avoid unnecessarily aborting a successful request when\r\n // dispose() is called in a callback triggered by a complete response, but\r\n // in which browser cleanup has not yet finished.\r\n // (See http://b/issue?id=1684217.)\r\n if (this.active_) {\r\n this.active_ = false;\r\n this.inAbort_ = true;\r\n this.xhr_.abort();\r\n this.inAbort_ = false;\r\n }\r\n this.cleanUpXhr_(true);\r\n }\r\n\r\n XhrIo.base(this, 'disposeInternal');\r\n};\r\n\r\n\r\n/**\r\n * Internal handler for the XHR object's readystatechange event. This method\r\n * checks the status and the readystate and fires the correct callbacks.\r\n * If the request has ended, the handlers are cleaned up and the XHR object is\r\n * nullified.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onReadyStateChange_ = function() {\r\n if (this.isDisposed()) {\r\n // This method is the target of an untracked goog.Timer.callOnce().\r\n return;\r\n }\r\n if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {\r\n // Were not being called from within a call to this.xhr_.send\r\n // this.xhr_.abort, or this.xhr_.open, so this is an entry point\r\n this.onReadyStateChangeEntryPoint_();\r\n } else {\r\n this.onReadyStateChangeHelper_();\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Used to protect the onreadystatechange handler entry point. Necessary\r\n * as {#onReadyStateChange_} maybe called from within send or abort, this\r\n * method is only called when {#onReadyStateChange_} is called as an\r\n * entry point.\r\n * {@see #protectEntryPoints}\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {\r\n this.onReadyStateChangeHelper_();\r\n};\r\n\r\n\r\n/**\r\n * Helper for {@link #onReadyStateChange_}. This is used so that\r\n * entry point calls to {@link #onReadyStateChange_} can be routed through\r\n * {@link #onReadyStateChangeEntryPoint_}.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {\r\n if (!this.active_) {\r\n // can get called inside abort call\r\n return;\r\n }\r\n\r\n if (typeof goog == 'undefined') {\r\n // NOTE(user): If goog is undefined then the callback has occurred as the\r\n // application is unloading and will error. Thus we let it silently fail.\r\n\r\n } else if (\r\n this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&\r\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&\r\n this.getStatus() == 2) {\r\n // NOTE(user): In IE if send() errors on a *local* request the readystate\r\n // is still changed to COMPLETE. We need to ignore it and allow the\r\n // try/catch around send() to pick up the error.\r\n goog.log.fine(\r\n this.logger_,\r\n this.formatMsg_('Local request error detected and ignored'));\r\n\r\n } else {\r\n // In IE when the response has been cached we sometimes get the callback\r\n // from inside the send call and this usually breaks code that assumes that\r\n // XhrIo is asynchronous. If that is the case we delay the callback\r\n // using a timer.\r\n if (this.inSend_ &&\r\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {\r\n goog.Timer.callOnce(this.onReadyStateChange_, 0, this);\r\n return;\r\n }\r\n\r\n this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);\r\n\r\n // readyState indicates the transfer has finished\r\n if (this.isComplete()) {\r\n goog.log.fine(this.logger_, this.formatMsg_('Request complete'));\r\n\r\n this.active_ = false;\r\n\r\n try {\r\n // Call the specific callbacks for success or failure. Only call the\r\n // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)\r\n if (this.isSuccess()) {\r\n this.dispatchEvent(goog.net.EventType.COMPLETE);\r\n this.dispatchEvent(goog.net.EventType.SUCCESS);\r\n } else {\r\n this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;\r\n this.lastError_ =\r\n this.getStatusText() + ' [' + this.getStatus() + ']';\r\n this.dispatchErrors_();\r\n }\r\n } finally {\r\n this.cleanUpXhr_();\r\n }\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Internal handler for the XHR object's onprogress event. Fires both a generic\r\n * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to\r\n * allow specific binding for each XHR progress event.\r\n * @param {!ProgressEvent} e XHR progress event.\r\n * @param {boolean=} opt_isDownload Whether the current progress event is from a\r\n * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS\r\n * event should be dispatched.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {\r\n goog.asserts.assert(\r\n e.type === goog.net.EventType.PROGRESS,\r\n 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');\r\n this.dispatchEvent(\r\n goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));\r\n this.dispatchEvent(\r\n goog.net.XhrIo.buildProgressEvent_(\r\n e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :\r\n goog.net.EventType.UPLOAD_PROGRESS));\r\n};\r\n\r\n\r\n/**\r\n * Creates a representation of the native ProgressEvent. IE doesn't support\r\n * constructing ProgressEvent via \"new\", and the alternatives (e.g.,\r\n * ProgressEvent.initProgressEvent) are non-standard or deprecated.\r\n * @param {!ProgressEvent} e XHR progress event.\r\n * @param {!goog.net.EventType} eventType The type of the event.\r\n * @return {!ProgressEvent} The progress event.\r\n * @private\r\n */\r\ngoog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {\r\n return /** @type {!ProgressEvent} */ ({\r\n type: eventType,\r\n lengthComputable: e.lengthComputable,\r\n loaded: e.loaded,\r\n total: e.total\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Remove the listener to protect against leaks, and nullify the XMLHttpRequest\r\n * object.\r\n * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to\r\n * fire any events).\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {\r\n if (this.xhr_) {\r\n // Cancel any pending timeout event handler.\r\n this.cleanUpTimeoutTimer_();\r\n\r\n // Save reference so we can mark it as closed after the READY event. The\r\n // READY event may trigger another request, thus we must nullify this.xhr_\r\n var xhr = this.xhr_;\r\n var clearedOnReadyStateChange =\r\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\r\n goog.nullFunction :\r\n null;\r\n this.xhr_ = null;\r\n this.xhrOptions_ = null;\r\n\r\n if (!opt_fromDispose) {\r\n this.dispatchEvent(goog.net.EventType.READY);\r\n }\r\n\r\n try {\r\n // NOTE(user): Not nullifying in FireFox can still leak if the callbacks\r\n // are defined in the same scope as the instance of XhrIo. But, IE doesn't\r\n // allow you to set the onreadystatechange to NULL so nullFunction is\r\n // used.\r\n xhr.onreadystatechange = clearedOnReadyStateChange;\r\n } catch (e) {\r\n // This seems to occur with a Gears HTTP request. Delayed the setting of\r\n // this onreadystatechange until after READY is sent out and catching the\r\n // error to see if we can track down the problem.\r\n goog.log.error(\r\n this.logger_,\r\n 'Problem encountered resetting onreadystatechange: ' + e.message);\r\n }\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Make sure the timeout timer isn't running.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {\r\n if (this.xhr_ && this.useXhr2Timeout_) {\r\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;\r\n }\r\n if (this.timeoutId_) {\r\n goog.Timer.clear(this.timeoutId_);\r\n this.timeoutId_ = null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether there is an active request.\r\n */\r\ngoog.net.XhrIo.prototype.isActive = function() {\r\n return !!this.xhr_;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the request has completed.\r\n */\r\ngoog.net.XhrIo.prototype.isComplete = function() {\r\n return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} Whether the request completed with a success.\r\n */\r\ngoog.net.XhrIo.prototype.isSuccess = function() {\r\n var status = this.getStatus();\r\n // A zero status code is considered successful for local files.\r\n return goog.net.HttpStatus.isSuccess(status) ||\r\n status === 0 && !this.isLastUriEffectiveSchemeHttp_();\r\n};\r\n\r\n\r\n/**\r\n * @return {boolean} whether the effective scheme of the last URI that was\r\n * fetched was 'http' or 'https'.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {\r\n var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\r\n return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);\r\n};\r\n\r\n\r\n/**\r\n * Get the readystate from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.\r\n */\r\ngoog.net.XhrIo.prototype.getReadyState = function() {\r\n return this.xhr_ ?\r\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\r\n goog.net.XmlHttp.ReadyState\r\n .UNINITIALIZED;\r\n};\r\n\r\n\r\n/**\r\n * Get the status from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @return {number} Http status.\r\n */\r\ngoog.net.XhrIo.prototype.getStatus = function() {\r\n /**\r\n * IE doesn't like you checking status until the readystate is greater than 2\r\n * (i.e. it is receiving or complete). The try/catch is used for when the\r\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\r\n */\r\n try {\r\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\r\n this.xhr_.status :\r\n -1;\r\n } catch (e) {\r\n return -1;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the status text from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @return {string} Status text.\r\n */\r\ngoog.net.XhrIo.prototype.getStatusText = function() {\r\n /**\r\n * IE doesn't like you checking status until the readystate is greater than 2\r\n * (i.e. it is receiving or complete). The try/catch is used for when the\r\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\r\n */\r\n try {\r\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\r\n this.xhr_.statusText :\r\n '';\r\n } catch (e) {\r\n goog.log.fine(this.logger_, 'Can not get status: ' + e.message);\r\n return '';\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the last Uri that was requested\r\n * @return {string} Last Uri.\r\n */\r\ngoog.net.XhrIo.prototype.getLastUri = function() {\r\n return String(this.lastUri_);\r\n};\r\n\r\n\r\n/**\r\n * Get the response text from the Xhr object\r\n * Will only return correct result when called from the context of a callback.\r\n * @return {string} Result from the server, or '' if no result available.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseText = function() {\r\n try {\r\n return this.xhr_ ? this.xhr_.responseText : '';\r\n } catch (e) {\r\n // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute\r\n // states that responseText should return '' (and responseXML null)\r\n // when the state is not LOADING or DONE. Instead, IE can\r\n // throw unexpected exceptions, for example when a request is aborted\r\n // or no data is available yet.\r\n goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);\r\n return '';\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the response body from the Xhr object. This property is only available\r\n * in IE since version 7 according to MSDN:\r\n * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx\r\n * Will only return correct result when called from the context of a callback.\r\n *\r\n * One option is to construct a VBArray from the returned object and convert\r\n * it to a JavaScript array using the toArray method:\r\n * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`\r\n * This will result in an array of numbers in the range of [0..255]\r\n *\r\n * Another option is to use the VBScript CStr method to convert it into a\r\n * string as outlined in http://stackoverflow.com/questions/1919972\r\n *\r\n * @return {Object} Binary result from the server or null if not available.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseBody = function() {\r\n try {\r\n if (this.xhr_ && 'responseBody' in this.xhr_) {\r\n return this.xhr_['responseBody'];\r\n }\r\n } catch (e) {\r\n // IE can throw unexpected exceptions, for example when a request is aborted\r\n // or no data is yet available.\r\n goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);\r\n }\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * Get the response XML from the Xhr object\r\n * Will only return correct result when called from the context of a callback.\r\n * @return {Document} The DOM Document representing the XML file, or null\r\n * if no result available.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseXml = function() {\r\n try {\r\n return this.xhr_ ? this.xhr_.responseXML : null;\r\n } catch (e) {\r\n goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);\r\n return null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the response and evaluates it as JSON from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for\r\n * stripping of the response before parsing. This needs to be set only if\r\n * your backend server prepends the same prefix string to the JSON response.\r\n * @throws Error if the response text is invalid JSON.\r\n * @return {Object|undefined} JavaScript object.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {\r\n if (!this.xhr_) {\r\n return undefined;\r\n }\r\n\r\n var responseText = this.xhr_.responseText;\r\n if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {\r\n responseText = responseText.substring(opt_xssiPrefix.length);\r\n }\r\n\r\n return goog.json.hybrid.parse(responseText);\r\n};\r\n\r\n\r\n/**\r\n * Get the response as the type specificed by {@link #setResponseType}. At time\r\n * of writing, this is only directly supported in very recent versions of WebKit\r\n * (10.0.612.1 dev and later). If the field is not supported directly, we will\r\n * try to emulate it.\r\n *\r\n * Emulating the response means following the rules laid out at\r\n * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute\r\n *\r\n * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only\r\n * response types of DEFAULT or TEXT may be used, and the response returned will\r\n * be the text response.\r\n *\r\n * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),\r\n * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the\r\n * response returned will be either the text response or the Mozilla\r\n * implementation of the array buffer response.\r\n *\r\n * On browsers will full support, any valid response type supported by the\r\n * browser may be used, and the response provided by the browser will be\r\n * returned.\r\n *\r\n * @return {*} The response.\r\n */\r\ngoog.net.XhrIo.prototype.getResponse = function() {\r\n try {\r\n if (!this.xhr_) {\r\n return null;\r\n }\r\n if ('response' in this.xhr_) {\r\n return this.xhr_.response;\r\n }\r\n switch (this.responseType_) {\r\n case ResponseType.DEFAULT:\r\n case ResponseType.TEXT:\r\n return this.xhr_.responseText;\r\n // DOCUMENT and BLOB don't need to be handled here because they are\r\n // introduced in the same spec that adds the .response field, and would\r\n // have been caught above.\r\n // ARRAY_BUFFER needs an implementation for Firefox 4, where it was\r\n // implemented using a draft spec rather than the final spec.\r\n case ResponseType.ARRAY_BUFFER:\r\n if ('mozResponseArrayBuffer' in this.xhr_) {\r\n return this.xhr_.mozResponseArrayBuffer;\r\n }\r\n }\r\n // Fell through to a response type that is not supported on this browser.\r\n goog.log.error(\r\n this.logger_, 'Response type ' + this.responseType_ + ' is not ' +\r\n 'supported on this browser');\r\n return null;\r\n } catch (e) {\r\n goog.log.fine(this.logger_, 'Can not get response: ' + e.message);\r\n return null;\r\n }\r\n};\r\n\r\n\r\n/**\r\n * Get the value of the response-header with the given name from the Xhr object\r\n * Will only return correct result when called from the context of a callback\r\n * and the request has completed\r\n * @param {string} key The name of the response-header to retrieve.\r\n * @return {string|undefined} The value of the response-header named key.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseHeader = function(key) {\r\n if (!this.xhr_ || !this.isComplete()) {\r\n return undefined;\r\n }\r\n\r\n var value = this.xhr_.getResponseHeader(key);\r\n return goog.isNull(value) ? undefined : value;\r\n};\r\n\r\n\r\n/**\r\n * Gets the text of all the headers in the response.\r\n * Will only return correct result when called from the context of a callback\r\n * and the request has completed.\r\n * @return {string} The value of the response headers or empty string.\r\n */\r\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\r\n // getAllResponseHeaders can return null if no response has been received,\r\n // ensure we always return an empty string.\r\n return this.xhr_ && this.isComplete() ?\r\n (this.xhr_.getAllResponseHeaders() || '') :\r\n '';\r\n};\r\n\r\n\r\n/**\r\n * Returns all response headers as a key-value map.\r\n * Multiple values for the same header key can be combined into one,\r\n * separated by a comma and a space.\r\n * Note that the native getResponseHeader method for retrieving a single header\r\n * does a case insensitive match on the header name. This method does not\r\n * include any case normalization logic, it will just return a key-value\r\n * representation of the headers.\r\n * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method\r\n * @return {!Object<string, string>} An object with the header keys as keys\r\n * and header values as values.\r\n */\r\ngoog.net.XhrIo.prototype.getResponseHeaders = function() {\r\n // TODO(b/120371595): Make this function parse headers as per the spec\r\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\r\n\r\n var headersObject = {};\r\n var headersArray = this.getAllResponseHeaders().split('\\r\\n');\r\n for (var i = 0; i < headersArray.length; i++) {\r\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\r\n continue;\r\n }\r\n var keyValue =\r\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\r\n var key = keyValue[0];\r\n var value = keyValue[1];\r\n\r\n if (!goog.isString(value)) {\r\n // There must be a value but it can be the empty string.\r\n continue;\r\n }\r\n\r\n // Whitespace at the start and end of the value is meaningless.\r\n value = value.trim();\r\n // The key should not contain whitespace but we currently ignore that.\r\n\r\n var values = headersObject[key] || [];\r\n headersObject[key] = values;\r\n values.push(value);\r\n }\r\n\r\n return goog.object.map(headersObject, function(values) {\r\n return values.join(', ');\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Get the value of the response-header with the given name from the Xhr object.\r\n * As opposed to {@link #getResponseHeader}, this method does not require that\r\n * the request has completed.\r\n * @param {string} key The name of the response-header to retrieve.\r\n * @return {?string} The value of the response-header, or null if it is\r\n * unavailable.\r\n */\r\ngoog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {\r\n return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;\r\n};\r\n\r\n\r\n/**\r\n * Gets the text of all the headers in the response. As opposed to\r\n * {@link #getAllResponseHeaders}, this method does not require that the request\r\n * has completed.\r\n * @return {string} The value of the response headers or empty string.\r\n */\r\ngoog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {\r\n return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';\r\n};\r\n\r\n\r\n/**\r\n * Get the last error message\r\n * @return {!goog.net.ErrorCode} Last error code.\r\n */\r\ngoog.net.XhrIo.prototype.getLastErrorCode = function() {\r\n return this.lastErrorCode_;\r\n};\r\n\r\n\r\n/**\r\n * Get the last error message\r\n * @return {string} Last error message.\r\n */\r\ngoog.net.XhrIo.prototype.getLastError = function() {\r\n return goog.isString(this.lastError_) ? this.lastError_ :\r\n String(this.lastError_);\r\n};\r\n\r\n\r\n/**\r\n * Adds the last method, status and URI to the message. This is used to add\r\n * this information to the logging calls.\r\n * @param {string} msg The message text that we want to add the extra text to.\r\n * @return {string} The message with the extra text appended.\r\n * @private\r\n */\r\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\r\n return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +\r\n this.getStatus() + ']';\r\n};\r\n\r\n\r\n// Register the xhr handler as an entry point, so that\r\n// it can be monitored for exception handling, etc.\r\ngoog.debug.entryPointRegistry.register(\r\n /**\r\n * @param {function(!Function): !Function} transformer The transforming\r\n * function.\r\n */\r\n function(transformer) {\r\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\r\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\r\n });\r\n}); // goog.scope\r\n","// Copyright 2011 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Constants for HTTP status codes.\r\n */\r\n\r\ngoog.provide('goog.net.HttpStatus');\r\n\r\n\r\n/**\r\n * HTTP Status Codes defined in RFC 2616, RFC 6585, RFC 4918 and RFC 7538.\r\n * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\r\n * @see http://tools.ietf.org/html/rfc6585\r\n * @see https://tools.ietf.org/html/rfc4918\r\n * @see https://tools.ietf.org/html/rfc7538\r\n * @enum {number}\r\n */\r\ngoog.net.HttpStatus = {\r\n // Informational 1xx\r\n CONTINUE: 100,\r\n SWITCHING_PROTOCOLS: 101,\r\n\r\n // Successful 2xx\r\n OK: 200,\r\n CREATED: 201,\r\n ACCEPTED: 202,\r\n NON_AUTHORITATIVE_INFORMATION: 203,\r\n NO_CONTENT: 204,\r\n RESET_CONTENT: 205,\r\n PARTIAL_CONTENT: 206,\r\n MULTI_STATUS: 207,\r\n\r\n // Redirection 3xx\r\n MULTIPLE_CHOICES: 300,\r\n MOVED_PERMANENTLY: 301,\r\n FOUND: 302,\r\n SEE_OTHER: 303,\r\n NOT_MODIFIED: 304,\r\n USE_PROXY: 305,\r\n TEMPORARY_REDIRECT: 307,\r\n PERMANENT_REDIRECT: 308,\r\n\r\n // Client Error 4xx\r\n BAD_REQUEST: 400,\r\n UNAUTHORIZED: 401,\r\n PAYMENT_REQUIRED: 402,\r\n FORBIDDEN: 403,\r\n NOT_FOUND: 404,\r\n METHOD_NOT_ALLOWED: 405,\r\n NOT_ACCEPTABLE: 406,\r\n PROXY_AUTHENTICATION_REQUIRED: 407,\r\n REQUEST_TIMEOUT: 408,\r\n CONFLICT: 409,\r\n GONE: 410,\r\n LENGTH_REQUIRED: 411,\r\n PRECONDITION_FAILED: 412,\r\n REQUEST_ENTITY_TOO_LARGE: 413,\r\n REQUEST_URI_TOO_LONG: 414,\r\n UNSUPPORTED_MEDIA_TYPE: 415,\r\n REQUEST_RANGE_NOT_SATISFIABLE: 416,\r\n EXPECTATION_FAILED: 417,\r\n UNPROCESSABLE_ENTITY: 422,\r\n LOCKED: 423,\r\n FAILED_DEPENDENCY: 424,\r\n PRECONDITION_REQUIRED: 428,\r\n TOO_MANY_REQUESTS: 429,\r\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\r\n\r\n // Server Error 5xx\r\n INTERNAL_SERVER_ERROR: 500,\r\n NOT_IMPLEMENTED: 501,\r\n BAD_GATEWAY: 502,\r\n SERVICE_UNAVAILABLE: 503,\r\n GATEWAY_TIMEOUT: 504,\r\n HTTP_VERSION_NOT_SUPPORTED: 505,\r\n INSUFFICIENT_STORAGE: 507,\r\n NETWORK_AUTHENTICATION_REQUIRED: 511,\r\n\r\n /*\r\n * IE returns this code for 204 due to its use of URLMon, which returns this\r\n * code for 'Operation Aborted'. The status text is 'Unknown', the response\r\n * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.\r\n */\r\n QUIRK_IE_NO_CONTENT: 1223\r\n};\r\n\r\n\r\n/**\r\n * Returns whether the given status should be considered successful.\r\n *\r\n * Successful codes are OK (200), CREATED (201), ACCEPTED (202),\r\n * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),\r\n * and IE's no content code (1223).\r\n *\r\n * @param {number} status The status code to test.\r\n * @return {boolean} Whether the status code should be considered successful.\r\n */\r\ngoog.net.HttpStatus.isSuccess = function(status) {\r\n switch (status) {\r\n case goog.net.HttpStatus.OK:\r\n case goog.net.HttpStatus.CREATED:\r\n case goog.net.HttpStatus.ACCEPTED:\r\n case goog.net.HttpStatus.NO_CONTENT:\r\n case goog.net.HttpStatus.PARTIAL_CONTENT:\r\n case goog.net.HttpStatus.NOT_MODIFIED:\r\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\r\n return true;\r\n\r\n default:\r\n return false;\r\n }\r\n};\r\n","// Copyright 2017 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Provides CORS support for HTTP based RPC requests.\r\n *\r\n * As part of net.rpc package, CORS features provided by this class\r\n * depend on the server support. Please check related specs to decide how\r\n * to enable any of the features provided by this class.\r\n *\r\n */\r\n\r\ngoog.module('goog.net.rpc.HttpCors');\r\n\r\nvar GoogUri = goog.require('goog.Uri');\r\nvar googObject = goog.require('goog.object');\r\nvar googString = goog.require('goog.string');\r\nvar googUriUtils = goog.require('goog.uri.utils');\r\n\r\n\r\n/**\r\n * The default URL parameter name to overwrite http headers with a URL param\r\n * to avoid CORS preflight.\r\n *\r\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\r\n *\r\n * @type {string}\r\n */\r\nexports.HTTP_HEADERS_PARAM_NAME = '$httpHeaders';\r\n\r\n\r\n/**\r\n * The default URL parameter name to overwrite http method with a URL param\r\n * to avoid CORS preflight.\r\n *\r\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\r\n *\r\n * @type {string}\r\n */\r\nexports.HTTP_METHOD_PARAM_NAME = '$httpMethod';\r\n\r\n\r\n/**\r\n * Generates the URL parameter value with custom headers encoded as\r\n * HTTP/1.1 headers block.\r\n *\r\n * @param {!Object<string, string>} headers The custom headers.\r\n * @return {string} The URL param to overwrite custom HTTP headers.\r\n */\r\nexports.generateHttpHeadersOverwriteParam = function(headers) {\r\n var result = '';\r\n googObject.forEach(headers, function(value, key) {\r\n result += key;\r\n result += ':';\r\n result += value;\r\n result += '\\r\\n';\r\n });\r\n return result;\r\n};\r\n\r\n\r\n/**\r\n * Generates the URL-encoded URL parameter value with custom headers encoded as\r\n * HTTP/1.1 headers block.\r\n *\r\n * @param {!Object<string, string>} headers The custom headers.\r\n * @return {string} The URL param to overwrite custom HTTP headers.\r\n */\r\nexports.generateEncodedHttpHeadersOverwriteParam = function(headers) {\r\n return googString.urlEncode(\r\n exports.generateHttpHeadersOverwriteParam(headers));\r\n};\r\n\r\n\r\n/**\r\n * Sets custom HTTP headers via an overwrite URL param.\r\n *\r\n * @param {!GoogUri|string} url The URI object or a string path.\r\n * @param {string} urlParam The URL param name.\r\n * @param {!Object<string, string>} extraHeaders The HTTP headers.\r\n * @return {!GoogUri|string} The URI object or a string path with headers\r\n * encoded as a url param.\r\n */\r\nexports.setHttpHeadersWithOverwriteParam = function(\r\n url, urlParam, extraHeaders) {\r\n if (googObject.isEmpty(extraHeaders)) {\r\n return url;\r\n }\r\n var httpHeaders = exports.generateHttpHeadersOverwriteParam(extraHeaders);\r\n if (goog.isString(url)) {\r\n return googUriUtils.appendParam(\r\n url, googString.urlEncode(urlParam), httpHeaders);\r\n } else {\r\n url.setParameterValue(urlParam, httpHeaders); // duplicate removed!\r\n return url;\r\n }\r\n};\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Implementation of a WebChannel transport using WebChannelBase.\r\n *\r\n * When WebChannelBase is used as the underlying transport, the capabilities\r\n * of the WebChannel are limited to what's supported by the implementation.\r\n * Particularly, multiplexing is not possible, and only strings are\r\n * supported as message types.\r\n *\r\n */\r\n\r\ngoog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');\r\n\r\ngoog.require('goog.asserts');\r\ngoog.require('goog.events.EventTarget');\r\ngoog.require('goog.json');\r\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\r\ngoog.require('goog.labs.net.webChannel.WebChannelBase');\r\ngoog.require('goog.labs.net.webChannel.Wire');\r\ngoog.require('goog.log');\r\ngoog.require('goog.net.WebChannel');\r\ngoog.require('goog.net.WebChannelTransport');\r\ngoog.require('goog.object');\r\ngoog.require('goog.string');\r\ngoog.require('goog.string.path');\r\n\r\n\r\n\r\n/**\r\n * Implementation of {@link goog.net.WebChannelTransport} with\r\n * {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel\r\n * implementation.\r\n *\r\n * @constructor\r\n * @struct\r\n * @implements {goog.net.WebChannelTransport}\r\n * @final\r\n */\r\ngoog.labs.net.webChannel.WebChannelBaseTransport = function() {\r\n if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {\r\n throw new Error('Environmental error: no available transport.');\r\n }\r\n};\r\n\r\n\r\ngoog.scope(function() {\r\nvar WebChannelBaseTransport = goog.labs.net.webChannel.WebChannelBaseTransport;\r\nvar WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\r\nvar Wire = goog.labs.net.webChannel.Wire;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.prototype.createWebChannel = function(\r\n url, opt_options) {\r\n return new WebChannelBaseTransport.Channel(url, opt_options);\r\n};\r\n\r\n\r\n\r\n/**\r\n * Implementation of the {@link goog.net.WebChannel} interface.\r\n *\r\n * @param {string} url The URL path for the new WebChannel instance.\r\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\r\n * new WebChannel instance.\r\n *\r\n * @constructor\r\n * @implements {goog.net.WebChannel}\r\n * @extends {goog.events.EventTarget}\r\n * @final\r\n */\r\nWebChannelBaseTransport.Channel = function(url, opt_options) {\r\n WebChannelBaseTransport.Channel.base(this, 'constructor');\r\n\r\n /**\r\n * @private {!WebChannelBase} The underlying channel object.\r\n */\r\n this.channel_ = new WebChannelBase(\r\n opt_options, goog.net.WebChannelTransport.CLIENT_VERSION);\r\n\r\n /**\r\n * @private {string} The URL of the target server end-point.\r\n */\r\n this.url_ = url;\r\n\r\n /**\r\n * The test URL of the target server end-point. This value defaults to\r\n * this.url_ + '/test'.\r\n *\r\n * @private {string}\r\n */\r\n this.testUrl_ = (opt_options && opt_options.testUrl) ?\r\n opt_options.testUrl :\r\n goog.string.path.join(this.url_, 'test');\r\n\r\n /**\r\n * @private {goog.log.Logger} The logger for this class.\r\n */\r\n this.logger_ =\r\n goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');\r\n\r\n /**\r\n * @private {Object<string, string>} Extra URL parameters\r\n * to be added to each HTTP request.\r\n */\r\n this.messageUrlParams_ =\r\n (opt_options && opt_options.messageUrlParams) || null;\r\n\r\n var messageHeaders = (opt_options && opt_options.messageHeaders) || null;\r\n\r\n // default is false\r\n if (opt_options && opt_options.clientProtocolHeaderRequired) {\r\n if (messageHeaders) {\r\n goog.object.set(\r\n messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,\r\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\r\n } else {\r\n messageHeaders = goog.object.create(\r\n goog.net.WebChannel.X_CLIENT_PROTOCOL,\r\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\r\n }\r\n }\r\n\r\n this.channel_.setExtraHeaders(messageHeaders);\r\n\r\n var initHeaders = (opt_options && opt_options.initMessageHeaders) || null;\r\n\r\n if (opt_options && opt_options.messageContentType) {\r\n if (initHeaders) {\r\n goog.object.set(\r\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\r\n opt_options.messageContentType);\r\n } else {\r\n initHeaders = goog.object.create(\r\n goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\r\n opt_options.messageContentType);\r\n }\r\n }\r\n\r\n if (opt_options && opt_options.clientProfile) {\r\n if (initHeaders) {\r\n goog.object.set(\r\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\r\n opt_options.clientProfile);\r\n } else {\r\n initHeaders = goog.object.create(\r\n goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\r\n opt_options.clientProfile);\r\n }\r\n }\r\n\r\n this.channel_.setInitHeaders(initHeaders);\r\n\r\n var httpHeadersOverwriteParam =\r\n opt_options && opt_options.httpHeadersOverwriteParam;\r\n if (httpHeadersOverwriteParam &&\r\n !goog.string.isEmptyOrWhitespace(httpHeadersOverwriteParam)) {\r\n this.channel_.setHttpHeadersOverwriteParam(httpHeadersOverwriteParam);\r\n }\r\n\r\n /**\r\n * @private {boolean} Whether to enable CORS.\r\n */\r\n this.supportsCrossDomainXhr_ =\r\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\r\n\r\n /**\r\n * @private {boolean} Whether to send raw Json and bypass v8 wire format.\r\n */\r\n this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;\r\n\r\n // Note that httpSessionIdParam will be ignored if the same parameter name\r\n // has already been specified with messageUrlParams\r\n var httpSessionIdParam = opt_options && opt_options.httpSessionIdParam;\r\n if (httpSessionIdParam &&\r\n !goog.string.isEmptyOrWhitespace(httpSessionIdParam)) {\r\n this.channel_.setHttpSessionIdParam(httpSessionIdParam);\r\n if (goog.object.containsKey(this.messageUrlParams_, httpSessionIdParam)) {\r\n goog.object.remove(this.messageUrlParams_, httpSessionIdParam);\r\n goog.log.warning(this.logger_,\r\n 'Ignore httpSessionIdParam also specified with messageUrlParams: '\r\n + httpSessionIdParam);\r\n }\r\n }\r\n\r\n /**\r\n * The channel handler.\r\n *\r\n * @private {!WebChannelBaseTransport.Channel.Handler_}\r\n */\r\n this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);\r\n};\r\ngoog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);\r\n\r\n\r\n/**\r\n * @override\r\n * @suppress {checkTypes}\r\n */\r\nWebChannelBaseTransport.Channel.prototype.addEventListener = function(\r\n type, handler, /** boolean= */ opt_capture, opt_handlerScope) {\r\n WebChannelBaseTransport.Channel.base(\r\n this, 'addEventListener', type, handler, opt_capture, opt_handlerScope);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n * @suppress {checkTypes}\r\n */\r\nWebChannelBaseTransport.Channel.prototype.removeEventListener = function(\r\n type, handler, /** boolean= */ opt_capture, opt_handlerScope) {\r\n WebChannelBaseTransport.Channel.base(\r\n this, 'removeEventListener', type, handler, opt_capture,\r\n opt_handlerScope);\r\n};\r\n\r\n\r\n/**\r\n * Test path is always set to \"/url/test\".\r\n *\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.open = function() {\r\n this.channel_.setHandler(this.channelHandler_);\r\n if (this.supportsCrossDomainXhr_) {\r\n this.channel_.setSupportsCrossDomainXhrs(true);\r\n }\r\n this.channel_.connect(\r\n this.testUrl_, this.url_, (this.messageUrlParams_ || undefined));\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.close = function() {\r\n this.channel_.disconnect();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.halfClose = function() {\r\n // to be implemented\r\n throw new Error('Not implemented');\r\n};\r\n\r\n\r\n/**\r\n * The WebChannelBase only supports object types.\r\n *\r\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\r\n *\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.send = function(message) {\r\n goog.asserts.assert(\r\n goog.isObject(message) || goog.isString(message),\r\n 'only object type or raw string is supported');\r\n\r\n if (goog.isString(message)) {\r\n var rawJson = {};\r\n rawJson[Wire.RAW_DATA_KEY] = message;\r\n this.channel_.sendMap(rawJson);\r\n } else if (this.sendRawJson_) {\r\n var rawJson = {};\r\n rawJson[Wire.RAW_DATA_KEY] = goog.json.serialize(message);\r\n this.channel_.sendMap(rawJson);\r\n } else {\r\n this.channel_.sendMap(message);\r\n }\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.disposeInternal = function() {\r\n this.channel_.setHandler(null);\r\n delete this.channelHandler_;\r\n this.channel_.disconnect();\r\n delete this.channel_;\r\n\r\n WebChannelBaseTransport.Channel.base(this, 'disposeInternal');\r\n};\r\n\r\n\r\n\r\n/**\r\n * The message event.\r\n *\r\n * @param {!Array<?>|!Object} array The data array from the underlying channel.\r\n * @constructor\r\n * @extends {goog.net.WebChannel.MessageEvent}\r\n * @final\r\n */\r\nWebChannelBaseTransport.Channel.MessageEvent = function(array) {\r\n WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');\r\n\r\n // single-metadata only\r\n var metadata = array['__sm__'];\r\n if (metadata) {\r\n this.metadataKey = goog.object.getAnyKey(metadata);\r\n if (this.metadataKey) {\r\n this.data = goog.object.get(metadata, this.metadataKey);\r\n } else {\r\n this.data = metadata; // empty\r\n }\r\n } else {\r\n this.data = array;\r\n }\r\n};\r\ngoog.inherits(\r\n WebChannelBaseTransport.Channel.MessageEvent,\r\n goog.net.WebChannel.MessageEvent);\r\n\r\n\r\n\r\n/**\r\n * The error event.\r\n *\r\n * @param {WebChannelBase.Error} error The error code.\r\n * @constructor\r\n * @extends {goog.net.WebChannel.ErrorEvent}\r\n * @final\r\n */\r\nWebChannelBaseTransport.Channel.ErrorEvent = function(error) {\r\n WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');\r\n\r\n /**\r\n * High-level status code.\r\n */\r\n this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;\r\n\r\n /**\r\n * @const {WebChannelBase.Error} Internal error code, for debugging use only.\r\n */\r\n this.errorCode = error;\r\n};\r\ngoog.inherits(\r\n WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);\r\n\r\n\r\n\r\n/**\r\n * Implementation of {@link WebChannelBase.Handler} interface.\r\n *\r\n * @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.\r\n *\r\n * @constructor\r\n * @extends {WebChannelBase.Handler}\r\n * @private\r\n */\r\nWebChannelBaseTransport.Channel.Handler_ = function(channel) {\r\n WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');\r\n\r\n /**\r\n * @type {!WebChannelBaseTransport.Channel}\r\n * @private\r\n */\r\n this.channel_ = channel;\r\n};\r\ngoog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(\r\n channel) {\r\n goog.log.info(\r\n this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);\r\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =\r\n function(channel, array) {\r\n goog.asserts.assert(array, 'array expected to be defined');\r\n this.channel_.dispatchEvent(\r\n new WebChannelBaseTransport.Channel.MessageEvent(array));\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(\r\n channel, error) {\r\n goog.log.info(\r\n this.channel_.logger_, 'WebChannel aborted on ' + this.channel_.url_ +\r\n ' due to channel error: ' + error);\r\n this.channel_.dispatchEvent(\r\n new WebChannelBaseTransport.Channel.ErrorEvent(error));\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(\r\n channel, opt_pendingMaps, opt_undeliveredMaps) {\r\n goog.log.info(\r\n this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);\r\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {\r\n return new WebChannelBaseTransport.ChannelProperties(this.channel_);\r\n};\r\n\r\n\r\n\r\n/**\r\n * Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.\r\n *\r\n * @param {!WebChannelBase} channel The underlying channel object.\r\n *\r\n * @constructor\r\n * @implements {goog.net.WebChannel.RuntimeProperties}\r\n * @final\r\n */\r\nWebChannelBaseTransport.ChannelProperties = function(channel) {\r\n /**\r\n * The underlying channel object.\r\n *\r\n * @private {!WebChannelBase}\r\n */\r\n this.channel_ = channel;\r\n\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =\r\n function() {\r\n return this.channel_.getForwardChannelRequestPool().getMaxSize();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {\r\n return this.getConcurrentRequestLimit() > 1;\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getPendingRequestCount =\r\n function() {\r\n return this.channel_.getForwardChannelRequestPool().getRequestCount();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getHttpSessionId =\r\n function() {\r\n return this.channel_.getHttpSessionId();\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.commit = function(\r\n callback) {\r\n this.channel_.setForwardChannelFlushCallback(callback);\r\n};\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.notifyNonAckedMessageCount =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.onCommit =\r\n goog.abstractMethod;\r\n\r\n\r\n/**\r\n * @override\r\n */\r\nWebChannelBaseTransport.ChannelProperties.prototype.ackCommit =\r\n goog.abstractMethod;\r\n\r\n\r\n/** @override */\r\nWebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =\r\n function() {\r\n return this.channel_.getLastStatusCode();\r\n};\r\n}); // goog.scope\r\n","// Copyright 2010 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for dealing with POSIX path strings. Based on\r\n * Python's os.path and posixpath.\r\n * @author nnaze@google.com (Nathan Naze)\r\n */\r\n\r\ngoog.provide('goog.string.path');\r\n\r\ngoog.require('goog.array');\r\ngoog.require('goog.string');\r\n\r\n\r\n/**\r\n * Returns the final component of a pathname.\r\n * See http://docs.python.org/library/os.path.html#os.path.basename\r\n * @param {string} path A pathname.\r\n * @return {string} path The final component of a pathname, i.e. everything\r\n * after the final slash.\r\n */\r\ngoog.string.path.baseName = function(path) {\r\n var i = path.lastIndexOf('/') + 1;\r\n return path.slice(i);\r\n};\r\n\r\n\r\n/**\r\n * Alias to goog.string.path.baseName.\r\n * @param {string} path A pathname.\r\n * @return {string} path The final component of a pathname.\r\n * @deprecated Use goog.string.path.baseName.\r\n */\r\ngoog.string.path.basename = goog.string.path.baseName;\r\n\r\n\r\n/**\r\n * Returns the directory component of a pathname.\r\n * See http://docs.python.org/library/os.path.html#os.path.dirname\r\n * @param {string} path A pathname.\r\n * @return {string} The directory component of a pathname, i.e. everything\r\n * leading up to the final slash.\r\n */\r\ngoog.string.path.dirname = function(path) {\r\n var i = path.lastIndexOf('/') + 1;\r\n var head = path.slice(0, i);\r\n // If the path isn't all forward slashes, trim the trailing slashes.\r\n if (!/^\\/+$/.test(head)) {\r\n head = head.replace(/\\/+$/, '');\r\n }\r\n return head;\r\n};\r\n\r\n\r\n/**\r\n * Extracts the extension part of a pathname.\r\n * @param {string} path The path name to process.\r\n * @return {string} The extension if any, otherwise the empty string.\r\n */\r\ngoog.string.path.extension = function(path) {\r\n var separator = '.';\r\n // Combining all adjacent periods in the basename to a single period.\r\n var baseName = goog.string.path.baseName(path).replace(/\\.+/g, separator);\r\n var separatorIndex = baseName.lastIndexOf(separator);\r\n return separatorIndex <= 0 ? '' : baseName.substr(separatorIndex + 1);\r\n};\r\n\r\n\r\n// TODO(johnlenz): goog.string.path.join should not accept undefined\r\n/**\r\n * Joins one or more path components (e.g. 'foo/' and 'bar' make 'foo/bar').\r\n * An absolute component will discard all previous component.\r\n * See http://docs.python.org/library/os.path.html#os.path.join\r\n * @param {...(string|undefined)} var_args One of more path components.\r\n * @return {string} The path components joined.\r\n */\r\ngoog.string.path.join = function(var_args) {\r\n var path = arguments[0];\r\n\r\n for (var i = 1; i < arguments.length; i++) {\r\n var arg = arguments[i];\r\n if (goog.string.startsWith(arg, '/')) {\r\n path = arg;\r\n } else if (path == '' || goog.string.endsWith(path, '/')) {\r\n path += arg;\r\n } else {\r\n path += '/' + arg;\r\n }\r\n }\r\n\r\n return path;\r\n};\r\n\r\n\r\n/**\r\n * Normalizes a pathname by collapsing duplicate separators, parent directory\r\n * references ('..'), and current directory references ('.').\r\n * See http://docs.python.org/library/os.path.html#os.path.normpath\r\n * @param {string} path One or more path components.\r\n * @return {string} The path after normalization.\r\n */\r\ngoog.string.path.normalizePath = function(path) {\r\n if (path == '') {\r\n return '.';\r\n }\r\n\r\n var initialSlashes = '';\r\n // POSIX will keep two slashes, but three or more will be collapsed to one.\r\n if (goog.string.startsWith(path, '/')) {\r\n initialSlashes = '/';\r\n if (goog.string.startsWith(path, '//') &&\r\n !goog.string.startsWith(path, '///')) {\r\n initialSlashes = '//';\r\n }\r\n }\r\n\r\n var parts = path.split('/');\r\n var newParts = [];\r\n\r\n for (var i = 0; i < parts.length; i++) {\r\n var part = parts[i];\r\n\r\n // '' and '.' don't change the directory, ignore.\r\n if (part == '' || part == '.') {\r\n continue;\r\n }\r\n\r\n // A '..' should pop a directory unless this is not an absolute path and\r\n // we're at the root, or we've travelled upwards relatively in the last\r\n // iteration.\r\n if (part != '..' || (!initialSlashes && !newParts.length) ||\r\n goog.array.peek(newParts) == '..') {\r\n newParts.push(part);\r\n } else {\r\n newParts.pop();\r\n }\r\n }\r\n\r\n var returnPath = initialSlashes + newParts.join('/');\r\n return returnPath || '.';\r\n};\r\n\r\n\r\n/**\r\n * Splits a pathname into \"dirname\" and \"baseName\" components, where \"baseName\"\r\n * is everything after the final slash. Either part may return an empty string.\r\n * See http://docs.python.org/library/os.path.html#os.path.split\r\n * @param {string} path A pathname.\r\n * @return {!Array<string>} An array of [dirname, basename].\r\n */\r\ngoog.string.path.split = function(path) {\r\n var head = goog.string.path.dirname(path);\r\n var tail = goog.string.path.baseName(path);\r\n return [head, tail];\r\n};\r\n\r\n// TODO(nnaze): Implement other useful functions from os.path\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Transport support for WebChannel.\r\n *\r\n * The <code>WebChannelTransport</code> implementation serves as the factory\r\n * for <code>WebChannel</code>, which offers an abstraction for\r\n * point-to-point socket-like communication similar to what BrowserChannel\r\n * or HTML5 WebSocket offers.\r\n *\r\n */\r\n\r\ngoog.provide('goog.net.WebChannelTransport');\r\n\r\ngoog.forwardDeclare('goog.net.WebChannel');\r\ngoog.forwardDeclare('goog.net.WebChannel.Options');\r\n\r\n\r\n\r\n/**\r\n * A WebChannelTransport instance represents a shared context of logical\r\n * connectivity between a browser client and a remote origin.\r\n *\r\n * Over a single WebChannelTransport instance, multiple WebChannels may be\r\n * created against different URLs, which may all share the same\r\n * underlying connectivity (i.e. TCP connection) whenever possible.\r\n *\r\n * When multi-domains are supported, such as CORS, multiple origins may be\r\n * supported over a single WebChannelTransport instance at the same time.\r\n *\r\n * Sharing between different window contexts such as tabs is not addressed\r\n * by WebChannelTransport. Applications may choose HTML5 shared workers\r\n * or other techniques to access the same transport instance\r\n * across different window contexts.\r\n *\r\n * @interface\r\n */\r\ngoog.net.WebChannelTransport = function() {};\r\n\r\n\r\n/**\r\n * The client version. This integer value will be passed to the server\r\n * when a channel is opened to inform the server the client \"capabilities\".\r\n *\r\n * Wire protocol version is a different concept and is internal to the\r\n * transport implementation.\r\n *\r\n * @const\r\n * @type {number}\r\n */\r\ngoog.net.WebChannelTransport.CLIENT_VERSION = 22;\r\n\r\n\r\n/**\r\n * Create a new WebChannel instance.\r\n *\r\n * The new WebChannel is to be opened against the server-side resource\r\n * as specified by the given URL. See {@link goog.net.WebChannel} for detailed\r\n * semantics.\r\n *\r\n * @param {string} url The URL path for the new WebChannel instance.\r\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\r\n * new WebChannel instance. The configuration object is reusable after\r\n * the new channel instance is created.\r\n * @return {!goog.net.WebChannel} the newly created WebChannel instance.\r\n */\r\ngoog.net.WebChannelTransport.prototype.createWebChannel = goog.abstractMethod;\r\n","// Copyright 2013 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Default factory for <code>WebChannelTransport</code> to\r\n * avoid exposing concrete classes to clients.\r\n *\r\n */\r\n\r\ngoog.provide('goog.net.createWebChannelTransport');\r\n\r\ngoog.require('goog.functions');\r\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\r\n\r\n\r\n/**\r\n * Create a new WebChannelTransport instance using the default implementation.\r\n * Throws an error message if no default transport available in the current\r\n * environment.\r\n *\r\n * @return {!goog.net.WebChannelTransport} the newly created transport instance.\r\n */\r\ngoog.net.createWebChannelTransport =\r\n /** @type {function(): !goog.net.WebChannelTransport} */ (\r\n goog.partial(\r\n goog.functions.create,\r\n goog.labs.net.webChannel.WebChannelBaseTransport));\r\n","// Copyright 2008 The Closure Library Authors. All Rights Reserved.\r\n//\r\n// Licensed under the Apache License, Version 2.0 (the \"License\");\r\n// you may not use this file except in compliance with the License.\r\n// You may obtain a copy of the License at\r\n//\r\n// http://www.apache.org/licenses/LICENSE-2.0\r\n//\r\n// Unless required by applicable law or agreed to in writing, software\r\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\r\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n// See the License for the specific language governing permissions and\r\n// limitations under the License.\r\n\r\n/**\r\n * @fileoverview Utilities for creating functions. Loosely inspired by these\r\n * java classes from the Guava library:\r\n * com.google.common.base.Functions\r\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\r\n *\r\n * com.google.common.base.Predicates\r\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\r\n *\r\n * More about these can be found at\r\n * https://github.com/google/guava/wiki/FunctionalExplained\r\n *\r\n * @author nicksantos@google.com (Nick Santos)\r\n */\r\n\r\n\r\ngoog.provide('goog.functions');\r\n\r\n\r\n/**\r\n * Creates a function that always returns the same value.\r\n * @param {T} retValue The value to return.\r\n * @return {function():T} The new function.\r\n * @template T\r\n */\r\ngoog.functions.constant = function(retValue) {\r\n return function() { return retValue; };\r\n};\r\n\r\n\r\n/**\r\n * Always returns false.\r\n * @type {function(...): boolean}\r\n */\r\ngoog.functions.FALSE = function() {\r\n return false;\r\n};\r\n\r\n\r\n/**\r\n * Always returns true.\r\n * @type {function(...): boolean}\r\n */\r\ngoog.functions.TRUE = function() {\r\n return true;\r\n};\r\n\r\n\r\n/**\r\n * Always returns NULL.\r\n * @type {function(...): null}\r\n */\r\ngoog.functions.NULL = function() {\r\n return null;\r\n};\r\n\r\n\r\n/**\r\n * A simple function that returns the first argument of whatever is passed\r\n * into it.\r\n * @param {T=} opt_returnValue The single value that will be returned.\r\n * @param {...*} var_args Optional trailing arguments. These are ignored.\r\n * @return {T} The first argument passed in, or undefined if nothing was passed.\r\n * @template T\r\n */\r\ngoog.functions.identity = function(opt_returnValue, var_args) {\r\n return opt_returnValue;\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that always throws an error with the given message.\r\n * @param {string} message The error message.\r\n * @return {!Function} The error-throwing function.\r\n */\r\ngoog.functions.error = function(message) {\r\n return function() {\r\n throw new Error(message);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that throws the given object.\r\n * @param {*} err An object to be thrown.\r\n * @return {!Function} The error-throwing function.\r\n */\r\ngoog.functions.fail = function(err) {\r\n return function() { throw err; };\r\n};\r\n\r\n\r\n/**\r\n * Given a function, create a function that keeps opt_numArgs arguments and\r\n * silently discards all additional arguments.\r\n * @param {Function} f The original function.\r\n * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.\r\n * @return {!Function} A version of f that only keeps the first opt_numArgs\r\n * arguments.\r\n */\r\ngoog.functions.lock = function(f, opt_numArgs) {\r\n opt_numArgs = opt_numArgs || 0;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns its nth argument.\r\n * @param {number} n The position of the return argument.\r\n * @return {!Function} A new function.\r\n */\r\ngoog.functions.nth = function(n) {\r\n return function() { return arguments[n]; };\r\n};\r\n\r\n\r\n/**\r\n * Like goog.partial(), except that arguments are added after arguments to the\r\n * returned function.\r\n *\r\n * Usage:\r\n * function f(arg1, arg2, arg3, arg4) { ... }\r\n * var g = goog.functions.partialRight(f, arg3, arg4);\r\n * g(arg1, arg2);\r\n *\r\n * @param {!Function} fn A function to partially apply.\r\n * @param {...*} var_args Additional arguments that are partially applied to fn\r\n * at the end.\r\n * @return {!Function} A partially-applied form of the function goog.partial()\r\n * was invoked as a method of.\r\n */\r\ngoog.functions.partialRight = function(fn, var_args) {\r\n var rightArgs = Array.prototype.slice.call(arguments, 1);\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n var newArgs = Array.prototype.slice.call(arguments);\r\n newArgs.push.apply(newArgs, rightArgs);\r\n return fn.apply(self, newArgs);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Given a function, create a new function that swallows its return value\r\n * and replaces it with a new one.\r\n * @param {Function} f A function.\r\n * @param {T} retValue A new return value.\r\n * @return {function(...?):T} A new function.\r\n * @template T\r\n */\r\ngoog.functions.withReturnValue = function(f, retValue) {\r\n return goog.functions.sequence(f, goog.functions.constant(retValue));\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns whether its argument equals the given value.\r\n *\r\n * Example:\r\n * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));\r\n *\r\n * @param {*} value The value to compare to.\r\n * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)\r\n * comparison rather than a strict (===) one. Defaults to false.\r\n * @return {function(*):boolean} The new function.\r\n */\r\ngoog.functions.equalTo = function(value, opt_useLooseComparison) {\r\n return function(other) {\r\n return opt_useLooseComparison ? (value == other) : (value === other);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates the composition of the functions passed in.\r\n * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).\r\n * @param {function(...?):T} fn The final function.\r\n * @param {...Function} var_args A list of functions.\r\n * @return {function(...?):T} The composition of all inputs.\r\n * @template T\r\n */\r\ngoog.functions.compose = function(fn, var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n var result;\r\n if (length) {\r\n result = functions[length - 1].apply(self, arguments);\r\n }\r\n\r\n for (var i = length - 2; i >= 0; i--) {\r\n result = functions[i].call(self, result);\r\n }\r\n return result;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that calls the functions passed in in sequence, and\r\n * returns the value of the last function. For example,\r\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\r\n * @param {...Function} var_args A list of functions.\r\n * @return {!Function} A function that calls all inputs in sequence.\r\n */\r\ngoog.functions.sequence = function(var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n var result;\r\n for (var i = 0; i < length; i++) {\r\n result = functions[i].apply(self, arguments);\r\n }\r\n return result;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns true if each of its components evaluates\r\n * to true. The components are evaluated in order, and the evaluation will be\r\n * short-circuited as soon as a function returns false.\r\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\r\n * @param {...Function} var_args A list of functions.\r\n * @return {function(...?):boolean} A function that ANDs its component\r\n * functions.\r\n */\r\ngoog.functions.and = function(var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n for (var i = 0; i < length; i++) {\r\n if (!functions[i].apply(self, arguments)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns true if any of its components evaluates\r\n * to true. The components are evaluated in order, and the evaluation will be\r\n * short-circuited as soon as a function returns true.\r\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\r\n * @param {...Function} var_args A list of functions.\r\n * @return {function(...?):boolean} A function that ORs its component\r\n * functions.\r\n */\r\ngoog.functions.or = function(var_args) {\r\n var functions = arguments;\r\n var length = functions.length;\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n for (var i = 0; i < length; i++) {\r\n if (functions[i].apply(self, arguments)) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Creates a function that returns the Boolean opposite of a provided function.\r\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\r\n * @param {!Function} f The original function.\r\n * @return {function(...?):boolean} A function that delegates to f and returns\r\n * opposite.\r\n */\r\ngoog.functions.not = function(f) {\r\n return function() {\r\n var self = /** @type {*} */ (this);\r\n return !f.apply(self, arguments);\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Generic factory function to construct an object given the constructor\r\n * and the arguments. Intended to be bound to create object factories.\r\n *\r\n * Example:\r\n *\r\n * var factory = goog.partial(goog.functions.create, Class);\r\n *\r\n * @param {function(new:T, ...)} constructor The constructor for the Object.\r\n * @param {...*} var_args The arguments to be passed to the constructor.\r\n * @return {T} A new instance of the class given in `constructor`.\r\n * @template T\r\n */\r\ngoog.functions.create = function(constructor, var_args) {\r\n /**\r\n * @constructor\r\n * @final\r\n */\r\n var temp = function() {};\r\n temp.prototype = constructor.prototype;\r\n\r\n // obj will have constructor's prototype in its chain and\r\n // 'obj instanceof constructor' will be true.\r\n var obj = new temp();\r\n\r\n // obj is initialized by constructor.\r\n // arguments is only array-like so lacks shift(), but can be used with\r\n // the Array prototype function.\r\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\r\n return obj;\r\n};\r\n\r\n\r\n/**\r\n * @define {boolean} Whether the return value cache should be used.\r\n * This should only be used to disable caches when testing.\r\n */\r\ngoog.functions.CACHE_RETURN_VALUE =\r\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\r\n\r\n\r\n/**\r\n * Gives a wrapper function that caches the return value of a parameterless\r\n * function when first called.\r\n *\r\n * When called for the first time, the given function is called and its\r\n * return value is cached (thus this is only appropriate for idempotent\r\n * functions). Subsequent calls will return the cached return value. This\r\n * allows the evaluation of expensive functions to be delayed until first used.\r\n *\r\n * To cache the return values of functions with parameters, see goog.memoize.\r\n *\r\n * @param {function():T} fn A function to lazily evaluate.\r\n * @return {function():T} A wrapped version the function.\r\n * @template T\r\n */\r\ngoog.functions.cacheReturnValue = function(fn) {\r\n var called = false;\r\n var value;\r\n\r\n return function() {\r\n if (!goog.functions.CACHE_RETURN_VALUE) {\r\n return fn();\r\n }\r\n\r\n if (!called) {\r\n value = fn();\r\n called = true;\r\n }\r\n\r\n return value;\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once. All\r\n * additional calls are no-ops.\r\n *\r\n * This is particularly useful for initialization functions\r\n * that should be called, at most, once.\r\n *\r\n * @param {function():*} f Function to call.\r\n * @return {function():undefined} Wrapped function.\r\n */\r\ngoog.functions.once = function(f) {\r\n // Keep a reference to the function that we null out when we're done with\r\n // it -- that way, the function can be GC'd when we're done with it.\r\n var inner = f;\r\n return function() {\r\n if (inner) {\r\n var tmp = inner;\r\n inner = null;\r\n tmp();\r\n }\r\n };\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once per interval\r\n * (specified in milliseconds). If the wrapper function is called N times within\r\n * that interval, only the Nth call will go through.\r\n *\r\n * This is particularly useful for batching up repeated actions where the\r\n * last action should win. This can be used, for example, for refreshing an\r\n * autocomplete pop-up every so often rather than updating with every keystroke,\r\n * since the final text typed by the user is the one that should produce the\r\n * final autocomplete results. For more stateful debouncing with support for\r\n * pausing, resuming, and canceling debounced actions, use\r\n * `goog.async.Debouncer`.\r\n *\r\n * @param {function(this:SCOPE, ...?)} f Function to call.\r\n * @param {number} interval Interval over which to debounce. The function will\r\n * only be called after the full interval has elapsed since the last call.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\r\n * @return {function(...?): undefined} Wrapped function.\r\n * @template SCOPE\r\n */\r\ngoog.functions.debounce = function(f, interval, opt_scope) {\r\n var timeout = 0;\r\n return /** @type {function(...?)} */ (function(var_args) {\r\n goog.global.clearTimeout(timeout);\r\n var args = arguments;\r\n timeout = goog.global.setTimeout(function() {\r\n f.apply(opt_scope, args);\r\n }, interval);\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once per interval\r\n * (specified in milliseconds). If the wrapper function is called N times in\r\n * that interval, both the 1st and the Nth calls will go through.\r\n *\r\n * This is particularly useful for limiting repeated user requests where the\r\n * the last action should win, but you also don't want to wait until the end of\r\n * the interval before sending a request out, as it leads to a perception of\r\n * slowness for the user.\r\n *\r\n * @param {function(this:SCOPE, ...?)} f Function to call.\r\n * @param {number} interval Interval over which to throttle. The function can\r\n * only be called once per interval.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\r\n * @return {function(...?): undefined} Wrapped function.\r\n * @template SCOPE\r\n */\r\ngoog.functions.throttle = function(f, interval, opt_scope) {\r\n var timeout = 0;\r\n var shouldFire = false;\r\n var args = [];\r\n\r\n var handleTimeout = function() {\r\n timeout = 0;\r\n if (shouldFire) {\r\n shouldFire = false;\r\n fire();\r\n }\r\n };\r\n\r\n var fire = function() {\r\n timeout = goog.global.setTimeout(handleTimeout, interval);\r\n f.apply(opt_scope, args);\r\n };\r\n\r\n return /** @type {function(...?)} */ (function(var_args) {\r\n args = arguments;\r\n if (!timeout) {\r\n fire();\r\n } else {\r\n shouldFire = true;\r\n }\r\n });\r\n};\r\n\r\n\r\n/**\r\n * Wraps a function to allow it to be called, at most, once per interval\r\n * (specified in milliseconds). If the wrapper function is called N times within\r\n * that interval, only the 1st call will go through.\r\n *\r\n * This is particularly useful for limiting repeated user requests where the\r\n * first request is guaranteed to have all the data required to perform the\r\n * final action, so there's no need to wait until the end of the interval before\r\n * sending the request out.\r\n *\r\n * @param {function(this:SCOPE, ...?)} f Function to call.\r\n * @param {number} interval Interval over which to rate-limit. The function will\r\n * only be called once per interval, and ignored for the remainer of the\r\n * interval.\r\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\r\n * @return {function(...?): undefined} Wrapped function.\r\n * @template SCOPE\r\n */\r\ngoog.functions.rateLimit = function(f, interval, opt_scope) {\r\n var timeout = 0;\r\n\r\n var handleTimeout = function() {\r\n timeout = 0;\r\n };\r\n\r\n return /** @type {function(...?)} */ (function(var_args) {\r\n if (!timeout) {\r\n timeout = goog.global.setTimeout(handleTimeout, interval);\r\n f.apply(opt_scope, arguments);\r\n }\r\n });\r\n};\r\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * Bring in closure-library dependencies\n */\n\ngoog.provide('firebase.webchannel.wrapper');\n\n// goog.net.WebChannelTransport\ngoog.require('goog.net.createWebChannelTransport');\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\n/**\n * NOTE: The `createWebChannel` function takes an options object as a second param\n * whose properties are typically mangled. We override these in externs/overrides.js\n * Without those externs, this does not function properly.\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport.prototype['createWebChannel'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.prototype.createWebChannel;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['send'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.send;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['open'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.open;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['close'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.close;\n\n// goog.net.ErrorCode\ngoog.require('goog.net.ErrorCode');\ngoog.net.ErrorCode['NO_ERROR'] = goog.net.ErrorCode.NO_ERROR;\ngoog.net.ErrorCode['TIMEOUT'] = goog.net.ErrorCode.TIMEOUT;\ngoog.net.ErrorCode['HTTP_ERROR'] = goog.net.ErrorCode.HTTP_ERROR;\n\n// goog.net.ErrorType\ngoog.require('goog.net.EventType');\ngoog.net.EventType['COMPLETE'] = goog.net.EventType.COMPLETE;\n\n// goog.net.WebChannel\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.events.EventTarget');\ngoog.net.WebChannel['EventType'] = goog.net.WebChannel.EventType;\ngoog.net.WebChannel.EventType['OPEN'] = goog.net.WebChannel.EventType.OPEN;\ngoog.net.WebChannel.EventType['CLOSE'] = goog.net.WebChannel.EventType.CLOSE;\ngoog.net.WebChannel.EventType['ERROR'] = goog.net.WebChannel.EventType.ERROR;\ngoog.net.WebChannel.EventType['MESSAGE'] =\n goog.net.WebChannel.EventType.MESSAGE;\ngoog.events.EventTarget.prototype['listen'] =\n goog.events.EventTarget.prototype.listen;\n\n// goog.net.XhrIo\ngoog.require('goog.net.XhrIo');\ngoog.net.XhrIo.prototype['listenOnce'] = goog.net.XhrIo.prototype.listenOnce;\ngoog.net.XhrIo.prototype['getLastError'] =\n goog.net.XhrIo.prototype.getLastError;\ngoog.net.XhrIo.prototype['getLastErrorCode'] =\n goog.net.XhrIo.prototype.getLastErrorCode;\ngoog.net.XhrIo.prototype['getStatus'] = goog.net.XhrIo.prototype.getStatus;\ngoog.net.XhrIo.prototype['getResponseJson'] =\n goog.net.XhrIo.prototype.getResponseJson;\ngoog.net.XhrIo.prototype['getResponseText'] =\n goog.net.XhrIo.prototype.getResponseText;\ngoog.net.XhrIo.prototype['send'] = goog.net.XhrIo.prototype.send;\n\n/**\n * This ignore statement is required as closure will minify these properties\n * if done in the typical prettier format\n */\n// prettier-ignore\nmodule['exports'] = {\n 'createWebChannelTransport': goog.net.createWebChannelTransport,\n 'ErrorCode': goog.net.ErrorCode,\n 'EventType': goog.net.EventType,\n 'WebChannel': goog.net.WebChannel,\n 'XhrIo': goog.net.XhrIo\n};\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { User } from '../auth/user';\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\n// TODO(mikelehen): This should be split into multiple files and probably\n// moved to an auth/ folder to match other platforms.\n\nexport interface FirstPartyCredentialsSettings {\n type: 'gapi';\n client: unknown;\n sessionIndex: string;\n}\n\nexport interface ProviderCredentialsSettings {\n type: 'provider';\n client: CredentialsProvider;\n}\n\n/** Settings for private credentials */\nexport type CredentialsSettings =\n | FirstPartyCredentialsSettings\n | ProviderCredentialsSettings;\n\nexport type TokenType = 'OAuth' | 'FirstParty';\nexport interface Token {\n /** Type of token. */\n type: TokenType;\n\n /**\n * The user with which the token is associated (used for persisting user\n * state on disk, etc.).\n */\n user: User;\n\n /** Extra header values to be passed along with a request */\n authHeaders: { [header: string]: string };\n}\n\nexport class OAuthToken implements Token {\n type = 'OAuth' as TokenType;\n authHeaders: { [header: string]: string };\n constructor(value: string, public user: User) {\n this.authHeaders = {};\n // Set the headers using Object Literal notation to avoid minification\n this.authHeaders['Authorization'] = `Bearer ${value}`;\n }\n}\n\n/**\n * A Listener for credential change events. The listener should fetch a new\n * token and may need to invalidate other state if the current user has also\n * changed.\n */\nexport type CredentialChangeListener = (user: User) => void;\n\n/**\n * Provides methods for getting the uid and token for the current user and\n * listening for changes.\n */\nexport interface CredentialsProvider {\n /** Requests a token for the current user. */\n getToken(): Promise<Token | null>;\n\n /**\n * Marks the last retrieved token as invalid, making the next GetToken request\n * force-refresh the token.\n */\n invalidateToken(): void;\n\n /**\n * Specifies a listener to be notified of credential changes\n * (sign-in / sign-out, token changes). It is immediately called once with the\n * initial user.\n */\n setChangeListener(changeListener: CredentialChangeListener): void;\n\n /** Removes the previously-set change listener. */\n removeChangeListener(): void;\n}\n\n/** A CredentialsProvider that always yields an empty token. */\nexport class EmptyCredentialsProvider implements CredentialsProvider {\n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n private changeListener: CredentialChangeListener | null = null;\n\n getToken(): Promise<Token | null> {\n return Promise.resolve<Token | null>(null);\n }\n\n invalidateToken(): void {}\n\n setChangeListener(changeListener: CredentialChangeListener): void {\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\n this.changeListener = changeListener;\n // Fire with initial user.\n changeListener(User.UNAUTHENTICATED);\n }\n\n removeChangeListener(): void {\n assert(\n this.changeListener !== null,\n 'removeChangeListener() when no listener registered'\n );\n this.changeListener = null;\n }\n}\n\nexport class FirebaseCredentialsProvider implements CredentialsProvider {\n /**\n * The auth token listener registered with FirebaseApp, retained here so we\n * can unregister it.\n */\n private tokenListener: ((token: string | null) => void) | null = null;\n\n /** Tracks the current User. */\n private currentUser: User = User.UNAUTHENTICATED;\n private receivedInitialUser: boolean = false;\n\n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n private tokenCounter = 0;\n\n /** The listener registered with setChangeListener(). */\n private changeListener: CredentialChangeListener | null = null;\n\n private forceRefresh = false;\n\n private auth: FirebaseAuthInternal | null;\n\n constructor(authProvider: Provider<FirebaseAuthInternalName>) {\n this.tokenListener = () => {\n this.tokenCounter++;\n this.currentUser = this.getUser();\n this.receivedInitialUser = true;\n if (this.changeListener) {\n this.changeListener(this.currentUser);\n }\n };\n\n this.tokenCounter = 0;\n\n this.auth = authProvider.getImmediate({ optional: true });\n\n if (this.auth) {\n this.auth.addAuthTokenListener(this.tokenListener!);\n } else {\n // if auth is not available, invoke tokenListener once with null token\n this.tokenListener(null);\n authProvider.get().then(\n auth => {\n this.auth = auth;\n if (this.tokenListener) {\n // tokenListener can be removed by removeChangeListener()\n this.auth.addAuthTokenListener(this.tokenListener);\n }\n },\n () => {\n /* this.authProvider.get() never rejects */\n }\n );\n }\n }\n\n getToken(): Promise<Token | null> {\n assert(\n this.tokenListener != null,\n 'getToken cannot be called after listener removed.'\n );\n\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const initialTokenCounter = this.tokenCounter;\n const forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n\n if (!this.auth) {\n return Promise.resolve(null);\n }\n\n return this.auth.getToken(forceRefresh).then(tokenData => {\n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n if (this.tokenCounter !== initialTokenCounter) {\n throw new FirestoreError(\n Code.ABORTED,\n 'getToken aborted due to token change.'\n );\n } else {\n if (tokenData) {\n assert(\n typeof tokenData.accessToken === 'string',\n 'Invalid tokenData returned from getToken():' + tokenData\n );\n return new OAuthToken(tokenData.accessToken, this.currentUser);\n } else {\n return null;\n }\n }\n });\n }\n\n invalidateToken(): void {\n this.forceRefresh = true;\n }\n\n setChangeListener(changeListener: CredentialChangeListener): void {\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\n this.changeListener = changeListener;\n\n // Fire the initial event\n if (this.receivedInitialUser) {\n changeListener(this.currentUser);\n }\n }\n\n removeChangeListener(): void {\n assert(this.tokenListener != null, 'removeChangeListener() called twice');\n assert(\n this.changeListener !== null,\n 'removeChangeListener() called when no listener registered'\n );\n\n if (this.auth) {\n this.auth.removeAuthTokenListener(this.tokenListener!);\n }\n this.tokenListener = null;\n this.changeListener = null;\n }\n\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n private getUser(): User {\n const currentUid = this.auth && this.auth.getUid();\n assert(\n currentUid === null || typeof currentUid === 'string',\n 'Received invalid UID: ' + currentUid\n );\n return new User(currentUid);\n }\n}\n\n// Manual type definition for the subset of Gapi we use.\ninterface Gapi {\n auth: {\n getAuthHeaderValueForFirstParty: (\n userIdentifiers: Array<{ [key: string]: string }>\n ) => string | null;\n };\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */\nexport class FirstPartyToken implements Token {\n type = 'FirstParty' as TokenType;\n user = User.FIRST_PARTY;\n\n constructor(private gapi: Gapi, private sessionIndex: string) {}\n\n get authHeaders(): { [header: string]: string } {\n const headers: { [header: string]: string } = {\n 'X-Goog-AuthUser': this.sessionIndex\n };\n const authHeader = this.gapi.auth.getAuthHeaderValueForFirstParty([]);\n if (authHeader) {\n headers['Authorization'] = authHeader;\n }\n return headers;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */\nexport class FirstPartyCredentialsProvider implements CredentialsProvider {\n constructor(private gapi: Gapi, private sessionIndex: string) {}\n\n getToken(): Promise<Token | null> {\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\n }\n\n setChangeListener(changeListener: CredentialChangeListener): void {\n // Fire with initial uid.\n changeListener(User.FIRST_PARTY);\n }\n\n removeChangeListener(): void {}\n\n invalidateToken(): void {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\nexport function makeCredentialsProvider(\n credentials?: CredentialsSettings\n): CredentialsProvider {\n if (!credentials) {\n return new EmptyCredentialsProvider();\n }\n\n switch (credentials.type) {\n case 'gapi':\n const client = credentials.client as Gapi;\n // Make sure this really is a Gapi client.\n assert(\n !!(\n typeof client === 'object' &&\n client !== null &&\n client['auth'] &&\n client['auth']['getAuthHeaderValueForFirstParty']\n ),\n 'unexpected gapi interface'\n );\n return new FirstPartyCredentialsProvider(\n client,\n credentials.sessionIndex || '0'\n );\n\n case 'provider':\n return credentials.client;\n\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'makeCredentialsProvider failed due to invalid credential type'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\n\n/** The semver (www.semver.org) version of the SDK. */\nexport const SDK_VERSION = firebase.SDK_VERSION;\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * as firestore from '@firebase/firestore-types';\n\n/**\n * Error Codes describing the different ways Firestore can fail. These come\n * directly from GRPC.\n */\nexport type Code = firestore.FirestoreErrorCode;\n\nexport const Code = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: 'ok' as Code,\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled' as Code,\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown' as Code,\n\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: 'invalid-argument' as Code,\n\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded' as Code,\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found' as Code,\n\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: 'already-exists' as Code,\n\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: 'permission-denied' as Code,\n\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: 'unauthenticated' as Code,\n\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted' as Code,\n\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: 'failed-precondition' as Code,\n\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: 'aborted' as Code,\n\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: 'out-of-range' as Code,\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented' as Code,\n\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: 'internal' as Code,\n\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: 'unavailable' as Code,\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss' as Code\n};\n\n/**\n * An error class used for Firestore-generated errors. Ideally we should be\n * using FirebaseError, but integrating with it is overly arduous at the moment,\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\n * and compatible `code` and `message` fields.)\n */\nexport class FirestoreError extends Error implements firestore.FirestoreError {\n name = 'FirebaseError';\n stack?: string;\n\n constructor(readonly code: Code, readonly message: string) {\n super(message);\n\n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Code, FirestoreError } from './error';\n\n/**\n * Helper function to prevent instantiation through the constructor.\n *\n * This method creates a new constructor that throws when it's invoked.\n * The prototype of that constructor is then set to the prototype of the hidden\n * \"class\" to expose all the prototype methods and allow for instanceof\n * checks.\n *\n * To also make all the static methods available, all properties of the\n * original constructor are copied to the new constructor.\n */\nexport function makeConstructorPrivate<T extends Function>(\n cls: T,\n optionalMessage?: string\n): T {\n function PublicConstructor(): never {\n let error = 'This constructor is private.';\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n }\n\n // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n PublicConstructor.prototype = cls.prototype;\n\n // Copy any static methods/members\n Object.assign(PublicConstructor, cls);\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return PublicConstructor as any;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\nexport interface Dict<V> {\n [stringKey: string]: V;\n [numberKey: number]: V;\n}\n\nexport function contains<V>(obj: Dict<V>, key: string | number): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n\nexport function get<V>(obj: Dict<V>, key: string | number): V | null {\n return Object.prototype.hasOwnProperty.call(obj, key) ? obj[key] : null;\n}\n\nexport function size<V>(obj: Dict<V>): number {\n let count = 0;\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n count++;\n }\n }\n return count;\n}\n\n/** Returns the given value if it's defined or the defaultValue otherwise. */\nexport function defaulted<V>(value: V | undefined, defaultValue: V): V {\n return value !== undefined ? value : defaultValue;\n}\n\nexport function forEachNumber<V>(\n obj: Dict<V>,\n fn: (key: number, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const num = Number(key);\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\n\nexport function values<V>(obj: Dict<V>): V[] {\n const vs: V[] = [];\n forEach(obj, (_, v) => vs.push(v));\n return vs;\n}\n\nexport function forEach<V>(\n obj: Dict<V>,\n fn: (key: string, val: V) => void\n): void {\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nexport function lookupOrInsert<V>(\n obj: Dict<V>,\n key: string | number,\n valFn: () => V\n): V {\n if (!contains(obj, key)) {\n obj[key] = valFn();\n }\n return obj[key];\n}\n\nexport function isEmpty<V>(obj: Dict<V>): boolean {\n assert(\n obj != null && typeof obj === 'object',\n 'isEmpty() expects object parameter.'\n );\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n return true;\n}\n\nexport function shallowCopy<V>(obj: Dict<V>): Dict<V> {\n assert(\n obj && typeof obj === 'object',\n 'shallowCopy() expects object parameter.'\n );\n return { ...obj };\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { fail } from './assert';\nimport { Code, FirestoreError } from './error';\nimport * as obj from './obj';\n\n/** Types accepted by validateType() and related methods for validation. */\nexport type ValidationType =\n | 'undefined'\n | 'object'\n | 'function'\n | 'boolean'\n | 'number'\n | 'string'\n | 'non-empty string';\n\n/**\n * Validates that no arguments were passed in the invocation of functionName.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateNoArgs('myFunction', arguments);\n */\nexport function validateNoArgs(functionName: string, args: IArguments): void {\n if (args.length !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() does not support arguments, ` +\n 'but was called with ' +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the invocation of functionName has the exact number of arguments.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateExactNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateExactNumberOfArgs(\n functionName: string,\n args: IArguments,\n numberOfArgs: number\n): void {\n if (args.length !== numberOfArgs) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires ` +\n formatPlural(numberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the invocation of functionName has at least the provided number of\n * arguments (but can have many more).\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\n */\nexport function validateAtLeastNumberOfArgs(\n functionName: string,\n args: IArguments,\n minNumberOfArgs: number\n): void {\n if (args.length < minNumberOfArgs) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires at least ` +\n formatPlural(minNumberOfArgs, 'argument') +\n ', but was called with ' +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the invocation of functionName has number of arguments between\n * the values provided.\n *\n * Forward the magic \"arguments\" variable as second parameter on which the\n * parameter validation is performed:\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\n */\nexport function validateBetweenNumberOfArgs(\n functionName: string,\n args: IArguments,\n minNumberOfArgs: number,\n maxNumberOfArgs: number\n): void {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires between ${minNumberOfArgs} and ` +\n `${maxNumberOfArgs} arguments, but was called with ` +\n formatPlural(args.length, 'argument') +\n '.'\n );\n }\n}\n\n/**\n * Validates the provided argument is an array and has as least the expected\n * number of elements.\n */\nexport function validateNamedArrayAtLeastNumberOfElements<T>(\n functionName: string,\n value: T[],\n name: string,\n minNumberOfElements: number\n): void {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${name} argument to be an ` +\n 'array with at least ' +\n `${formatPlural(minNumberOfElements, 'element')}.`\n );\n }\n}\n\n/**\n * Validates the provided positional argument has the native JavaScript type\n * using typeof checks.\n */\nexport function validateArgType(\n functionName: string,\n type: ValidationType,\n position: number,\n argument: unknown\n): void {\n validateType(functionName, type, `${ordinal(position)} argument`, argument);\n}\n\n/**\n * Validates the provided argument has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateOptionalArgType(\n functionName: string,\n type: ValidationType,\n position: number,\n argument: unknown\n): void {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks.\n */\nexport function validateNamedType(\n functionName: string,\n type: ValidationType,\n optionName: string,\n argument: unknown\n): void {\n validateType(functionName, type, `${optionName} option`, argument);\n}\n\n/**\n * Validates the provided named option has the native JavaScript type using\n * typeof checks or is undefined.\n */\nexport function validateNamedOptionalType(\n functionName: string,\n type: ValidationType,\n optionName: string,\n argument: unknown\n): void {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n\nexport function validateArrayElements<T>(\n functionName: string,\n optionName: string,\n typeDescription: string,\n argument: T[],\n validator: (arg0: T) => boolean\n): void {\n if (!(argument instanceof Array)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${optionName} ` +\n `option to be an array, but it was: ${valueDescription(argument)}`\n );\n }\n\n for (let i = 0; i < argument.length; ++i) {\n if (!validator(argument[i])) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires all ${optionName} ` +\n `elements to be ${typeDescription}, but the value at index ${i} ` +\n `was: ${valueDescription(argument[i])}`\n );\n }\n }\n}\n\nexport function validateOptionalArrayElements<T>(\n functionName: string,\n optionName: string,\n typeDescription: string,\n argument: T[] | undefined,\n validator: (arg0: T) => boolean\n): void {\n if (argument !== undefined) {\n validateArrayElements(\n functionName,\n optionName,\n typeDescription,\n argument,\n validator\n );\n }\n}\n\n/**\n * Validates that the provided named option equals one of the expected values.\n */\nexport function validateNamedPropertyEquals<T>(\n functionName: string,\n inputName: string,\n optionName: string,\n input: T,\n expected: T[]\n): void {\n const expectedDescription: string[] = [];\n\n for (const val of expected) {\n if (val === input) {\n return;\n }\n expectedDescription.push(valueDescription(val));\n }\n\n const actualDescription = valueDescription(input);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid value ${actualDescription} provided to function ${functionName}() for option ` +\n `\"${optionName}\". Acceptable values: ${expectedDescription.join(', ')}`\n );\n}\n\n/**\n * Validates that the provided named option equals one of the expected values or\n * is undefined.\n */\nexport function validateNamedOptionalPropertyEquals<T>(\n functionName: string,\n inputName: string,\n optionName: string,\n input: T,\n expected: T[]\n): void {\n if (input !== undefined) {\n validateNamedPropertyEquals(\n functionName,\n inputName,\n optionName,\n input,\n expected\n );\n }\n}\n\n/**\n * Validates that the provided argument is a valid enum.\n *\n * @param functionName Function making the validation call.\n * @param enums Array containing all possible values for the enum.\n * @param position Position of the argument in `functionName`.\n * @param argument Arugment to validate.\n */\nexport function validateStringEnum<T>(\n functionName: string,\n enums: string[],\n position: number,\n argument: unknown\n): void {\n if (!enums.some(element => element === argument)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid value ${valueDescription(argument)} provided to function ` +\n `${functionName}() for its ${ordinal(position)} argument. Acceptable ` +\n `values: ${enums.join(', ')}`\n );\n }\n}\n\n/** Helper to validate the type of a provided input. */\nfunction validateType(\n functionName: string,\n type: ValidationType,\n inputName: string,\n input: unknown\n): void {\n let valid = false;\n if (type === 'object') {\n valid = isPlainObject(input);\n } else if (type === 'non-empty string') {\n valid = typeof input === 'string' && input !== '';\n } else {\n valid = typeof input === type;\n }\n\n if (!valid) {\n const description = valueDescription(input);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${inputName} ` +\n `to be of type ${type}, but it was: ${description}`\n );\n }\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\nexport function isPlainObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n (Object.getPrototypeOf(input) === Object.prototype ||\n Object.getPrototypeOf(input) === null)\n );\n}\n\n/** Returns a string describing the type / value of the provided input. */\nexport function valueDescription(input: unknown): string {\n if (input === undefined) {\n return 'undefined';\n } else if (input === null) {\n return 'null';\n } else if (typeof input === 'string') {\n if (input.length > 20) {\n input = `${input.substring(0, 20)}...`;\n }\n return JSON.stringify(input);\n } else if (typeof input === 'number' || typeof input === 'boolean') {\n return '' + input;\n } else if (typeof input === 'object') {\n if (input instanceof Array) {\n return 'an array';\n } else {\n const customObjectName = tryGetCustomObjectType(input!);\n if (customObjectName) {\n return `a custom ${customObjectName} object`;\n } else {\n return 'an object';\n }\n }\n } else if (typeof input === 'function') {\n return 'a function';\n } else {\n return fail('Unknown wrong type: ' + typeof input);\n }\n}\n\n/** Hacky method to try to get the constructor name for an object. */\nexport function tryGetCustomObjectType(input: object): string | null {\n if (input.constructor) {\n const funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n const results = funcNameRegex.exec(input.constructor.toString());\n if (results && results.length > 1) {\n return results[1];\n }\n }\n return null;\n}\n\n/** Validates the provided argument is defined. */\nexport function validateDefined(\n functionName: string,\n position: number,\n argument: unknown\n): void {\n if (argument === undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires a valid ${ordinal(position)} ` +\n `argument, but it was undefined.`\n );\n }\n}\n\n/**\n * Validates the provided positional argument is an object, and its keys and\n * values match the expected keys and types provided in optionTypes.\n */\nexport function validateOptionNames(\n functionName: string,\n options: object,\n optionNames: string[]\n): void {\n obj.forEach(options as obj.Dict<unknown>, (key, _) => {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Unknown option '${key}' passed to function ${functionName}(). ` +\n 'Available options: ' +\n optionNames.join(', ')\n );\n }\n });\n}\n\n/**\n * Helper method to throw an error that the provided argument did not pass\n * an instanceof check.\n */\nexport function invalidClassError(\n functionName: string,\n type: string,\n position: number,\n argument: unknown\n): Error {\n const description = valueDescription(argument);\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${functionName}() requires its ${ordinal(position)} ` +\n `argument to be a ${type}, but it was: ${description}`\n );\n}\n\nexport function validatePositiveNumber(\n functionName: string,\n position: number,\n n: number\n): void {\n if (n <= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function \"${functionName}()\" requires its ${ordinal(\n position\n )} argument to be a positive number, but it was: ${n}.`\n );\n }\n}\n\n/** Converts a number to its english word representation */\nfunction ordinal(num: number): string {\n switch (num) {\n case 1:\n return 'first';\n case 2:\n return 'second';\n case 3:\n return 'third';\n default:\n return num + 'th';\n }\n}\n\n/**\n * Formats the given word as plural conditionally given the preceding number.\n */\nfunction formatPlural(num: number, str: string): string {\n return `${num} ${str}` + (num === 1 ? '' : 's');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PlatformSupport } from '../platform/platform';\n\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n */\nexport class ByteString {\n static readonly EMPTY_BYTE_STRING = new ByteString('');\n\n private readonly _binaryString: string;\n\n private constructor(binaryString: string) {\n this._binaryString = binaryString;\n }\n\n static fromBase64String(base64: string): ByteString {\n const binaryString = PlatformSupport.getPlatform().atob(base64);\n return new ByteString(binaryString);\n }\n\n static fromUint8Array(array: Uint8Array): ByteString {\n const binaryString = binaryStringFromUint8Array(array);\n return new ByteString(binaryString);\n }\n\n toBase64(): string {\n return PlatformSupport.getPlatform().btoa(this._binaryString);\n }\n\n toUint8Array(): Uint8Array {\n return uint8ArrayFromBinaryString(this._binaryString);\n }\n\n approximateByteSize(): number {\n return this._binaryString.length * 2;\n }\n\n isEqual(other: ByteString): boolean {\n return this._binaryString === other._binaryString;\n }\n}\n\n/**\n * Helper function to convert an Uint8array to a binary string.\n */\nexport function binaryStringFromUint8Array(array: Uint8Array): string {\n let binaryString = '';\n for (let i = 0; i < array.length; ++i) {\n binaryString += String.fromCharCode(array[i]);\n }\n return binaryString;\n}\n\n/**\n * Helper function to convert a binary string to an Uint8Array.\n */\nexport function uint8ArrayFromBinaryString(binaryString: string): Uint8Array {\n const buffer = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n buffer[i] = binaryString.charCodeAt(i);\n }\n return buffer;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n invalidClassError,\n validateArgType,\n validateExactNumberOfArgs\n} from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\nimport {\n binaryStringFromUint8Array,\n uint8ArrayFromBinaryString\n} from '../util/byte_string';\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable(): void {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'Uint8Arrays are not available in this environment.'\n );\n }\n}\n\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available(): void {\n if (!PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'Blobs are unavailable in Firestore in this environment.'\n );\n }\n}\n\n/**\n * Immutable class holding a blob (binary data).\n * This class is directly exposed in the public API.\n *\n * Note that while you can't hide the constructor in JavaScript code, we are\n * using the hack above to make sure no-one outside this module can call it.\n */\nexport class Blob {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion.\n // A binary string is a string with each char as Unicode code point in the\n // range of [0, 255], essentially simulating a byte array.\n private _binaryString: string;\n\n private constructor(binaryString: string) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n\n static fromBase64String(base64: string): Blob {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n try {\n const binaryString = PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to construct Blob from Base64 string: ' + e\n );\n }\n }\n\n static fromUint8Array(array: Uint8Array): Blob {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n }\n const binaryString = binaryStringFromUint8Array(array);\n return new Blob(binaryString);\n }\n\n toBase64(): string {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return PlatformSupport.getPlatform().btoa(this._binaryString);\n }\n\n toUint8Array(): Uint8Array {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n const buffer = uint8ArrayFromBinaryString(this._binaryString);\n return buffer;\n }\n\n toString(): string {\n return 'Blob(base64: ' + this.toBase64() + ')';\n }\n\n isEqual(other: Blob): boolean {\n return this._binaryString === other._binaryString;\n }\n\n _approximateByteSize(): number {\n // Assume UTF-16 encoding in memory (see StringValue.approximateByteSize())\n return this._binaryString.length * 2;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: Blob): number {\n return primitiveComparator(this._binaryString, other._binaryString);\n }\n}\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\nexport const PublicBlob = makeConstructorPrivate(\n Blob,\n 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.'\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Code, FirestoreError } from '../util/error';\nimport {\n validateArgType,\n validateExactNumberOfArgs\n} from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\n\n/**\n * Immutable class representing a geo point as latitude-longitude pair.\n * This class is directly exposed in the public API, including its constructor.\n */\nexport class GeoPoint {\n // Prefix with underscore to signal this is a private variable in JS and\n // prevent it showing up for autocompletion when typing latitude or longitude.\n private _lat: number;\n private _long: number;\n\n constructor(latitude: number, longitude: number) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Latitude must be a number between -90 and 90, but was: ' + latitude\n );\n }\n if (!isFinite(longitude) || longitude < -180 || longitude > 180) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Longitude must be a number between -180 and 180, but was: ' + longitude\n );\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n /**\n * Returns the latitude of this geo point, a number between -90 and 90.\n */\n get latitude(): number {\n return this._lat;\n }\n\n /**\n * Returns the longitude of this geo point, a number between -180 and 180.\n */\n get longitude(): number {\n return this._long;\n }\n\n isEqual(other: GeoPoint): boolean {\n return this._lat === other._lat && this._long === other._long;\n }\n\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */\n _compareTo(other: GeoPoint): number {\n return (\n primitiveComparator(this._lat, other._lat) ||\n primitiveComparator(this._long, other._long)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Code, FirestoreError } from '../util/error';\nimport { primitiveComparator } from '../util/misc';\n\n// The earlist date supported by Firestore timestamps (0001-01-01T00:00:00Z).\nconst MIN_SECONDS = -62135596800;\n\nexport class Timestamp {\n static now(): Timestamp {\n return Timestamp.fromMillis(Date.now());\n }\n\n static fromDate(date: Date): Timestamp {\n return Timestamp.fromMillis(date.getTime());\n }\n\n static fromMillis(milliseconds: number): Timestamp {\n const seconds = Math.floor(milliseconds / 1000);\n const nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n }\n\n constructor(readonly seconds: number, readonly nanoseconds: number) {\n if (nanoseconds < 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp nanoseconds out of range: ' + nanoseconds\n );\n }\n if (seconds < MIN_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n // This will break in the year 10,000.\n if (seconds >= 253402300800) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Timestamp seconds out of range: ' + seconds\n );\n }\n }\n\n toDate(): Date {\n return new Date(this.toMillis());\n }\n\n toMillis(): number {\n return this.seconds * 1000 + this.nanoseconds / 1e6;\n }\n\n _compareTo(other: Timestamp): number {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n return primitiveComparator(this.seconds, other.seconds);\n }\n\n isEqual(other: Timestamp): boolean {\n return (\n other.seconds === this.seconds && other.nanoseconds === this.nanoseconds\n );\n }\n\n toString(): string {\n return (\n 'Timestamp(seconds=' +\n this.seconds +\n ', nanoseconds=' +\n this.nanoseconds +\n ')'\n );\n }\n\n valueOf(): string {\n // This method returns a string of the form <seconds>.<nanoseconds> where <seconds> is\n // translated to have a non-negative value and both <seconds> and <nanoseconds> are left-padded\n // with zeroes to be a consistent length. Strings with this format then have a lexiographical\n // ordering that matches the expected ordering. The <seconds> translation is done to avoid\n // having a leading negative sign (i.e. a leading '-' character) in its string representation,\n // which would affect its lexiographical ordering.\n const adjustedSeconds = this.seconds - MIN_SECONDS;\n // Note: Up to 12 decimal digits are required to represent all valid 'seconds' values.\n const formattedSeconds = String(adjustedSeconds).padStart(12, '0');\n const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0');\n return formattedSeconds + '.' + formattedNanoseconds;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\n\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */\nexport class SnapshotVersion {\n static readonly MIN = new SnapshotVersion(new Timestamp(0, 0));\n\n // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n static fromMicroseconds(value: number): SnapshotVersion {\n const seconds = Math.floor(value / 1e6);\n const nanos = (value % 1e6) * 1e3;\n return new SnapshotVersion(new Timestamp(seconds, nanos));\n }\n\n static fromTimestamp(value: Timestamp): SnapshotVersion {\n return new SnapshotVersion(value);\n }\n\n static forDeletedDoc(): SnapshotVersion {\n return SnapshotVersion.MIN;\n }\n\n private constructor(private timestamp: Timestamp) {}\n\n compareTo(other: SnapshotVersion): number {\n return this.timestamp._compareTo(other.timestamp);\n }\n\n isEqual(other: SnapshotVersion): boolean {\n return this.timestamp.isEqual(other.timestamp);\n }\n\n /** Returns a number representation of the version for use in spec tests. */\n toMicroseconds(): number {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n }\n\n toString(): string {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n }\n\n toTimestamp(): Timestamp {\n return this.timestamp;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DOCUMENT_KEY_NAME = '__name__';\n\n/**\n * Path represents an ordered sequence of string segments.\n */\nabstract class BasePath<B extends BasePath<B>> {\n private segments: string[];\n private offset: number;\n private len: number;\n\n constructor(segments: string[], offset?: number, length?: number) {\n if (offset === undefined) {\n offset = 0;\n } else if (offset > segments.length) {\n fail('offset ' + offset + ' out of range ' + segments.length);\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail('length ' + length + ' out of range ' + (segments.length - offset));\n }\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n }\n\n /**\n * Abstract constructor method to construct an instance of B with the given\n * parameters.\n */\n protected abstract construct(\n segments: string[],\n offset?: number,\n length?: number\n ): B;\n\n /**\n * Returns a String representation.\n *\n * Implementing classes are required to provide deterministic implementations as\n * the String representation is used to obtain canonical Query IDs.\n */\n abstract toString(): string;\n\n get length(): number {\n return this.len;\n }\n\n isEqual(other: B): boolean {\n return BasePath.comparator(this, other) === 0;\n }\n\n child(nameOrPath: string | B): B {\n const segments = this.segments.slice(this.offset, this.limit());\n if (nameOrPath instanceof BasePath) {\n nameOrPath.forEach(segment => {\n segments.push(segment);\n });\n } else {\n segments.push(nameOrPath);\n }\n return this.construct(segments);\n }\n\n /** The index of one past the last segment of the path. */\n private limit(): number {\n return this.offset + this.length;\n }\n\n popFirst(size?: number): B {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(\n this.segments,\n this.offset + size,\n this.length - size\n );\n }\n\n popLast(): B {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n\n firstSegment(): string {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n }\n\n lastSegment(): string {\n return this.get(this.length - 1);\n }\n\n get(index: number): string {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n }\n\n isEmpty(): boolean {\n return this.length === 0;\n }\n\n isPrefixOf(other: this): boolean {\n if (other.length < this.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== other.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n isImmediateParentOf(potentialChild: this): boolean {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (let i = 0; i < this.length; i++) {\n if (this.get(i) !== potentialChild.get(i)) {\n return false;\n }\n }\n\n return true;\n }\n\n forEach(fn: (segment: string) => void): void {\n for (let i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n }\n\n toArray(): string[] {\n return this.segments.slice(this.offset, this.limit());\n }\n\n static comparator<T extends BasePath<T>>(\n p1: BasePath<T>,\n p2: BasePath<T>\n ): number {\n const len = Math.min(p1.length, p2.length);\n for (let i = 0; i < len; i++) {\n const left = p1.get(i);\n const right = p2.get(i);\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n }\n if (p1.length < p2.length) {\n return -1;\n }\n if (p1.length > p2.length) {\n return 1;\n }\n return 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n */\nexport class ResourcePath extends BasePath<ResourcePath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): ResourcePath {\n return new ResourcePath(segments, offset, length);\n }\n\n canonicalString(): string {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n return this.toArray().join('/');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Creates a resource path from the given slash-delimited string.\n */\n static fromString(path: string): ResourcePath {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n\n if (path.indexOf('//') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid path (${path}). Paths must not contain // in them.`\n );\n }\n\n // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n const segments = path.split('/').filter(segment => segment.length > 0);\n\n return new ResourcePath(segments);\n }\n\n static EMPTY_PATH = new ResourcePath([]);\n}\n\nconst identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/** A dot-separated path for navigating sub-objects within a document. */\nexport class FieldPath extends BasePath<FieldPath> {\n protected construct(\n segments: string[],\n offset?: number,\n length?: number\n ): FieldPath {\n return new FieldPath(segments, offset, length);\n }\n\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */\n private static isValidIdentifier(segment: string): boolean {\n return identifierRegExp.test(segment);\n }\n\n canonicalString(): string {\n return this.toArray()\n .map(str => {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n return str;\n })\n .join('.');\n }\n\n toString(): string {\n return this.canonicalString();\n }\n\n /**\n * Returns true if this field references the key of a document.\n */\n isKeyField(): boolean {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n }\n\n /**\n * The field designating the key of a document.\n */\n static keyField(): FieldPath {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n }\n\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */\n static fromServerFormat(path: string): FieldPath {\n const segments: string[] = [];\n let current = '';\n let i = 0;\n\n const addCurrentSegment = (): void => {\n if (current.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, begin ` +\n `with '.', end with '.', or contain '..'`\n );\n }\n segments.push(current);\n current = '';\n };\n\n let inBackticks = false;\n\n while (i < path.length) {\n const c = path[i];\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has trailing escape character: ' + path\n );\n }\n const next = path[i + 1];\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Path has invalid escape sequence: ' + path\n );\n }\n current += next;\n i += 2;\n } else if (c === '`') {\n inBackticks = !inBackticks;\n i++;\n } else if (c === '.' && !inBackticks) {\n addCurrentSegment();\n i++;\n } else {\n current += c;\n i++;\n }\n }\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unterminated ` in path: ' + path\n );\n }\n\n return new FieldPath(segments);\n }\n\n static EMPTY_PATH = new FieldPath([]);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../util/assert';\n\nimport { ResourcePath } from './path';\n\nexport class DocumentKey {\n constructor(readonly path: ResourcePath) {\n assert(\n DocumentKey.isDocumentKey(path),\n 'Invalid DocumentKey with an odd number of segments: ' +\n path.toArray().join('/')\n );\n }\n\n /** Returns true if the document is in the specified collectionId. */\n hasCollectionId(collectionId: string): boolean {\n return (\n this.path.length >= 2 &&\n this.path.get(this.path.length - 2) === collectionId\n );\n }\n\n isEqual(other: DocumentKey | null): boolean {\n return (\n other !== null && ResourcePath.comparator(this.path, other.path) === 0\n );\n }\n\n toString(): string {\n return this.path.toString();\n }\n\n static EMPTY = new DocumentKey(new ResourcePath([]));\n\n static comparator(k1: DocumentKey, k2: DocumentKey): number {\n return ResourcePath.comparator(k1.path, k2.path);\n }\n\n static isDocumentKey(path: ResourcePath): boolean {\n return path.length % 2 === 0;\n }\n\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param path The segments of the path to the document\n * @return A new instance of DocumentKey\n */\n static fromSegments(segments: string[]): DocumentKey {\n return new DocumentKey(new ResourcePath(segments.slice()));\n }\n\n /**\n * Creates and returns a new document key using '/' to split the string into\n * segments.\n *\n * @param path The slash-separated path string to the document\n * @return A new instance of DocumentKey\n */\n static fromPathString(path: string): DocumentKey {\n return new DocumentKey(ResourcePath.fromString(path));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, fail } from './assert';\n\n/*\n * 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\nexport type Comparator<K> = (key1: K, key2: K) => number;\n\nexport interface Entry<K, V> {\n key: K;\n value: V;\n}\n\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nexport class SortedMap<K, V> {\n // visible for testing\n root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n\n constructor(\n public comparator: Comparator<K>,\n root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.root = root ? root : LLRBNode.EMPTY;\n }\n\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(key: K, value: V): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .insert(key, value, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns a copy of the map, with the specified key removed.\n remove(key: K): SortedMap<K, V> {\n return new SortedMap<K, V>(\n this.comparator,\n this.root\n .remove(key, this.comparator)\n .copy(null, null, LLRBNode.BLACK, null, null)\n );\n }\n\n // Returns the value of the node with the given key, or null.\n get(key: K): V | null {\n let node = this.root;\n while (!node.isEmpty()) {\n const 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 // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(key: K): number {\n // Number of nodes that were pruned when descending right\n let prunedNodes = 0;\n let node = this.root;\n while (!node.isEmpty()) {\n const cmp = this.comparator(key, node.key);\n if (cmp === 0) {\n return prunedNodes + node.left.size;\n } else if (cmp < 0) {\n node = node.left;\n } else {\n // Count all nodes left of the node plus the node itself\n prunedNodes += node.left.size + 1;\n node = node.right;\n }\n }\n // Node not found\n return -1;\n }\n\n isEmpty(): boolean {\n return this.root.isEmpty();\n }\n\n // Returns the total number of nodes in the map.\n get size(): number {\n return this.root.size;\n }\n\n // Returns the minimum key in the map.\n minKey(): K | null {\n return this.root.minKey();\n }\n\n // Returns the maximum key in the map.\n maxKey(): K | null {\n return this.root.maxKey();\n }\n\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).inorderTraversal(action);\n }\n\n forEach(fn: (k: K, v: V) => void): void {\n this.inorderTraversal((k, v) => {\n fn(k, v);\n return false;\n });\n }\n\n toString(): string {\n const descriptions: string[] = [];\n this.inorderTraversal((k, v) => {\n descriptions.push(`${k}:${v}`);\n return false;\n });\n return `{${descriptions.join(', ')}}`;\n }\n\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal<T>(action: (k: K, v: V) => T): T {\n return (this.root as LLRBNode<K, V>).reverseTraversal(action);\n }\n\n // Returns an iterator over the SortedMap.\n getIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);\n }\n\n getIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);\n }\n\n getReverseIterator(): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);\n }\n\n getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {\n return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);\n }\n} // end SortedMap\n\n// An iterator over an LLRBNode.\nexport class SortedMapIterator<K, V> {\n private isReverse: boolean;\n private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;\n\n constructor(\n node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n startKey: K | null,\n comparator: Comparator<K>,\n isReverse: boolean\n ) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n\n let cmp = 1;\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1;\n // flip the comparison if we're going in reverse\n if (isReverse) {\n cmp *= -1;\n }\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,\n // 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\n // 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(): Entry<K, V> {\n assert(\n this.nodeStack.length > 0,\n 'getNext() called on iterator when hasNext() is false.'\n );\n\n let node = this.nodeStack.pop()!;\n const result = { key: node.key, value: node.value };\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(): Entry<K, V> | null {\n if (this.nodeStack.length === 0) {\n return null;\n }\n\n const node = this.nodeStack[this.nodeStack.length - 1];\n return { key: node.key, value: node.value };\n }\n} // end SortedMapIterator\n\n// Represents a node in a Left-leaning Red-Black tree.\nexport class LLRBNode<K, V> {\n readonly color: boolean;\n readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;\n readonly size: number;\n\n // Empty node is shared between all LLRB trees.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n static EMPTY: LLRBEmptyNode<any, any> = null as any;\n\n static RED = true;\n static BLACK = false;\n\n constructor(\n public key: K,\n public value: V,\n color?: boolean,\n left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,\n right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>\n ) {\n this.color = color != null ? color : LLRBNode.RED;\n this.left = left != null ? left : LLRBNode.EMPTY;\n this.right = right != null ? right : LLRBNode.EMPTY;\n this.size = this.left.size + 1 + this.right.size;\n }\n\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBNode<K, V> {\n return new LLRBNode<K, V>(\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 isEmpty(): boolean {\n return false;\n }\n\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal<T>(action: (k: K, v: V) => T): T {\n return (\n (this.left as LLRBNode<K, V>).inorderTraversal(action) ||\n action(this.key, this.value) ||\n (this.right as LLRBNode<K, V>).inorderTraversal(action)\n );\n }\n\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal<T>(action: (k: K, v: V) => T): T {\n return (\n (this.right as LLRBNode<K, V>).reverseTraversal(action) ||\n action(this.key, this.value) ||\n (this.left as LLRBNode<K, V>).reverseTraversal(action)\n );\n }\n\n // Returns the minimum node in the tree.\n private min(): LLRBNode<K, V> {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return (this.left as LLRBNode<K, V>).min();\n }\n }\n\n // Returns the maximum key in the tree.\n minKey(): K | null {\n return this.min().key;\n }\n\n // Returns the maximum key in the tree.\n maxKey(): K | null {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }\n\n // Returns new tree, with the key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n const 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 private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n let n: LLRBNode<K, V> = this;\n if (!n.left.isRed() && !n.left.left.isRed()) {\n n = n.moveRedLeft();\n }\n n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);\n return n.fixUp();\n }\n\n // Returns new tree, with the specified item removed.\n remove(\n key: K,\n comparator: Comparator<K>\n ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {\n let smallest: LLRBNode<K, V>;\n let n: LLRBNode<K, V> = 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 = n.rotateRight();\n }\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 LLRBNode.EMPTY;\n } else {\n smallest = (n.right as LLRBNode<K, V>).min();\n n = n.copy(\n smallest.key,\n smallest.value,\n null,\n null,\n (n.right as LLRBNode<K, V>).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 isRed(): boolean {\n return this.color;\n }\n\n // Returns new tree after performing any needed rotations.\n private fixUp(): LLRBNode<K, V> {\n let n: LLRBNode<K, V> = this;\n if (n.right.isRed() && !n.left.isRed()) {\n n = n.rotateLeft();\n }\n if (n.left.isRed() && n.left.left.isRed()) {\n n = n.rotateRight();\n }\n if (n.left.isRed() && n.right.isRed()) {\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedLeft(): LLRBNode<K, V> {\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<K, V>).rotateRight()\n );\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n return n;\n }\n\n private moveRedRight(): LLRBNode<K, V> {\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 private rotateLeft(): LLRBNode<K, V> {\n const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return (this.right as LLRBNode<K, V>).copy(\n null,\n null,\n this.color,\n nl,\n null\n );\n }\n\n private rotateRight(): LLRBNode<K, V> {\n const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);\n }\n\n private colorFlip(): LLRBNode<K, V> {\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 // For testing.\n checkMaxDepth(): boolean {\n const blackDepth = this.check();\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\n }\n }\n\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n protected check(): number {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n const blackDepth = (this.left as LLRBNode<K, V>).check();\n if (blackDepth !== (this.right as LLRBNode<K, V>).check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }\n} // end LLRBNode\n\n// Represents an empty node (a leaf node in the Red-Black Tree).\nexport class LLRBEmptyNode<K, V> {\n get key(): never {\n throw fail('LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail('LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail('LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail('LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail('LLRBEmptyNode has no right child.');\n }\n size = 0;\n\n // Returns a copy of the current node.\n copy(\n key: K | null,\n value: V | null,\n color: boolean | null,\n left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,\n right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null\n ): LLRBEmptyNode<K, V> {\n return this;\n }\n\n // Returns a copy of the tree, with the specified key/value added.\n insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {\n return new LLRBNode<K, V>(key, value);\n }\n\n // Returns a copy of the tree, with the specified key removed.\n remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {\n return this;\n }\n\n isEmpty(): boolean {\n return true;\n }\n\n inorderTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n reverseTraversal(action: (k: K, v: V) => boolean): boolean {\n return false;\n }\n\n minKey(): K | null {\n return null;\n }\n\n maxKey(): K | null {\n return null;\n }\n\n isRed(): boolean {\n return false;\n }\n\n // For testing.\n checkMaxDepth(): boolean {\n return true;\n }\n\n protected check(): 0 {\n return 0;\n }\n} // end LLRBEmptyNode\n\nLLRBNode.EMPTY = new LLRBEmptyNode<unknown, unknown>();\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, SortedMapIterator } from './sorted_map';\n\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nexport class SortedSet<T> {\n private data: SortedMap<T, boolean>;\n\n constructor(private comparator: (left: T, right: T) => number) {\n this.data = new SortedMap<T, boolean>(this.comparator);\n }\n\n /**\n * Creates a SortedSet from the keys of the map.\n * This is currently implemented as an O(n) copy.\n */\n static fromMapKeys<K, V>(map: SortedMap<K, V>): SortedSet<K> {\n let keys = new SortedSet<K>(map.comparator);\n map.forEach(key => {\n keys = keys.add(key);\n });\n return keys;\n }\n\n has(elem: T): boolean {\n return this.data.get(elem) !== null;\n }\n\n first(): T | null {\n return this.data.minKey();\n }\n\n last(): T | null {\n return this.data.maxKey();\n }\n\n get size(): number {\n return this.data.size;\n }\n\n indexOf(elem: T): number {\n return this.data.indexOf(elem);\n }\n\n /** Iterates elements in order defined by \"comparator\" */\n forEach(cb: (elem: T) => void): void {\n this.data.inorderTraversal((k: T, v: boolean) => {\n cb(k);\n return false;\n });\n }\n\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n forEachInRange(range: [T, T], cb: (elem: T) => void): void {\n const iter = this.data.getIteratorFrom(range[0]);\n while (iter.hasNext()) {\n const elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) {\n return;\n }\n cb(elem.key);\n }\n }\n\n /**\n * Iterates over `elem`s such that: start <= elem until false is returned.\n */\n forEachWhile(cb: (elem: T) => boolean, start?: T): void {\n let iter: SortedMapIterator<T, boolean>;\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n while (iter.hasNext()) {\n const elem = iter.getNext();\n const result = cb(elem.key);\n if (!result) {\n return;\n }\n }\n }\n\n /** Finds the least element greater than or equal to `elem`. */\n firstAfterOrEqual(elem: T): T | null {\n const iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n }\n\n getIterator(): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIterator());\n }\n\n getIteratorFrom(key: T): SortedSetIterator<T> {\n return new SortedSetIterator<T>(this.data.getIteratorFrom(key));\n }\n\n /** Inserts or updates an element */\n add(elem: T): SortedSet<T> {\n return this.copy(this.data.remove(elem).insert(elem, true));\n }\n\n /** Deletes an element */\n delete(elem: T): SortedSet<T> {\n if (!this.has(elem)) {\n return this;\n }\n return this.copy(this.data.remove(elem));\n }\n\n isEmpty(): boolean {\n return this.data.isEmpty();\n }\n\n unionWith(other: SortedSet<T>): SortedSet<T> {\n let result: SortedSet<T> = this;\n\n // Make sure `result` always refers to the larger one of the two sets.\n if (result.size < other.size) {\n result = other;\n other = this;\n }\n\n other.forEach(elem => {\n result = result.add(elem);\n });\n return result;\n }\n\n isEqual(other: SortedSet<T>): boolean {\n if (!(other instanceof SortedSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.data.getIterator();\n const otherIt = other.data.getIterator();\n while (thisIt.hasNext()) {\n const thisElem = thisIt.getNext().key;\n const otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) {\n return false;\n }\n }\n return true;\n }\n\n toArray(): T[] {\n const res: T[] = [];\n this.forEach(targetId => {\n res.push(targetId);\n });\n return res;\n }\n\n toString(): string {\n const result: T[] = [];\n this.forEach(elem => result.push(elem));\n return 'SortedSet(' + result.toString() + ')';\n }\n\n private copy(data: SortedMap<T, boolean>): SortedSet<T> {\n const result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n }\n}\n\nexport class SortedSetIterator<T> {\n constructor(private iter: SortedMapIterator<T, boolean>) {}\n\n getNext(): T {\n return this.iter.getNext().key;\n }\n\n hasNext(): boolean {\n return this.iter.hasNext();\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\nimport {\n ArrayValue,\n DoubleValue,\n FieldValue,\n IntegerValue,\n NumberValue,\n ServerTimestampValue\n} from './field_value';\n\n/** Represents a transform within a TransformMutation. */\nexport interface TransformOperation {\n /**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue;\n\n /**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue;\n\n /**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @return a base value to store along with the mutation, or null for\n * idempotent transforms.\n */\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null;\n\n isEqual(other: TransformOperation): boolean;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nexport class ServerTimestampTransform implements TransformOperation {\n private constructor() {}\n static instance = new ServerTimestampTransform();\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n return new ServerTimestampValue(localWriteTime!, previousValue);\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\n return transformResult!;\n }\n\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null {\n return null; // Server timestamps are idempotent and don't require a base value.\n }\n\n isEqual(other: TransformOperation): boolean {\n return other instanceof ServerTimestampTransform;\n }\n}\n\n/** Transforms an array value via a union operation. */\nexport class ArrayUnionTransformOperation implements TransformOperation {\n constructor(readonly elements: FieldValue[]) {}\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n return this.apply(previousValue);\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return this.apply(previousValue);\n }\n\n private apply(previousValue: FieldValue | null): FieldValue {\n const result = coercedFieldValuesArray(previousValue);\n for (const toUnion of this.elements) {\n if (!result.find(element => element.isEqual(toUnion))) {\n result.push(toUnion);\n }\n }\n return new ArrayValue(result);\n }\n\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null {\n return null; // Array transforms are idempotent and don't require a base value.\n }\n\n isEqual(other: TransformOperation): boolean {\n return (\n other instanceof ArrayUnionTransformOperation &&\n misc.arrayEquals(other.elements, this.elements)\n );\n }\n}\n\n/** Transforms an array value via a remove operation. */\nexport class ArrayRemoveTransformOperation implements TransformOperation {\n constructor(readonly elements: FieldValue[]) {}\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n return this.apply(previousValue);\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return this.apply(previousValue);\n }\n\n private apply(previousValue: FieldValue | null): FieldValue {\n let result = coercedFieldValuesArray(previousValue);\n for (const toRemove of this.elements) {\n result = result.filter(element => !element.isEqual(toRemove));\n }\n return new ArrayValue(result);\n }\n\n computeBaseValue(previousValue: FieldValue | null): FieldValue | null {\n return null; // Array transforms are idempotent and don't require a base value.\n }\n\n isEqual(other: TransformOperation): boolean {\n return (\n other instanceof ArrayRemoveTransformOperation &&\n misc.arrayEquals(other.elements, this.elements)\n );\n }\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */\nexport class NumericIncrementTransformOperation implements TransformOperation {\n constructor(readonly operand: NumberValue) {}\n\n applyToLocalView(\n previousValue: FieldValue | null,\n localWriteTime: Timestamp\n ): FieldValue {\n const baseValue = this.computeBaseValue(previousValue);\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n\n // Return an integer value iff the previous value and the operand is an\n // integer.\n if (\n baseValue instanceof IntegerValue &&\n this.operand instanceof IntegerValue\n ) {\n const sum = baseValue.internalValue + this.operand.internalValue;\n return new IntegerValue(sum);\n } else {\n const sum = baseValue.internalValue + this.operand.internalValue;\n return new DoubleValue(sum);\n }\n }\n\n applyToRemoteDocument(\n previousValue: FieldValue | null,\n transformResult: FieldValue | null\n ): FieldValue {\n assert(\n transformResult !== null,\n \"Didn't receive transformResult for NUMERIC_ADD transform\"\n );\n return transformResult;\n }\n\n /**\n * Inspects the provided value, returning the provided value if it is already\n * a NumberValue, otherwise returning a coerced IntegerValue of 0.\n */\n computeBaseValue(previousValue: FieldValue | null): NumberValue {\n return previousValue instanceof NumberValue\n ? previousValue\n : new IntegerValue(0);\n }\n\n isEqual(other: TransformOperation): boolean {\n return (\n other instanceof NumericIncrementTransformOperation &&\n this.operand.isEqual(other.operand)\n );\n }\n}\n\nfunction coercedFieldValuesArray(value: FieldValue | null): FieldValue[] {\n if (value instanceof ArrayValue) {\n return value.internalValue.slice();\n } else {\n // coerce to empty array.\n return [];\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\nimport * as misc from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n Document,\n MaybeDocument,\n NoDocument,\n UnknownDocument\n} from './document';\nimport { DocumentKey } from './document_key';\nimport { FieldValue, ObjectValue, ObjectValueBuilder } from './field_value';\nimport { FieldPath } from './path';\nimport { TransformOperation } from './transform_operation';\n\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */\nexport class FieldMask {\n constructor(readonly fields: SortedSet<FieldPath>) {\n // TODO(dimond): validation of FieldMask\n }\n\n static fromSet(fields: SortedSet<FieldPath>): FieldMask {\n return new FieldMask(fields);\n }\n\n static fromArray(fields: FieldPath[]): FieldMask {\n let fieldsAsSet = new SortedSet<FieldPath>(FieldPath.comparator);\n fields.forEach(fieldPath => (fieldsAsSet = fieldsAsSet.add(fieldPath)));\n return new FieldMask(fieldsAsSet);\n }\n\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */\n covers(fieldPath: FieldPath): boolean {\n let found = false;\n this.fields.forEach(fieldMaskPath => {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n found = true;\n }\n });\n return found;\n }\n\n isEqual(other: FieldMask): boolean {\n return this.fields.isEqual(other.fields);\n }\n}\n\n/** A field path and the TransformOperation to perform upon it. */\nexport class FieldTransform {\n constructor(\n readonly field: FieldPath,\n readonly transform: TransformOperation\n ) {}\n\n isEqual(other: FieldTransform): boolean {\n return (\n this.field.isEqual(other.field) && this.transform.isEqual(other.transform)\n );\n }\n}\n\n/** The result of successfully applying a mutation to the backend. */\nexport class MutationResult {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n readonly version: SnapshotVersion,\n /**\n * The resulting fields returned from the backend after a\n * TransformMutation has been committed. Contains one FieldValue for each\n * FieldTransform that was in the mutation.\n *\n * Will be null if the mutation was not a TransformMutation.\n */\n readonly transformResults: Array<FieldValue | null> | null\n ) {}\n}\n\nexport const enum MutationType {\n Set,\n Patch,\n Transform,\n Delete,\n Verify\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */\nexport class Precondition {\n static readonly NONE = new Precondition();\n\n private constructor(\n readonly updateTime?: SnapshotVersion,\n readonly exists?: boolean\n ) {\n assert(\n updateTime === undefined || exists === undefined,\n 'Precondition can specify \"exists\" or \"updateTime\" but not both'\n );\n }\n\n /** Creates a new Precondition with an exists flag. */\n static exists(exists: boolean): Precondition {\n return new Precondition(undefined, exists);\n }\n\n /** Creates a new Precondition based on a version a document exists at. */\n static updateTime(version: SnapshotVersion): Precondition {\n return new Precondition(version);\n }\n\n /** Returns whether this Precondition is empty. */\n get isNone(): boolean {\n return this.updateTime === undefined && this.exists === undefined;\n }\n\n /**\n * Returns true if the preconditions is valid for the given document\n * (or null if no document is available).\n */\n isValidFor(maybeDoc: MaybeDocument | null): boolean {\n if (this.updateTime !== undefined) {\n return (\n maybeDoc instanceof Document &&\n maybeDoc.version.isEqual(this.updateTime)\n );\n } else if (this.exists !== undefined) {\n return this.exists === maybeDoc instanceof Document;\n } else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n }\n\n isEqual(other: Precondition): boolean {\n return (\n misc.equals(this.updateTime, other.updateTime) &&\n this.exists === other.exists\n );\n }\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set, Patch, and Transform mutations. For Delete\n * mutations, we reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation null Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation null null\n * TransformMutation Document(v3) Document(v3)\n * TransformMutation NoDocument(v3) NoDocument(v3)\n * TransformMutation null null\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation null NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set, Patch, and Transform mutations. As deletes\n * have no explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we return an `UnknownDocument` and rely on Watch to send us the\n * updated version.\n *\n * Note that TransformMutations don't create Documents (in the case of being\n * applied to a NoDocument), even though they would on the backend. This is\n * because the client always combines the TransformMutation with a SetMutation\n * or PatchMutation and we only want to apply the transform if the prior\n * mutation resulted in a Document (always true for a SetMutation, but not\n * necessarily for a PatchMutation).\n *\n * ## Subclassing Notes\n *\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document.\n */\nexport abstract class Mutation {\n abstract readonly type: MutationType;\n abstract readonly key: DocumentKey;\n abstract readonly precondition: Precondition;\n\n /**\n * Applies this mutation to the given MaybeDocument or null for the purposes\n * of computing a new remote document. If the input document doesn't match the\n * expected state (e.g. it is null or outdated), an `UnknownDocument` can be\n * returned.\n *\n * @param maybeDoc The document to mutate. The input document can be null if\n * the client has no knowledge of the pre-mutation state of the document.\n * @param mutationResult The result of applying the mutation from the backend.\n * @return The mutated document. The returned document may be an\n * UnknownDocument if the mutation could not be applied to the locally\n * cached base document.\n */\n abstract applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument;\n\n /**\n * Applies this mutation to the given MaybeDocument or null for the purposes\n * of computing the new local view of a document. Both the input and returned\n * documents can be null.\n *\n * @param maybeDoc The document to mutate. The input document can be null if\n * the client has no knowledge of the pre-mutation state of the document.\n * @param baseDoc The state of the document prior to this mutation batch. The\n * input document can be null if the client has no knowledge of the\n * pre-mutation state of the document.\n * @param localWriteTime A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @return The mutated document. The returned document may be null, but only\n * if maybeDoc was null and the mutation would not create a new document.\n */\n abstract applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null;\n\n /**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @return a base value to store along with the mutation, or null for\n * idempotent mutations.\n */\n abstract extractBaseValue(maybeDoc: MaybeDocument | null): ObjectValue | null;\n\n abstract isEqual(other: Mutation): boolean;\n\n protected verifyKeyMatches(maybeDoc: MaybeDocument | null): void {\n if (maybeDoc != null) {\n assert(\n maybeDoc.key.isEqual(this.key),\n 'Can only apply a mutation to a document with the same key'\n );\n }\n }\n\n /**\n * Returns the version from the given document for use as the result of a\n * mutation. Mutations are defined to return the version of the base document\n * only if it is an existing document. Deleted and unknown documents have a\n * post-mutation version of SnapshotVersion.MIN.\n */\n protected static getPostMutationVersion(\n maybeDoc: MaybeDocument | null\n ): SnapshotVersion {\n if (maybeDoc instanceof Document) {\n return maybeDoc.version;\n } else {\n return SnapshotVersion.MIN;\n }\n }\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */\nexport class SetMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly value: ObjectValue,\n readonly precondition: Precondition\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Set;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults == null,\n 'Transform results received by SetMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n\n const version = mutationResult.version;\n return new Document(\n this.key,\n version,\n {\n hasCommittedMutations: true\n },\n this.value\n );\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n const version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(\n this.key,\n version,\n {\n hasLocalMutations: true\n },\n this.value\n );\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n return null;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof SetMutation &&\n this.key.isEqual(other.key) &&\n this.value.isEqual(other.value) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n}\n\n/**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */\nexport class PatchMutation extends Mutation {\n constructor(\n readonly key: DocumentKey,\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly precondition: Precondition\n ) {\n super();\n }\n\n readonly type: MutationType = MutationType.Patch;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults == null,\n 'Transform results received by PatchMutation.'\n );\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and return an UnknownDocument with the\n // known updateTime.\n return new UnknownDocument(this.key, mutationResult.version);\n }\n\n const newData = this.patchDocument(maybeDoc);\n return new Document(\n this.key,\n mutationResult.version,\n {\n hasCommittedMutations: true\n },\n newData\n );\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n const version = Mutation.getPostMutationVersion(maybeDoc);\n const newData = this.patchDocument(maybeDoc);\n return new Document(\n this.key,\n version,\n {\n hasLocalMutations: true\n },\n newData\n );\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n return null;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof PatchMutation &&\n this.key.isEqual(other.key) &&\n this.fieldMask.isEqual(other.fieldMask) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n\n /**\n * Patches the data of document if available or creates a new document. Note\n * that this does not check whether or not the precondition of this patch\n * holds.\n */\n private patchDocument(maybeDoc: MaybeDocument | null): ObjectValue {\n let data: ObjectValue;\n if (maybeDoc instanceof Document) {\n data = maybeDoc.data();\n } else {\n data = ObjectValue.EMPTY;\n }\n return this.patchObject(data);\n }\n\n private patchObject(data: ObjectValue): ObjectValue {\n const builder = data.toBuilder();\n this.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = this.data.field(fieldPath);\n if (newValue !== null) {\n builder.set(fieldPath, newValue);\n } else {\n builder.delete(fieldPath);\n }\n }\n });\n return builder.build();\n }\n}\n\n/**\n * A mutation that modifies specific fields of the document with transform\n * operations. Currently the only supported transform is a server timestamp, but\n * IP Address, increment(n), etc. could be supported in the future.\n *\n * It is somewhat similar to a PatchMutation in that it patches specific fields\n * and has no effect when applied to a null or NoDocument (see comment on\n * Mutation for rationale).\n */\nexport class TransformMutation extends Mutation {\n readonly type: MutationType = MutationType.Transform;\n\n // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n readonly precondition = Precondition.exists(true);\n\n constructor(\n readonly key: DocumentKey,\n readonly fieldTransforms: FieldTransform[]\n ) {\n super();\n }\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults != null,\n 'Transform results missing for TransformMutation.'\n );\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and return an UnknownDocument with the\n // known updateTime.\n return new UnknownDocument(this.key, mutationResult.version);\n }\n\n const doc = this.requireDocument(maybeDoc);\n const transformResults = this.serverTransformResults(\n maybeDoc,\n mutationResult.transformResults!\n );\n\n const version = mutationResult.version;\n const newData = this.transformObject(doc.data(), transformResults);\n return new Document(\n this.key,\n version,\n {\n hasCommittedMutations: true\n },\n newData\n );\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n const doc = this.requireDocument(maybeDoc);\n const transformResults = this.localTransformResults(\n localWriteTime,\n maybeDoc,\n baseDoc\n );\n const newData = this.transformObject(doc.data(), transformResults);\n return new Document(\n this.key,\n doc.version,\n {\n hasLocalMutations: true\n },\n newData\n );\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): ObjectValue | null {\n let baseObject: ObjectValueBuilder | null = null;\n for (const fieldTransform of this.fieldTransforms) {\n const existingValue =\n maybeDoc instanceof Document\n ? maybeDoc.field(fieldTransform.field)\n : undefined;\n const coercedValue = fieldTransform.transform.computeBaseValue(\n existingValue || null\n );\n\n if (coercedValue != null) {\n if (baseObject == null) {\n baseObject = ObjectValue.newBuilder().set(\n fieldTransform.field,\n coercedValue\n );\n } else {\n baseObject = baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n }\n return baseObject ? baseObject.build() : null;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof TransformMutation &&\n this.key.isEqual(other.key) &&\n misc.arrayEquals(this.fieldTransforms, other.fieldTransforms) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n\n /**\n * Asserts that the given MaybeDocument is actually a Document and verifies\n * that it matches the key for this mutation. Since we only support\n * transformations with precondition exists this method is guaranteed to be\n * safe.\n */\n private requireDocument(maybeDoc: MaybeDocument | null): Document {\n assert(\n maybeDoc instanceof Document,\n 'Unknown MaybeDocument type ' + maybeDoc\n );\n assert(\n maybeDoc.key.isEqual(this.key),\n 'Can only transform a document with the same key'\n );\n return maybeDoc;\n }\n\n /**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a\n * TransformMutation has been acknowledged by the server.\n *\n * @param baseDoc The document prior to applying this mutation batch.\n * @param serverTransformResults The transform results received by the server.\n * @return The transform results list.\n */\n private serverTransformResults(\n baseDoc: MaybeDocument | null,\n serverTransformResults: Array<FieldValue | null>\n ): FieldValue[] {\n const transformResults = [] as FieldValue[];\n assert(\n this.fieldTransforms.length === serverTransformResults.length,\n `server transform result count (${serverTransformResults.length}) ` +\n `should match field transform count (${this.fieldTransforms.length})`\n );\n\n for (let i = 0; i < serverTransformResults.length; i++) {\n const fieldTransform = this.fieldTransforms[i];\n const transform = fieldTransform.transform;\n let previousValue: FieldValue | null = null;\n if (baseDoc instanceof Document) {\n previousValue = baseDoc.field(fieldTransform.field);\n }\n transformResults.push(\n transform.applyToRemoteDocument(\n previousValue,\n serverTransformResults[i]\n )\n );\n }\n return transformResults;\n }\n\n /**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * TransformMutation locally.\n *\n * @param localWriteTime The local time of the transform mutation (used to\n * generate ServerTimestampValues).\n * @param maybeDoc The current state of the document after applying all\n * previous mutations.\n * @param baseDoc The document prior to applying this mutation batch.\n * @return The transform results list.\n */\n private localTransformResults(\n localWriteTime: Timestamp,\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null\n ): FieldValue[] {\n const transformResults = [] as FieldValue[];\n for (const fieldTransform of this.fieldTransforms) {\n const transform = fieldTransform.transform;\n\n let previousValue: FieldValue | null = null;\n if (maybeDoc instanceof Document) {\n previousValue = maybeDoc.field(fieldTransform.field);\n }\n\n if (previousValue === null && baseDoc instanceof Document) {\n // If the current document does not contain a value for the mutated\n // field, use the value that existed before applying this mutation\n // batch. This solves an edge case where a PatchMutation clears the\n // values in a nested map before the TransformMutation is applied.\n previousValue = baseDoc.field(fieldTransform.field);\n }\n\n transformResults.push(\n transform.applyToLocalView(previousValue, localWriteTime)\n );\n }\n return transformResults;\n }\n\n private transformObject(\n data: ObjectValue,\n transformResults: FieldValue[]\n ): ObjectValue {\n assert(\n transformResults.length === this.fieldTransforms.length,\n 'TransformResults length mismatch.'\n );\n\n const builder = data.toBuilder();\n for (let i = 0; i < this.fieldTransforms.length; i++) {\n const fieldTransform = this.fieldTransforms[i];\n const fieldPath = fieldTransform.field;\n builder.set(fieldPath, transformResults[i]);\n }\n return builder.build();\n }\n}\n\n/** A mutation that deletes the document at the given key. */\nexport class DeleteMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Delete;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n this.verifyKeyMatches(maybeDoc);\n\n assert(\n mutationResult.transformResults == null,\n 'Transform results received by DeleteMutation.'\n );\n\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n\n return new NoDocument(this.key, mutationResult.version, {\n hasCommittedMutations: true\n });\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n if (maybeDoc) {\n assert(\n maybeDoc.key.isEqual(this.key),\n 'Can only apply mutation to document with same key'\n );\n }\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n return null;\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof DeleteMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n}\n\n/**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */\nexport class VerifyMutation extends Mutation {\n constructor(readonly key: DocumentKey, readonly precondition: Precondition) {\n super();\n }\n\n readonly type: MutationType = MutationType.Verify;\n\n applyToRemoteDocument(\n maybeDoc: MaybeDocument | null,\n mutationResult: MutationResult\n ): MaybeDocument {\n fail('VerifyMutation should only be used in Transactions.');\n }\n\n applyToLocalView(\n maybeDoc: MaybeDocument | null,\n baseDoc: MaybeDocument | null,\n localWriteTime: Timestamp\n ): MaybeDocument | null {\n fail('VerifyMutation should only be used in Transactions.');\n }\n\n extractBaseValue(maybeDoc: MaybeDocument | null): null {\n fail('VerifyMutation should only be used in Transactions.');\n }\n\n isEqual(other: Mutation): boolean {\n return (\n other instanceof VerifyMutation &&\n this.key.isEqual(other.key) &&\n this.precondition.isEqual(other.precondition)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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';\nimport { PlatformSupport } from '../platform/platform';\n\nexport type EventHandler<E> = (value: E) => void;\nexport interface Indexable {\n [k: string]: unknown;\n}\n\nexport class AutoId {\n static newId(): string {\n // Alphanumeric characters\n const chars =\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n let autoId = '';\n while (autoId.length < 20) {\n const bytes = PlatformSupport.getPlatform().randomBytes(40);\n bytes.forEach(b => {\n // Length of `chars` is 62. We only take bytes between 0 and 62*4-1\n // (both inclusive). The value is then evenly mapped to indices of `char`\n // via a modulo operation.\n const maxValue = 62 * 4 - 1;\n if (autoId.length < 20 && b <= maxValue) {\n autoId += chars.charAt(b % 62);\n }\n });\n }\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n }\n}\n\nexport function primitiveComparator<T>(left: T, right: T): number {\n if (left < right) {\n return -1;\n }\n if (left > right) {\n return 1;\n }\n return 0;\n}\n\n/** Duck-typed interface for objects that have an isEqual() method. */\nexport interface Equatable<T> {\n isEqual(other: T): boolean;\n}\n\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\nexport function equals<T>(\n left: Equatable<T> | null | undefined,\n right: T | null | undefined\n): boolean {\n if (left !== null && left !== undefined) {\n return !!(right && left.isEqual(right));\n } else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return (left as null | undefined) === right;\n }\n}\n\n/** Helper to compare arrays using isEqual(). */\nexport function arrayEquals<T>(left: Array<Equatable<T>>, right: T[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n\n for (let i = 0; i < left.length; i++) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */\nexport function immediateSuccessor(s: string): string {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Blob } from '../api/blob';\nimport { SnapshotOptions } from '../api/database';\nimport { GeoPoint } from '../api/geo_point';\nimport { Timestamp } from '../api/timestamp';\nimport { DatabaseId } from '../core/database_info';\nimport { assert, fail } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { DocumentKey } from './document_key';\nimport { FieldMask } from './mutation';\nimport { FieldPath } from './path';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\n/**\n * Supported data value types:\n * - Null\n * - Boolean\n * - Long\n * - Double\n * - String\n * - Object\n * - Array\n * - Binary\n * - Timestamp\n * - ServerTimestamp (a sentinel used in uncommitted writes)\n * - GeoPoint\n * - (Document) References\n */\n\nexport interface JsonObject<T> {\n [name: string]: T;\n}\n\nexport const enum TypeOrder {\n // This order is defined by the backend.\n NullValue = 0,\n BooleanValue = 1,\n NumberValue = 2,\n TimestampValue = 3,\n StringValue = 4,\n BlobValue = 5,\n RefValue = 6,\n GeoPointValue = 7,\n ArrayValue = 8,\n ObjectValue = 9\n}\n\n/** Defines the return value for pending server timestamps. */\nexport const enum ServerTimestampBehavior {\n Default,\n Estimate,\n Previous\n}\n\n/** Holds properties that define field value deserialization options. */\nexport class FieldValueOptions {\n constructor(\n readonly serverTimestampBehavior: ServerTimestampBehavior,\n readonly timestampsInSnapshots: boolean\n ) {}\n\n static fromSnapshotOptions(\n options: SnapshotOptions,\n timestampsInSnapshots: boolean\n ): FieldValueOptions {\n switch (options.serverTimestamps) {\n case 'estimate':\n return new FieldValueOptions(\n ServerTimestampBehavior.Estimate,\n timestampsInSnapshots\n );\n case 'previous':\n return new FieldValueOptions(\n ServerTimestampBehavior.Previous,\n timestampsInSnapshots\n );\n case 'none': // Fall-through intended.\n case undefined:\n return new FieldValueOptions(\n ServerTimestampBehavior.Default,\n timestampsInSnapshots\n );\n default:\n return fail('fromSnapshotOptions() called with invalid options.');\n }\n }\n}\n\n/**\n * Potential types returned by FieldValue.value(). This could be stricter\n * (instead of using {}), but there's little benefit.\n *\n * Note that currently we use AnyJs (which is identical except includes\n * undefined) for incoming user data as a convenience to the calling code (but\n * we'll throw if the data contains undefined). This should probably be changed\n * to use FieldType, but all consuming code will have to be updated to\n * explicitly handle undefined and then cast to FieldType or similar. Perhaps\n * we should tackle this when adding robust argument validation to the API.\n */\nexport type FieldType = null | boolean | number | string | {};\n\n/**\n * A field value represents a datatype as stored by Firestore.\n */\nexport abstract class FieldValue {\n abstract readonly typeOrder: TypeOrder;\n\n abstract value(options?: FieldValueOptions): FieldType;\n abstract isEqual(other: FieldValue): boolean;\n abstract compareTo(other: FieldValue): number;\n\n /**\n * Returns an approximate (and wildly inaccurate) in-memory size for the field\n * value.\n *\n * The memory size takes into account only the actual user data as it resides\n * in memory and ignores object overhead.\n */\n abstract approximateByteSize(): number;\n\n toString(): string {\n const val = this.value();\n return val === null ? 'null' : val.toString();\n }\n\n defaultCompareTo(other: FieldValue): number {\n assert(\n this.typeOrder !== other.typeOrder,\n 'Default compareTo should not be used for values of same type.'\n );\n const cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n }\n}\n\nexport class NullValue extends FieldValue {\n typeOrder = TypeOrder.NullValue;\n\n // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n readonly internalValue = null;\n\n private constructor() {\n super();\n }\n\n value(options?: FieldValueOptions): null {\n return null;\n }\n\n isEqual(other: FieldValue): boolean {\n return other instanceof NullValue;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof NullValue) {\n return 0;\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return 4;\n }\n\n static INSTANCE = new NullValue();\n}\n\nexport class BooleanValue extends FieldValue {\n typeOrder = TypeOrder.BooleanValue;\n\n private constructor(readonly internalValue: boolean) {\n super();\n }\n\n value(options?: FieldValueOptions): boolean {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof BooleanValue &&\n this.internalValue === other.internalValue\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return 4;\n }\n\n static of(value: boolean): BooleanValue {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n }\n\n static TRUE = new BooleanValue(true);\n static FALSE = new BooleanValue(false);\n}\n\n/** Base class for IntegerValue and DoubleValue. */\nexport abstract class NumberValue extends FieldValue {\n typeOrder = TypeOrder.NumberValue;\n\n constructor(readonly internalValue: number) {\n super();\n }\n\n value(options?: FieldValueOptions): number {\n return this.internalValue;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return 8;\n }\n}\n\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\nfunction numericComparator(left: number, right: number): number {\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n } else if (left === right) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n\n/**\n * Utility function to check numbers for equality using Firestore semantics\n * (NaN === NaN, -0.0 !== 0.0).\n */\nfunction numericEquals(left: number, right: number): boolean {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n } else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\n\nexport class IntegerValue extends NumberValue {\n isEqual(other: FieldValue): boolean {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n } else {\n return false;\n }\n }\n\n // NOTE: compareTo() is implemented in NumberValue.\n}\n\nexport class DoubleValue extends NumberValue {\n static NAN = new DoubleValue(NaN);\n static POSITIVE_INFINITY = new DoubleValue(Infinity);\n static NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n\n isEqual(other: FieldValue): boolean {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n } else {\n return false;\n }\n }\n\n // NOTE: compareTo() is implemented in NumberValue.\n}\n\n// TODO(b/37267885): Add truncation support\nexport class StringValue extends FieldValue {\n typeOrder = TypeOrder.StringValue;\n\n constructor(readonly internalValue: string) {\n super();\n }\n\n value(options?: FieldValueOptions): string {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof StringValue && this.internalValue === other.internalValue\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:\n // \"JavaScript's String type is [...] a set of elements of 16-bit unsigned\n // integer values\"\n return this.internalValue.length * 2;\n }\n}\n\nexport class TimestampValue extends FieldValue {\n typeOrder = TypeOrder.TimestampValue;\n\n constructor(readonly internalValue: Timestamp) {\n super();\n }\n\n value(options?: FieldValueOptions): Date | Timestamp {\n if (!options || options.timestampsInSnapshots) {\n return this.internalValue;\n } else {\n return this.internalValue.toDate();\n }\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof TimestampValue &&\n this.internalValue.isEqual(other.internalValue)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof TimestampValue) {\n return this.internalValue._compareTo(other.internalValue);\n } else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n approximateByteSize(): number {\n // Timestamps are made up of two distinct numbers (seconds + nanoseconds)\n return 16;\n }\n}\n\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\n * the local view of a document. Therefore they do not need to be parsed or\n * serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */\nexport class ServerTimestampValue extends FieldValue {\n typeOrder = TypeOrder.TimestampValue;\n\n constructor(\n readonly localWriteTime: Timestamp,\n readonly previousValue: FieldValue | null\n ) {\n super();\n }\n\n value(options?: FieldValueOptions): FieldType {\n if (\n options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Estimate\n ) {\n return new TimestampValue(this.localWriteTime).value(options);\n } else if (\n options &&\n options.serverTimestampBehavior === ServerTimestampBehavior.Previous\n ) {\n return this.previousValue ? this.previousValue.value(options) : null;\n } else {\n return null;\n }\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof ServerTimestampValue &&\n this.localWriteTime.isEqual(other.localWriteTime)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime._compareTo(other.localWriteTime);\n } else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n toString(): string {\n return '<ServerTimestamp localTime=' + this.localWriteTime.toString() + '>';\n }\n\n approximateByteSize(): number {\n return (\n /* localWriteTime */ 16 +\n (this.previousValue ? this.previousValue.approximateByteSize() : 0)\n );\n }\n}\n\nexport class BlobValue extends FieldValue {\n typeOrder = TypeOrder.BlobValue;\n\n constructor(readonly internalValue: Blob) {\n super();\n }\n\n value(options?: FieldValueOptions): Blob {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof BlobValue &&\n this.internalValue.isEqual(other.internalValue)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return this.internalValue._approximateByteSize();\n }\n}\n\nexport class RefValue extends FieldValue {\n typeOrder = TypeOrder.RefValue;\n\n constructor(readonly databaseId: DatabaseId, readonly key: DocumentKey) {\n super();\n }\n\n value(options?: FieldValueOptions): DocumentKey {\n return this.key;\n }\n\n isEqual(other: FieldValue): boolean {\n if (other instanceof RefValue) {\n return (\n this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId)\n );\n } else {\n return false;\n }\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof RefValue) {\n const cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n return (\n this.databaseId.projectId.length +\n this.databaseId.database.length +\n this.key.toString().length\n );\n }\n}\n\nexport class GeoPointValue extends FieldValue {\n typeOrder = TypeOrder.GeoPointValue;\n\n constructor(readonly internalValue: GeoPoint) {\n super();\n }\n\n value(options?: FieldValueOptions): GeoPoint {\n return this.internalValue;\n }\n\n isEqual(other: FieldValue): boolean {\n return (\n other instanceof GeoPointValue &&\n this.internalValue.isEqual(other.internalValue)\n );\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n return this.defaultCompareTo(other);\n }\n\n approximateByteSize(): number {\n // GeoPoints are made up of two distinct numbers (latitude + longitude)\n return 16;\n }\n}\n\nexport class ObjectValue extends FieldValue {\n typeOrder = TypeOrder.ObjectValue;\n\n constructor(readonly internalValue: SortedMap<string, FieldValue>) {\n super();\n }\n\n /** Returns a new ObjectValueBuilder instance that is based on an empty object. */\n static newBuilder(): ObjectValueBuilder {\n return new ObjectValueBuilder(ObjectValue.EMPTY.internalValue);\n }\n\n value(options?: FieldValueOptions): JsonObject<FieldType> {\n const result: JsonObject<FieldType> = {};\n this.internalValue.inorderTraversal((key, val) => {\n result[key] = val.value(options);\n });\n return result;\n }\n\n forEach(action: (key: string, value: FieldValue) => void): void {\n this.internalValue.inorderTraversal(action);\n }\n\n isEqual(other: FieldValue): boolean {\n if (other instanceof ObjectValue) {\n const it1 = this.internalValue.getIterator();\n const it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n const next1 = it1.getNext();\n const next2 = it2.getNext();\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\n return false;\n }\n }\n\n return !it1.hasNext() && !it2.hasNext();\n }\n\n return false;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof ObjectValue) {\n const it1 = this.internalValue.getIterator();\n const it2 = other.internalValue.getIterator();\n while (it1.hasNext() && it2.hasNext()) {\n const next1: { key: string; value: FieldValue } = it1.getNext();\n const next2: { key: string; value: FieldValue } = it2.getNext();\n const cmp =\n primitiveComparator(next1.key, next2.key) ||\n next1.value.compareTo(next2.value);\n if (cmp) {\n return cmp;\n }\n }\n\n // Only equal if both iterators are exhausted\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n contains(path: FieldPath): boolean {\n return this.field(path) !== null;\n }\n\n field(path: FieldPath): FieldValue | null {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n let field: FieldValue | null = this;\n path.forEach((pathSegment: string) => {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment);\n } else {\n field = null;\n }\n });\n return field;\n }\n\n /**\n * Returns a FieldMask built from all FieldPaths starting from this ObjectValue,\n * including paths from nested objects.\n */\n fieldMask(): FieldMask {\n let fields = new SortedSet<FieldPath>(FieldPath.comparator);\n this.internalValue.forEach((key, value) => {\n const currentPath = new FieldPath([key]);\n if (value instanceof ObjectValue) {\n const nestedMask = value.fieldMask();\n const nestedFields = nestedMask.fields;\n if (nestedFields.isEmpty()) {\n // Preserve the empty map by adding it to the FieldMask.\n fields = fields.add(currentPath);\n } else {\n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n nestedFields.forEach(nestedPath => {\n fields = fields.add(currentPath.child(nestedPath));\n });\n }\n } else {\n fields = fields.add(currentPath);\n }\n });\n return FieldMask.fromSet(fields);\n }\n\n approximateByteSize(): number {\n let size = 0;\n this.internalValue.inorderTraversal((key, val) => {\n size += key.length + val.approximateByteSize();\n });\n return size;\n }\n\n toString(): string {\n return this.internalValue.toString();\n }\n\n static EMPTY = new ObjectValue(\n new SortedMap<string, FieldValue>(primitiveComparator)\n );\n\n /** Creates a ObjectValueBuilder instance that is based on the current value. */\n toBuilder(): ObjectValueBuilder {\n return new ObjectValueBuilder(this.internalValue);\n }\n}\n\n/**\n * An ObjectValueBuilder provides APIs to set and delete fields from an\n * ObjectValue. All operations mutate the existing instance.\n */\nexport class ObjectValueBuilder {\n constructor(private internalValue: SortedMap<string, FieldValue>) {}\n\n /**\n * Sets the field to the provided value.\n *\n * @param path The field path to set.\n * @param value The value to set.\n * @return The current Builder instance.\n */\n set(path: FieldPath, value: FieldValue): ObjectValueBuilder {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n const childName = path.firstSegment();\n if (path.length === 1) {\n this.internalValue = this.internalValue.insert(childName, value);\n } else {\n // nested field\n const child = this.internalValue.get(childName);\n let obj: ObjectValue;\n if (child instanceof ObjectValue) {\n obj = child;\n } else {\n obj = ObjectValue.EMPTY;\n }\n const newChild = obj\n .toBuilder()\n .set(path.popFirst(), value)\n .build();\n this.internalValue = this.internalValue.insert(childName, newChild);\n }\n return this;\n }\n\n /**\n * Removes the field at the current path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path The field path to remove\n * @return The current Builder instance.\n */\n delete(path: FieldPath): ObjectValueBuilder {\n assert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n const childName = path.firstSegment();\n if (path.length === 1) {\n this.internalValue = this.internalValue.remove(childName);\n } else {\n // nested field\n const child = this.internalValue.get(childName);\n if (child instanceof ObjectValue) {\n const newChild = child\n .toBuilder()\n .delete(path.popFirst())\n .build();\n this.internalValue = this.internalValue.insert(\n path.firstSegment(),\n newChild\n );\n } else {\n // Don't actually change a primitive value to an object for a delete\n }\n }\n return this;\n }\n\n build(): ObjectValue {\n return new ObjectValue(this.internalValue);\n }\n}\n\nexport class ArrayValue extends FieldValue {\n typeOrder = TypeOrder.ArrayValue;\n\n constructor(readonly internalValue: FieldValue[]) {\n super();\n }\n\n value(options?: FieldValueOptions): FieldType[] {\n return this.internalValue.map(v => v.value(options));\n }\n\n /**\n * Returns true if the given value is contained in this array.\n */\n contains(value: FieldValue): boolean {\n for (const element of this.internalValue) {\n if (element.isEqual(value)) {\n return true;\n }\n }\n return false;\n }\n\n forEach(action: (value: FieldValue) => void): void {\n this.internalValue.forEach(action);\n }\n\n isEqual(other: FieldValue): boolean {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n\n for (let i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n }\n\n compareTo(other: FieldValue): number {\n if (other instanceof ArrayValue) {\n const minLength = Math.min(\n this.internalValue.length,\n other.internalValue.length\n );\n\n for (let i = 0; i < minLength; i++) {\n const cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n\n if (cmp) {\n return cmp;\n }\n }\n\n return primitiveComparator(\n this.internalValue.length,\n other.internalValue.length\n );\n } else {\n return this.defaultCompareTo(other);\n }\n }\n\n approximateByteSize(): number {\n return this.internalValue.reduce(\n (totalSize, value) => totalSize + value.approximateByteSize(),\n 0\n );\n }\n\n toString(): string {\n const descriptions = this.internalValue.map(v => v.toString());\n return `[${descriptions.join(',')}]`;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\n\nimport { DocumentKey } from './document_key';\nimport { FieldValue, JsonObject, ObjectValue } from './field_value';\nimport { FieldPath } from './path';\n\nimport * as api from '../protos/firestore_proto_api';\nimport * as obj from '../util/obj';\n\nexport interface DocumentOptions {\n hasLocalMutations?: boolean;\n hasCommittedMutations?: boolean;\n}\n\n/**\n * The result of a lookup for a given path may be an existing document or a\n * marker that this document does not exist at a given version.\n */\nexport abstract class MaybeDocument {\n constructor(readonly key: DocumentKey, readonly version: SnapshotVersion) {}\n\n static compareByKey(d1: MaybeDocument, d2: MaybeDocument): number {\n return DocumentKey.comparator(d1.key, d2.key);\n }\n\n /**\n * Whether this document had a local mutation applied that has not yet been\n * acknowledged by Watch.\n */\n abstract get hasPendingWrites(): boolean;\n\n abstract isEqual(other: MaybeDocument | null | undefined): boolean;\n\n abstract toString(): string;\n}\n\n/**\n * Represents a document in Firestore with a key, version, data and whether the\n * data has local mutations applied to it.\n */\nexport class Document extends MaybeDocument {\n readonly hasLocalMutations: boolean;\n readonly hasCommittedMutations: boolean;\n\n /**\n * A cache of canonicalized FieldPaths to FieldValues that have already been\n * deserialized in `getField()`.\n */\n private fieldValueCache?: Map<string, FieldValue | null>;\n\n constructor(\n key: DocumentKey,\n version: SnapshotVersion,\n options: DocumentOptions,\n private objectValue?: ObjectValue,\n readonly proto?: api.Document,\n private readonly converter?: (value: api.Value) => FieldValue\n ) {\n super(key, version);\n assert(\n this.objectValue !== undefined ||\n (this.proto !== undefined && this.converter !== undefined),\n 'If objectValue is not defined, proto and converter need to be set.'\n );\n\n this.hasLocalMutations = !!options.hasLocalMutations;\n this.hasCommittedMutations = !!options.hasCommittedMutations;\n }\n\n field(path: FieldPath): FieldValue | null {\n if (this.objectValue) {\n return this.objectValue.field(path);\n } else {\n if (!this.fieldValueCache) {\n // TODO(b/136090445): Remove the cache when `getField` is no longer\n // called during Query ordering.\n this.fieldValueCache = new Map<string, FieldValue>();\n }\n\n const canonicalPath = path.canonicalString();\n\n let fieldValue = this.fieldValueCache.get(canonicalPath);\n\n if (fieldValue === undefined) {\n // Instead of deserializing the full Document proto, we only\n // deserialize the value at the requested field path. This speeds up\n // Query execution as query filters can discard documents based on a\n // single field.\n const protoValue = this.getProtoField(path);\n if (protoValue === undefined) {\n fieldValue = null;\n } else {\n fieldValue = this.converter!(protoValue);\n }\n this.fieldValueCache.set(canonicalPath, fieldValue);\n }\n\n return fieldValue!;\n }\n }\n\n data(): ObjectValue {\n if (!this.objectValue) {\n const result = ObjectValue.newBuilder();\n obj.forEach(this.proto!.fields || {}, (key: string, value: api.Value) => {\n result.set(new FieldPath([key]), this.converter!(value));\n });\n this.objectValue = result.build();\n\n // Once objectValue is computed, values inside the fieldValueCache are no\n // longer accessed.\n this.fieldValueCache = undefined;\n }\n\n return this.objectValue;\n }\n\n value(): JsonObject<unknown> {\n return this.data().value();\n }\n\n isEqual(other: MaybeDocument | null | undefined): boolean {\n return (\n other instanceof Document &&\n this.key.isEqual(other.key) &&\n this.version.isEqual(other.version) &&\n this.hasLocalMutations === other.hasLocalMutations &&\n this.hasCommittedMutations === other.hasCommittedMutations &&\n this.data().isEqual(other.data())\n );\n }\n\n toString(): string {\n return (\n `Document(${this.key}, ${this.version}, ${this.data().toString()}, ` +\n `{hasLocalMutations: ${this.hasLocalMutations}}), ` +\n `{hasCommittedMutations: ${this.hasCommittedMutations}})`\n );\n }\n\n get hasPendingWrites(): boolean {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n\n /**\n * Returns the nested Protobuf value for 'path`. Can only be called if\n * `proto` was provided at construction time.\n */\n private getProtoField(path: FieldPath): api.Value | undefined {\n assert(\n this.proto !== undefined,\n 'Can only call getProtoField() when proto is defined'\n );\n\n let protoValue: api.Value | undefined = this.proto!.fields\n ? this.proto!.fields[path.firstSegment()]\n : undefined;\n for (let i = 1; i < path.length; ++i) {\n if (!protoValue || !protoValue.mapValue || !protoValue.mapValue.fields) {\n return undefined;\n }\n protoValue = protoValue.mapValue.fields[path.get(i)];\n }\n\n return protoValue;\n }\n\n static compareByField(field: FieldPath, d1: Document, d2: Document): number {\n const v1 = d1.field(field);\n const v2 = d2.field(field);\n if (v1 !== null && v2 !== null) {\n return v1.compareTo(v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n }\n}\n\n/**\n * A class representing a deleted document.\n * Version is set to 0 if we don't point to any specific time, otherwise it\n * denotes time we know it didn't exist at.\n */\nexport class NoDocument extends MaybeDocument {\n readonly hasCommittedMutations: boolean;\n\n constructor(\n key: DocumentKey,\n version: SnapshotVersion,\n options?: DocumentOptions\n ) {\n super(key, version);\n this.hasCommittedMutations = !!(options && options.hasCommittedMutations);\n }\n\n toString(): string {\n return `NoDocument(${this.key}, ${this.version})`;\n }\n\n get hasPendingWrites(): boolean {\n return this.hasCommittedMutations;\n }\n\n isEqual(other: MaybeDocument | null | undefined): boolean {\n return (\n other instanceof NoDocument &&\n other.hasCommittedMutations === this.hasCommittedMutations &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key)\n );\n }\n}\n\n/**\n * A class representing an existing document whose data is unknown (e.g. a\n * document that was updated without a known base document).\n */\nexport class UnknownDocument extends MaybeDocument {\n toString(): string {\n return `UnknownDocument(${this.key}, ${this.version})`;\n }\n\n get hasPendingWrites(): boolean {\n return true;\n }\n\n isEqual(other: MaybeDocument | null | undefined): boolean {\n return (\n other instanceof UnknownDocument &&\n other.version.isEqual(this.version) &&\n other.key.isEqual(this.key)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): boolean {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === -0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { isNullOrUndefined } from '../util/types';\nimport { Bound, Filter, OrderBy } from './query';\n\n/**\n * A Target represents the WatchTarget representation of a Query, which is used\n * by the LocalStore and the RemoteStore to keep track of and to execute\n * backend queries. While a Query can represent multiple Targets, each Targets\n * maps to a single WatchTarget in RemoteStore and a single TargetData entry\n * in persistence.\n */\nexport class Target {\n private memoizedCanonicalId: string | null = null;\n\n /**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this constructor, because `Query` provides an implicit `orderBy`\n * property.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly orderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {}\n\n canonicalId(): string {\n if (this.memoizedCanonicalId === null) {\n let canonicalId = this.path.canonicalString();\n if (this.collectionGroup !== null) {\n canonicalId += '|cg:' + this.collectionGroup;\n }\n canonicalId += '|f:';\n for (const filter of this.filters) {\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n canonicalId += '|ob:';\n // TODO(dimond): make this collision resistant\n for (const orderBy of this.orderBy) {\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit!;\n }\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n this.memoizedCanonicalId = canonicalId;\n }\n return this.memoizedCanonicalId;\n }\n\n toString(): string {\n let str = this.path.canonicalString();\n if (this.collectionGroup !== null) {\n str += ' collectionGroup=' + this.collectionGroup;\n }\n if (this.filters.length > 0) {\n str += `, filters: [${this.filters.join(', ')}]`;\n }\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n if (this.orderBy.length > 0) {\n str += `, orderBy: [${this.orderBy.join(', ')}]`;\n }\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n return `Target(${str})`;\n }\n\n isEqual(other: Target): boolean {\n if (this.limit !== other.limit) {\n return false;\n }\n\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n\n for (let i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\n return false;\n }\n }\n\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n\n for (let i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].isEqual(other.filters[i])) {\n return false;\n }\n }\n\n if (this.collectionGroup !== other.collectionGroup) {\n return false;\n }\n\n if (!this.path.isEqual(other.path)) {\n return false;\n }\n\n if (\n this.startAt !== null\n ? !this.startAt.isEqual(other.startAt)\n : other.startAt !== null\n ) {\n return false;\n }\n\n return this.endAt !== null\n ? this.endAt.isEqual(other.endAt)\n : other.endAt === null;\n }\n\n isDocumentQuery(): boolean {\n return (\n DocumentKey.isDocumentKey(this.path) &&\n this.collectionGroup === null &&\n this.filters.length === 0\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n ArrayValue,\n DoubleValue,\n FieldValue,\n NullValue,\n RefValue\n} from '../model/field_value';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isNullOrUndefined } from '../util/types';\nimport { Target } from './target';\n\nexport const enum LimitType {\n First = 'F',\n Last = 'L'\n}\n\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n */\nexport class Query {\n static atPath(path: ResourcePath): Query {\n return new Query(path);\n }\n\n private memoizedOrderBy: OrderBy[] | null = null;\n\n // The corresponding `Target` of this `Query` instance.\n private memoizedTarget: Target | null = null;\n\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(\n readonly path: ResourcePath,\n readonly collectionGroup: string | null = null,\n readonly explicitOrderBy: OrderBy[] = [],\n readonly filters: Filter[] = [],\n readonly limit: number | null = null,\n readonly limitType: LimitType = LimitType.First,\n readonly startAt: Bound | null = null,\n readonly endAt: Bound | null = null\n ) {\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n\n get orderBy(): OrderBy[] {\n if (this.memoizedOrderBy === null) {\n const inequalityField = this.getInequalityFilterField();\n const firstOrderByField = this.getFirstOrderByField();\n if (inequalityField !== null && firstOrderByField === null) {\n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n } else {\n this.memoizedOrderBy = [\n new OrderBy(inequalityField),\n KEY_ORDERING_ASC\n ];\n }\n } else {\n assert(\n inequalityField === null ||\n (firstOrderByField !== null &&\n inequalityField.isEqual(firstOrderByField)),\n 'First orderBy should match inequality field.'\n );\n this.memoizedOrderBy = [];\n let foundKeyOrdering = false;\n for (const orderBy of this.explicitOrderBy) {\n this.memoizedOrderBy.push(orderBy);\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n const lastDirection =\n this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir\n : Direction.ASCENDING;\n this.memoizedOrderBy.push(\n lastDirection === Direction.ASCENDING\n ? KEY_ORDERING_ASC\n : KEY_ORDERING_DESC\n );\n }\n }\n }\n return this.memoizedOrderBy;\n }\n\n addFilter(filter: Filter): Query {\n assert(\n this.getInequalityFilterField() == null ||\n !(filter instanceof FieldFilter) ||\n !filter.isInequality() ||\n filter.field.isEqual(this.getInequalityFilterField()!),\n 'Query must only have one inequality field.'\n );\n\n assert(!this.isDocumentQuery(), 'No filtering allowed for document query');\n\n const newFilters = this.filters.concat([filter]);\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n newFilters,\n this.limit,\n this.limitType,\n this.startAt,\n this.endAt\n );\n }\n\n addOrderBy(orderBy: OrderBy): Query {\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy');\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(\n this.path,\n this.collectionGroup,\n newOrderBy,\n this.filters.slice(),\n this.limit,\n this.limitType,\n this.startAt,\n this.endAt\n );\n }\n\n withLimitToFirst(limit: number | null): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n limit,\n LimitType.First,\n this.startAt,\n this.endAt\n );\n }\n\n withLimitToLast(limit: number | null): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n limit,\n LimitType.Last,\n this.startAt,\n this.endAt\n );\n }\n\n withStartAt(bound: Bound): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n this.limit,\n this.limitType,\n bound,\n this.endAt\n );\n }\n\n withEndAt(bound: Bound): Query {\n return new Query(\n this.path,\n this.collectionGroup,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n this.limit,\n this.limitType,\n this.startAt,\n bound\n );\n }\n\n /**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\n asCollectionQueryAtPath(path: ResourcePath): Query {\n return new Query(\n path,\n /*collectionGroup=*/ null,\n this.explicitOrderBy.slice(),\n this.filters.slice(),\n this.limit,\n this.limitType,\n this.startAt,\n this.endAt\n );\n }\n\n /**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\n matchesAllDocuments(): boolean {\n return (\n this.filters.length === 0 &&\n this.limit === null &&\n this.startAt == null &&\n this.endAt == null &&\n (this.explicitOrderBy.length === 0 ||\n (this.explicitOrderBy.length === 1 &&\n this.explicitOrderBy[0].field.isKeyField()))\n );\n }\n\n // TODO(b/29183165): This is used to get a unique string from a query to, for\n // example, use as a dictionary key, but the implementation is subject to\n // collisions. Make it collision-free.\n canonicalId(): string {\n return `${this.toTarget().canonicalId()}|lt:${this.limitType}`;\n }\n\n toString(): string {\n return `Query(target=${this.toTarget().toString()}; limitType=${\n this.limitType\n })`;\n }\n\n isEqual(other: Query): boolean {\n return (\n this.toTarget().isEqual(other.toTarget()) &&\n this.limitType === other.limitType\n );\n }\n\n docComparator(d1: Document, d2: Document): number {\n let comparedOnKeyField = false;\n for (const orderBy of this.orderBy) {\n const comp = orderBy.compare(d1, d2);\n if (comp !== 0) {\n return comp;\n }\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n }\n // Assert that we actually compared by key\n assert(\n comparedOnKeyField,\n \"orderBy used that doesn't compare on key field\"\n );\n return 0;\n }\n\n matches(doc: Document): boolean {\n return (\n this.matchesPathAndCollectionGroup(doc) &&\n this.matchesOrderBy(doc) &&\n this.matchesFilters(doc) &&\n this.matchesBounds(doc)\n );\n }\n\n hasLimitToFirst(): boolean {\n return !isNullOrUndefined(this.limit) && this.limitType === LimitType.First;\n }\n\n hasLimitToLast(): boolean {\n return !isNullOrUndefined(this.limit) && this.limitType === LimitType.Last;\n }\n\n getFirstOrderByField(): FieldPath | null {\n return this.explicitOrderBy.length > 0\n ? this.explicitOrderBy[0].field\n : null;\n }\n\n getInequalityFilterField(): FieldPath | null {\n for (const filter of this.filters) {\n if (filter instanceof FieldFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n return null;\n }\n\n // Checks if any of the provided Operators are included in the query and\n // returns the first one that is, or null if none are.\n findFilterOperator(operators: Operator[]): Operator | null {\n for (const filter of this.filters) {\n if (filter instanceof FieldFilter) {\n if (operators.indexOf(filter.op) >= 0) {\n return filter.op;\n }\n }\n }\n return null;\n }\n\n isDocumentQuery(): boolean {\n return this.toTarget().isDocumentQuery();\n }\n\n isCollectionGroupQuery(): boolean {\n return this.collectionGroup !== null;\n }\n\n /**\n * Converts this `Query` instance to it's corresponding `Target`\n * representation.\n */\n toTarget(): Target {\n if (!this.memoizedTarget) {\n if (this.limitType === LimitType.First) {\n this.memoizedTarget = new Target(\n this.path,\n this.collectionGroup,\n this.orderBy,\n this.filters,\n this.limit,\n this.startAt,\n this.endAt\n );\n } else {\n // Flip the orderBy directions since we want the last results\n const orderBys = [] as OrderBy[];\n for (const orderBy of this.orderBy) {\n const dir =\n orderBy.dir === Direction.DESCENDING\n ? Direction.ASCENDING\n : Direction.DESCENDING;\n orderBys.push(new OrderBy(orderBy.field, dir));\n }\n\n // We need to swap the cursors to match the now-flipped query ordering.\n const startAt = this.endAt\n ? new Bound(this.endAt.position, !this.endAt.before)\n : null;\n const endAt = this.startAt\n ? new Bound(this.startAt.position, !this.startAt.before)\n : null;\n\n // Now return as a LimitType.First query.\n this.memoizedTarget = new Target(\n this.path,\n this.collectionGroup,\n orderBys,\n this.filters,\n this.limit,\n startAt,\n endAt\n );\n }\n }\n return this.memoizedTarget!;\n }\n\n private matchesPathAndCollectionGroup(doc: Document): boolean {\n const docPath = doc.key.path;\n if (this.collectionGroup !== null) {\n // NOTE: this.path is currently always empty since we don't expose Collection\n // Group queries rooted at a document path yet.\n return (\n doc.key.hasCollectionId(this.collectionGroup) &&\n this.path.isPrefixOf(docPath)\n );\n } else if (DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return this.path.isImmediateParentOf(docPath);\n }\n }\n\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */\n private matchesOrderBy(doc: Document): boolean {\n for (const orderBy of this.explicitOrderBy) {\n // order by key always matches\n if (!orderBy.field.isKeyField() && doc.field(orderBy.field) === null) {\n return false;\n }\n }\n return true;\n }\n\n private matchesFilters(doc: Document): boolean {\n for (const filter of this.filters) {\n if (!filter.matches(doc)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Makes sure a document is within the bounds, if provided.\n */\n private matchesBounds(doc: Document): boolean {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n return true;\n }\n\n private assertValidBound(bound: Bound): void {\n assert(\n bound.position.length <= this.orderBy.length,\n 'Bound is longer than orderBy'\n );\n }\n}\n\nexport abstract class Filter {\n abstract matches(doc: Document): boolean;\n abstract canonicalId(): string;\n abstract isEqual(filter: Filter): boolean;\n}\n\nexport class Operator {\n static LESS_THAN = new Operator('<');\n static LESS_THAN_OR_EQUAL = new Operator('<=');\n static EQUAL = new Operator('==');\n static GREATER_THAN = new Operator('>');\n static GREATER_THAN_OR_EQUAL = new Operator('>=');\n static ARRAY_CONTAINS = new Operator('array-contains');\n static IN = new Operator('in');\n static ARRAY_CONTAINS_ANY = new Operator('array-contains-any');\n\n static fromString(op: string): Operator {\n switch (op) {\n case '<':\n return Operator.LESS_THAN;\n case '<=':\n return Operator.LESS_THAN_OR_EQUAL;\n case '==':\n return Operator.EQUAL;\n case '>=':\n return Operator.GREATER_THAN_OR_EQUAL;\n case '>':\n return Operator.GREATER_THAN;\n case 'array-contains':\n return Operator.ARRAY_CONTAINS;\n case 'in':\n return Operator.IN;\n case 'array-contains-any':\n return Operator.ARRAY_CONTAINS_ANY;\n default:\n return fail('Unknown FieldFilter operator: ' + op);\n }\n }\n\n constructor(public name: string) {}\n\n toString(): string {\n return this.name;\n }\n\n isEqual(other: Operator): boolean {\n return this.name === other.name;\n }\n}\n\nexport class FieldFilter extends Filter {\n protected constructor(\n public field: FieldPath,\n public op: Operator,\n public value: FieldValue\n ) {\n super();\n }\n\n /**\n * Creates a filter based on the provided arguments.\n */\n static create(\n field: FieldPath,\n op: Operator,\n value: FieldValue\n ): FieldFilter {\n if (field.isKeyField()) {\n if (op === Operator.IN) {\n assert(\n value instanceof ArrayValue,\n 'Comparing on key with IN, but filter value not an ArrayValue'\n );\n assert(\n value.internalValue.every(elem => {\n return elem instanceof RefValue;\n }),\n 'Comparing on key with IN, but an array value was not a RefValue'\n );\n return new KeyFieldInFilter(field, value);\n } else {\n assert(\n value instanceof RefValue,\n 'Comparing on key, but filter value not a RefValue'\n );\n assert(\n op !== Operator.ARRAY_CONTAINS && op !== Operator.ARRAY_CONTAINS_ANY,\n `'${op.toString()}' queries don't make sense on document keys.`\n );\n return new KeyFieldFilter(field, op, value);\n }\n } else if (value.isEqual(NullValue.INSTANCE)) {\n if (op !== Operator.EQUAL) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. Null supports only equality comparisons.'\n );\n }\n return new FieldFilter(field, op, value);\n } else if (value.isEqual(DoubleValue.NAN)) {\n if (op !== Operator.EQUAL) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. NaN supports only equality comparisons.'\n );\n }\n return new FieldFilter(field, op, value);\n } else if (op === Operator.ARRAY_CONTAINS) {\n return new ArrayContainsFilter(field, value);\n } else if (op === Operator.IN) {\n assert(\n value instanceof ArrayValue,\n 'IN filter has invalid value: ' + value.toString()\n );\n return new InFilter(field, value);\n } else if (op === Operator.ARRAY_CONTAINS_ANY) {\n assert(\n value instanceof ArrayValue,\n 'ARRAY_CONTAINS_ANY filter has invalid value: ' + value.toString()\n );\n return new ArrayContainsAnyFilter(field, value);\n } else {\n return new FieldFilter(field, op, value);\n }\n }\n\n matches(doc: Document): boolean {\n const other = doc.field(this.field);\n\n // Only compare types with matching backend order (such as double and int).\n return (\n other !== null &&\n this.value.typeOrder === other.typeOrder &&\n this.matchesComparison(other.compareTo(this.value))\n );\n }\n\n protected matchesComparison(comparison: number): boolean {\n switch (this.op) {\n case Operator.LESS_THAN:\n return comparison < 0;\n case Operator.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n case Operator.EQUAL:\n return comparison === 0;\n case Operator.GREATER_THAN:\n return comparison > 0;\n case Operator.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n default:\n return fail('Unknown FieldFilter operator: ' + this.op);\n }\n }\n\n isInequality(): boolean {\n return (\n [\n Operator.LESS_THAN,\n Operator.LESS_THAN_OR_EQUAL,\n Operator.GREATER_THAN,\n Operator.GREATER_THAN_OR_EQUAL\n ].indexOf(this.op) >= 0\n );\n }\n\n canonicalId(): string {\n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return (\n this.field.canonicalString() + this.op.toString() + this.value.toString()\n );\n }\n\n isEqual(other: Filter): boolean {\n if (other instanceof FieldFilter) {\n return (\n this.op.isEqual(other.op) &&\n this.field.isEqual(other.field) &&\n this.value.isEqual(other.value)\n );\n } else {\n return false;\n }\n }\n\n toString(): string {\n return `${this.field.canonicalString()} ${this.op} ${this.value.value()}`;\n }\n}\n\n/** Filter that matches on key fields (i.e. '__name__'). */\nexport class KeyFieldFilter extends FieldFilter {\n matches(doc: Document): boolean {\n const refValue = this.value as RefValue;\n const comparison = DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n }\n}\n\n/** Filter that matches on key fields within an array. */\nexport class KeyFieldInFilter extends FieldFilter {\n constructor(field: FieldPath, public value: ArrayValue) {\n super(field, Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n const arrayValue = this.value;\n return arrayValue.internalValue.some(refValue => {\n return doc.key.isEqual((refValue as RefValue).key);\n });\n }\n}\n\n/** A Filter that implements the array-contains operator. */\nexport class ArrayContainsFilter extends FieldFilter {\n constructor(field: FieldPath, value: FieldValue) {\n super(field, Operator.ARRAY_CONTAINS, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.field(this.field);\n return other instanceof ArrayValue && other.contains(this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */\nexport class InFilter extends FieldFilter {\n constructor(field: FieldPath, public value: ArrayValue) {\n super(field, Operator.IN, value);\n }\n\n matches(doc: Document): boolean {\n const arrayValue = this.value;\n const other = doc.field(this.field);\n return other !== null && arrayValue.contains(other);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */\nexport class ArrayContainsAnyFilter extends FieldFilter {\n constructor(field: FieldPath, public value: ArrayValue) {\n super(field, Operator.ARRAY_CONTAINS_ANY, value);\n }\n\n matches(doc: Document): boolean {\n const other = doc.field(this.field);\n return (\n other instanceof ArrayValue &&\n other.internalValue.some(lhsElem => {\n return this.value.contains(lhsElem);\n })\n );\n }\n}\n\n/**\n * The direction of sorting in an order by.\n */\nexport class Direction {\n static ASCENDING = new Direction('asc');\n static DESCENDING = new Direction('desc');\n\n private constructor(public name: string) {}\n\n toString(): string {\n return this.name;\n }\n}\n\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */\nexport class Bound {\n constructor(readonly position: FieldValue[], readonly before: boolean) {}\n\n canonicalId(): string {\n // TODO(b/29183165): Make this collision robust.\n let canonicalId = this.before ? 'b:' : 'a:';\n for (const component of this.position) {\n canonicalId += component.toString();\n }\n return canonicalId;\n }\n\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n sortsBeforeDocument(orderBy: OrderBy[], doc: Document): boolean {\n assert(\n this.position.length <= orderBy.length,\n \"Bound has more components than query's orderBy\"\n );\n let comparison = 0;\n for (let i = 0; i < this.position.length; i++) {\n const orderByComponent = orderBy[i];\n const component = this.position[i];\n if (orderByComponent.field.isKeyField()) {\n assert(\n component instanceof RefValue,\n 'Bound has a non-key value where the key path is being used.'\n );\n comparison = DocumentKey.comparator(component.key, doc.key);\n } else {\n const docValue = doc.field(orderByComponent.field);\n assert(\n docValue !== null,\n 'Field should exist since document matched the orderBy already.'\n );\n comparison = component.compareTo(docValue);\n }\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n if (comparison !== 0) {\n break;\n }\n }\n return this.before ? comparison <= 0 : comparison < 0;\n }\n\n isEqual(other: Bound | null): boolean {\n if (other === null) {\n return false;\n }\n if (\n this.before !== other.before ||\n this.position.length !== other.position.length\n ) {\n return false;\n }\n for (let i = 0; i < this.position.length; i++) {\n const thisPosition = this.position[i];\n const otherPosition = other.position[i];\n if (!thisPosition.isEqual(otherPosition)) {\n return false;\n }\n }\n return true;\n }\n}\n\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */\nexport class OrderBy {\n readonly dir: Direction;\n private readonly isKeyOrderBy: boolean;\n\n constructor(readonly field: FieldPath, dir?: Direction) {\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n\n compare(d1: Document, d2: Document): number {\n const comparison = this.isKeyOrderBy\n ? Document.compareByKey(d1, d2)\n : Document.compareByField(this.field, d1, d2);\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n case Direction.DESCENDING:\n return -1 * comparison;\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n }\n\n canonicalId(): string {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n }\n\n toString(): string {\n return `${this.field.canonicalString()} (${this.dir})`;\n }\n\n isEqual(other: OrderBy): boolean {\n return this.dir === other.dir && this.field.isEqual(other.field);\n }\n}\n\nconst KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\nconst KEY_ORDERING_DESC = new OrderBy(\n FieldPath.keyField(),\n Direction.DESCENDING\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { ByteString } from '../util/byte_string';\n\n/** An enumeration of the different purposes we have for targets. */\nexport const enum TargetPurpose {\n /** A regular, normal query target. */\n Listen,\n\n /**\n * The query target was used to refill a query after an existence filter mismatch.\n */\n ExistenceFilterMismatch,\n\n /** The query target was used to resolve a limbo document. */\n LimboResolution\n}\n\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */\nexport class TargetData {\n constructor(\n /** The target being listened to. */\n readonly target: Target,\n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n readonly targetId: TargetId,\n /** The purpose of the target. */\n readonly purpose: TargetPurpose,\n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n readonly sequenceNumber: ListenSequenceNumber,\n /** The latest snapshot version seen for this target. */\n readonly snapshotVersion: SnapshotVersion = SnapshotVersion.MIN,\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */\n readonly lastLimboFreeSnapshotVersion: SnapshotVersion = SnapshotVersion.MIN,\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n readonly resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING\n ) {}\n\n /** Creates a new target data instance with an updated sequence number. */\n withSequenceNumber(sequenceNumber: number): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n sequenceNumber,\n this.snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n this.resumeToken\n );\n }\n\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */\n withResumeToken(\n resumeToken: ByteString,\n snapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n snapshotVersion,\n this.lastLimboFreeSnapshotVersion,\n resumeToken\n );\n }\n\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */\n withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion: SnapshotVersion\n ): TargetData {\n return new TargetData(\n this.target,\n this.targetId,\n this.purpose,\n this.sequenceNumber,\n this.snapshotVersion,\n lastLimboFreeSnapshotVersion,\n this.resumeToken\n );\n }\n\n isEqual(other: TargetData): boolean {\n return (\n this.targetId === other.targetId &&\n this.purpose === other.purpose &&\n this.sequenceNumber === other.sequenceNumber &&\n this.snapshotVersion.isEqual(other.snapshotVersion) &&\n this.lastLimboFreeSnapshotVersion.isEqual(\n other.lastLimboFreeSnapshotVersion\n ) &&\n this.resumeToken.isEqual(other.resumeToken) &&\n this.target.isEqual(other.target)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 class ExistenceFilter {\n // TODO(b/33078163): just use simplest form of existence filter for now\n constructor(public count: number) {}\n\n isEqual(other: ExistenceFilter): boolean {\n return other && other.count === this.count;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { fail } from '../util/assert';\nimport { Code } from '../util/error';\nimport * as log from '../util/log';\n\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */\nenum RpcCode {\n OK = 0,\n CANCELLED = 1,\n UNKNOWN = 2,\n INVALID_ARGUMENT = 3,\n DEADLINE_EXCEEDED = 4,\n NOT_FOUND = 5,\n ALREADY_EXISTS = 6,\n PERMISSION_DENIED = 7,\n UNAUTHENTICATED = 16,\n RESOURCE_EXHAUSTED = 8,\n FAILED_PRECONDITION = 9,\n ABORTED = 10,\n OUT_OF_RANGE = 11,\n UNIMPLEMENTED = 12,\n INTERNAL = 13,\n UNAVAILABLE = 14,\n DATA_LOSS = 15\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nexport function isPermanentError(code: Code): boolean {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n case Code.CANCELLED:\n case Code.UNKNOWN:\n case Code.DEADLINE_EXCEEDED:\n case Code.RESOURCE_EXHAUSTED:\n case Code.INTERNAL:\n case Code.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case Code.UNAUTHENTICATED:\n return false;\n case Code.INVALID_ARGUMENT:\n case Code.NOT_FOUND:\n case Code.ALREADY_EXISTS:\n case Code.PERMISSION_DENIED:\n case Code.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\nexport function isPermanentWriteError(code: Code): boolean {\n return isPermanentError(code) && code !== Code.ABORTED;\n}\n\n/**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\nexport function mapCodeFromRpcStatus(status: string): Code | undefined {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const code: RpcCode = RpcCode[status as any] as any;\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nexport function mapCodeFromRpcCode(code: number | undefined): Code {\n if (code === undefined) {\n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n log.error('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n case RpcCode.ABORTED:\n return Code.ABORTED;\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Maps an RPC code from a Code. This is the reverse operation from\n * mapCodeFromRpcCode and should really only be used in tests.\n */\nexport function mapRpcCodeFromCode(code: Code | undefined): number {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n case Code.ABORTED:\n return RpcCode.ABORTED;\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n\n/**\n * Converts an HTTP Status Code to the equivalent error code.\n *\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\n * @returns The equivalent Code. Unknown status codes are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpStatus(status: number): Code {\n // The canonical error codes for Google APIs [1] specify mapping onto HTTP\n // status codes but the mapping is not bijective. In each case of ambiguity\n // this function chooses a primary error.\n //\n // [1]\n // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n switch (status) {\n case 200: // OK\n return Code.OK;\n\n case 400: // Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n\n case 401: // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403: // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404: // Not Found\n return Code.NOT_FOUND;\n\n case 409: // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416: // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429: // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499: // Client Closed Request\n return Code.CANCELLED;\n\n case 500: // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501: // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503: // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504: // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) {\n return Code.OK;\n }\n if (status >= 400 && status < 500) {\n return Code.FAILED_PRECONDITION;\n }\n if (status >= 500 && status < 600) {\n return Code.INTERNAL;\n }\n return Code.UNKNOWN;\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */\nexport function mapCodeFromHttpResponseErrorStatus(status: string): Code {\n const serverError = status.toLowerCase().replace('_', '-');\n return Object.values(Code).indexOf(serverError as Code) >= 0\n ? (serverError as Code)\n : Code.UNKNOWN;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SnapshotVersion } from '../core/snapshot_version';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { TargetId } from '../core/types';\nimport { primitiveComparator } from '../util/misc';\nimport { Document, MaybeDocument } from './document';\nimport { DocumentKey } from './document_key';\n\n/** Miscellaneous collection types / constants. */\nexport interface DocumentSizeEntry {\n maybeDocument: MaybeDocument;\n size: number;\n}\n\nexport type MaybeDocumentMap = SortedMap<DocumentKey, MaybeDocument>;\nconst EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap<DocumentKey, MaybeDocument>(\n DocumentKey.comparator\n);\nexport function maybeDocumentMap(): MaybeDocumentMap {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\n\nexport type NullableMaybeDocumentMap = SortedMap<\n DocumentKey,\n MaybeDocument | null\n>;\n\nexport function nullableMaybeDocumentMap(): NullableMaybeDocumentMap {\n return maybeDocumentMap();\n}\n\nexport interface DocumentSizeEntries {\n maybeDocuments: NullableMaybeDocumentMap;\n sizeMap: SortedMap<DocumentKey, number>;\n}\n\nexport type DocumentMap = SortedMap<DocumentKey, Document>;\nconst EMPTY_DOCUMENT_MAP = new SortedMap<DocumentKey, Document>(\n DocumentKey.comparator\n);\nexport function documentMap(): DocumentMap {\n return EMPTY_DOCUMENT_MAP;\n}\n\nexport type DocumentVersionMap = SortedMap<DocumentKey, SnapshotVersion>;\nconst EMPTY_DOCUMENT_VERSION_MAP = new SortedMap<DocumentKey, SnapshotVersion>(\n DocumentKey.comparator\n);\nexport function documentVersionMap(): DocumentVersionMap {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nexport type DocumentKeySet = SortedSet<DocumentKey>;\nconst EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\nexport function documentKeySet(...keys: DocumentKey[]): DocumentKeySet {\n let set = EMPTY_DOCUMENT_KEY_SET;\n for (const key of keys) {\n set = set.add(key);\n }\n return set;\n}\n\nexport type TargetIdSet = SortedSet<TargetId>;\nconst EMPTY_TARGET_ID_SET = new SortedSet<TargetId>(primitiveComparator);\nexport function targetIdSet(): SortedSet<TargetId> {\n return EMPTY_TARGET_ID_SET;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { ChangeType } from '../core/view_snapshot';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n maybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { assert, fail } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { debug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { ExistenceFilter } from './existence_filter';\nimport { RemoteEvent, TargetChange } from './remote_event';\nimport { ByteString } from '../util/byte_string';\n\n/**\n * Internal representation of the watcher API protocol buffers.\n */\nexport type WatchChange =\n | DocumentWatchChange\n | WatchTargetChange\n | ExistenceFilterChange;\n\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */\nexport class DocumentWatchChange {\n constructor(\n /** The new document applies to all of these targets. */\n public updatedTargetIds: TargetId[],\n /** The new document is removed from all of these targets. */\n public removedTargetIds: TargetId[],\n /** The key of the document for this change. */\n public key: DocumentKey,\n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n public newDoc: MaybeDocument | null\n ) {}\n}\n\nexport class ExistenceFilterChange {\n constructor(\n public targetId: TargetId,\n public existenceFilter: ExistenceFilter\n ) {}\n}\n\nexport const enum WatchTargetChangeState {\n NoChange,\n Added,\n Removed,\n Current,\n Reset\n}\n\nexport class WatchTargetChange {\n constructor(\n /** What kind of change occurred to the watch target. */\n public state: WatchTargetChangeState,\n /** The target IDs that were added/removed/set. */\n public targetIds: TargetId[],\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n public resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING,\n /** An RPC error indicating why the watch failed. */\n public cause: FirestoreError | null = null\n ) {}\n}\n\n/** Tracks the internal state of a Watch target. */\nclass TargetState {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n private pendingResponses = 0;\n\n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n private documentChanges: SortedMap<\n DocumentKey,\n ChangeType\n > = snapshotChangesMap();\n\n /** See public getters for explanations of these fields. */\n private _resumeToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n private _current = false;\n\n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n private _hasPendingChanges = true;\n\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */\n get current(): boolean {\n return this._current;\n }\n\n /** The last resume token sent to us for this target. */\n get resumeToken(): ByteString {\n return this._resumeToken;\n }\n\n /** Whether this target has pending target adds or target removes. */\n get isPending(): boolean {\n return this.pendingResponses !== 0;\n }\n\n /** Whether we have modified any state that should trigger a snapshot. */\n get hasPendingChanges(): boolean {\n return this._hasPendingChanges;\n }\n\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */\n updateResumeToken(resumeToken: ByteString): void {\n if (resumeToken.approximateByteSize() > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n }\n\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */\n toTargetChange(): TargetChange {\n let addedDocuments = documentKeySet();\n let modifiedDocuments = documentKeySet();\n let removedDocuments = documentKeySet();\n\n this.documentChanges.forEach((key, changeType) => {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n\n return new TargetChange(\n this._resumeToken,\n this._current,\n addedDocuments,\n modifiedDocuments,\n removedDocuments\n );\n }\n\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */\n clearPendingChanges(): void {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n }\n\n addDocumentChange(key: DocumentKey, changeType: ChangeType): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n }\n\n removeDocumentChange(key: DocumentKey): void {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n }\n\n recordPendingTargetRequest(): void {\n this.pendingResponses += 1;\n }\n\n recordTargetResponse(): void {\n this.pendingResponses -= 1;\n }\n\n markCurrent(): void {\n this._hasPendingChanges = true;\n this._current = true;\n }\n}\n\n/**\n * Interface implemented by RemoteStore to expose target metadata to the\n * WatchChangeAggregator.\n */\nexport interface TargetMetadataProvider {\n /**\n * Returns the set of remote document keys for the given target ID as of the\n * last raised snapshot.\n */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet;\n\n /**\n * Returns the TargetData for an active target ID or 'null' if this target\n * has become inactive\n */\n getTargetDataForTarget(targetId: TargetId): TargetData | null;\n}\n\nconst LOG_TAG = 'WatchChangeAggregator';\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nexport class WatchChangeAggregator {\n constructor(private metadataProvider: TargetMetadataProvider) {}\n\n /** The internal state of all tracked targets. */\n private targetStates: { [targetId: number]: TargetState } = {};\n\n /** Keeps track of the documents to update since the last raised snapshot. */\n private pendingDocumentUpdates = maybeDocumentMap();\n\n /** A mapping of document keys to their set of target IDs. */\n private pendingDocumentTargetMapping = documentTargetMap();\n\n /**\n * A list of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n private pendingTargetResets = new SortedSet<TargetId>(primitiveComparator);\n\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */\n handleDocumentChange(docChange: DocumentWatchChange): void {\n for (const targetId of docChange.updatedTargetIds) {\n if (docChange.newDoc instanceof Document) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else if (docChange.newDoc instanceof NoDocument) {\n this.removeDocumentFromTarget(\n targetId,\n docChange.key,\n docChange.newDoc\n );\n }\n }\n\n for (const targetId of docChange.removedTargetIds) {\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n }\n\n /** Processes and adds the WatchTargetChange to the current set of changes. */\n handleTargetChange(targetChange: WatchTargetChange): void {\n this.forEachTarget(targetChange, targetId => {\n const targetState = this.ensureTargetState(targetId);\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (this.isActiveTarget(targetId)) {\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Added:\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n targetState.clearPendingChanges();\n }\n targetState.updateResumeToken(targetChange.resumeToken);\n break;\n case WatchTargetChangeState.Removed:\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n targetState.recordTargetResponse();\n if (!targetState.isPending) {\n this.removeTarget(targetId);\n }\n assert(\n !targetChange.cause,\n 'WatchChangeAggregator does not handle errored targets'\n );\n break;\n case WatchTargetChangeState.Current:\n if (this.isActiveTarget(targetId)) {\n targetState.markCurrent();\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n case WatchTargetChangeState.Reset:\n if (this.isActiveTarget(targetId)) {\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.resetTarget(targetId);\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n break;\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n }\n\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */\n forEachTarget(\n targetChange: WatchTargetChange,\n fn: (targetId: TargetId) => void\n ): void {\n if (targetChange.targetIds.length > 0) {\n targetChange.targetIds.forEach(fn);\n } else {\n objUtils.forEachNumber(this.targetStates, fn);\n }\n }\n\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */\n handleExistenceFilter(watchChange: ExistenceFilterChange): void {\n const targetId = watchChange.targetId;\n const expectedCount = watchChange.existenceFilter.count;\n\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n const target = targetData.target;\n if (target.isDocumentQuery()) {\n if (expectedCount === 0) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const key = new DocumentKey(target.path);\n this.removeDocumentFromTarget(\n targetId,\n key,\n new NoDocument(key, SnapshotVersion.forDeletedDoc())\n );\n } else {\n assert(\n expectedCount === 1,\n 'Single document existence filter with count: ' + expectedCount\n );\n }\n } else {\n const currentSize = this.getCurrentDocumentCountForTarget(targetId);\n if (currentSize !== expectedCount) {\n // Existence filter mismatch: We reset the mapping and raise a new\n // snapshot with `isFromCache:true`.\n this.resetTarget(targetId);\n this.pendingTargetResets = this.pendingTargetResets.add(targetId);\n }\n }\n }\n }\n\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */\n createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent {\n const targetChanges: { [targetId: number]: TargetChange } = {};\n\n objUtils.forEachNumber(this.targetStates, (targetId, targetState) => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (targetData) {\n if (targetState.current && targetData.target.isDocumentQuery()) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n //\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const key = new DocumentKey(targetData.target.path);\n if (\n this.pendingDocumentUpdates.get(key) === null &&\n !this.targetContainsDocument(targetId, key)\n ) {\n this.removeDocumentFromTarget(\n targetId,\n key,\n new NoDocument(key, snapshotVersion)\n );\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges[targetId] = targetState.toTargetChange();\n targetState.clearPendingChanges();\n }\n }\n });\n\n let resolvedLimboDocuments = documentKeySet();\n\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n //\n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.pendingDocumentTargetMapping.forEach((key, targets) => {\n let isOnlyLimboTarget = true;\n\n targets.forEachWhile(targetId => {\n const targetData = this.targetDataForActiveTarget(targetId);\n if (\n targetData &&\n targetData.purpose !== TargetPurpose.LimboResolution\n ) {\n isOnlyLimboTarget = false;\n return false;\n }\n\n return true;\n });\n\n if (isOnlyLimboTarget) {\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\n }\n });\n\n const remoteEvent = new RemoteEvent(\n snapshotVersion,\n targetChanges,\n this.pendingTargetResets,\n this.pendingDocumentUpdates,\n resolvedLimboDocuments\n );\n\n this.pendingDocumentUpdates = maybeDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedSet<TargetId>(primitiveComparator);\n\n return remoteEvent;\n }\n\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n addDocumentToTarget(targetId: TargetId, document: MaybeDocument): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const changeType = this.targetContainsDocument(targetId, document.key)\n ? ChangeType.Modified\n : ChangeType.Added;\n\n const targetState = this.ensureTargetState(targetId);\n targetState.addDocumentChange(document.key, changeType);\n\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n document.key,\n document\n );\n\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(\n document.key,\n this.ensureDocumentTargetMapping(document.key).add(targetId)\n );\n }\n\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n removeDocumentFromTarget(\n targetId: TargetId,\n key: DocumentKey,\n updatedDocument: MaybeDocument | null\n ): void {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n const targetState = this.ensureTargetState(targetId);\n if (this.targetContainsDocument(targetId, key)) {\n targetState.addDocumentChange(key, ChangeType.Removed);\n } else {\n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n targetState.removeDocumentChange(key);\n }\n\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).delete(targetId)\n );\n\n if (updatedDocument) {\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(\n key,\n updatedDocument\n );\n }\n }\n\n removeTarget(targetId: TargetId): void {\n delete this.targetStates[targetId];\n }\n\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */\n private getCurrentDocumentCountForTarget(targetId: TargetId): number {\n const targetState = this.ensureTargetState(targetId);\n const targetChange = targetState.toTargetChange();\n return (\n this.metadataProvider.getRemoteKeysForTarget(targetId).size +\n targetChange.addedDocuments.size -\n targetChange.removedDocuments.size\n );\n }\n\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */\n recordPendingTargetRequest(targetId: TargetId): void {\n // For each request we get we need to record we need a response for it.\n const targetState = this.ensureTargetState(targetId);\n targetState.recordPendingTargetRequest();\n }\n\n private ensureTargetState(targetId: TargetId): TargetState {\n if (!this.targetStates[targetId]) {\n this.targetStates[targetId] = new TargetState();\n }\n\n return this.targetStates[targetId];\n }\n\n private ensureDocumentTargetMapping(key: DocumentKey): SortedSet<TargetId> {\n let targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet<TargetId>(primitiveComparator);\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(\n key,\n targetMapping\n );\n }\n\n return targetMapping;\n }\n\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */\n protected isActiveTarget(targetId: TargetId): boolean {\n const targetActive = this.targetDataForActiveTarget(targetId) !== null;\n if (!targetActive) {\n debug(LOG_TAG, 'Detected inactive target', targetId);\n }\n return targetActive;\n }\n\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */\n protected targetDataForActiveTarget(targetId: TargetId): TargetData | null {\n const targetState = this.targetStates[targetId];\n return targetState && targetState.isPending\n ? null\n : this.metadataProvider.getTargetDataForTarget(targetId);\n }\n\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */\n private resetTarget(targetId: TargetId): void {\n assert(\n !this.targetStates[targetId].isPending,\n 'Should only reset active targets'\n );\n this.targetStates[targetId] = new TargetState();\n\n // Trigger removal for any documents currently mapped to this target.\n // These removals will be part of the initial snapshot if Watch does not\n // resend these documents.\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n existingKeys.forEach(key => {\n this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null);\n });\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */\n private targetContainsDocument(\n targetId: TargetId,\n key: DocumentKey\n ): boolean {\n const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n return existingKeys.has(key);\n }\n}\n\nfunction documentTargetMap(): SortedMap<DocumentKey, SortedSet<TargetId>> {\n return new SortedMap<DocumentKey, SortedSet<TargetId>>(\n DocumentKey.comparator\n );\n}\n\nfunction snapshotChangesMap(): SortedMap<DocumentKey, ChangeType> {\n return new SortedMap<DocumentKey, ChangeType>(DocumentKey.comparator);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../util/sorted_map';\n\nimport { documentMap } from './collections';\nimport { Document } from './document';\nimport { DocumentComparator } from './document_comparator';\nimport { DocumentKey } from './document_key';\n\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */\n\nexport class DocumentSet {\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */\n static emptySet(oldSet: DocumentSet): DocumentSet {\n return new DocumentSet(oldSet.comparator);\n }\n\n private comparator: DocumentComparator;\n private keyedMap: SortedMap<DocumentKey, Document>;\n private sortedSet: SortedMap<Document, null>;\n\n /** The default ordering is by key if the comparator is omitted */\n constructor(comp?: DocumentComparator) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n if (comp) {\n this.comparator = (d1: Document, d2: Document) =>\n comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n } else {\n this.comparator = (d1: Document, d2: Document) =>\n DocumentKey.comparator(d1.key, d2.key);\n }\n\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap<Document, null>(this.comparator);\n }\n\n has(key: DocumentKey): boolean {\n return this.keyedMap.get(key) != null;\n }\n\n get(key: DocumentKey): Document | null {\n return this.keyedMap.get(key);\n }\n\n first(): Document | null {\n return this.sortedSet.minKey();\n }\n\n last(): Document | null {\n return this.sortedSet.maxKey();\n }\n\n isEmpty(): boolean {\n return this.sortedSet.isEmpty();\n }\n\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */\n indexOf(key: DocumentKey): number {\n const doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n }\n\n get size(): number {\n return this.sortedSet.size;\n }\n\n /** Iterates documents in order defined by \"comparator\" */\n forEach(cb: (doc: Document) => void): void {\n this.sortedSet.inorderTraversal((k, v) => {\n cb(k);\n return false;\n });\n }\n\n /** Inserts or updates a document with the same key */\n add(doc: Document): DocumentSet {\n // First remove the element if we have it.\n const set = this.delete(doc.key);\n return set.copy(\n set.keyedMap.insert(doc.key, doc),\n set.sortedSet.insert(doc, null)\n );\n }\n\n /** Deletes a document with a given key */\n delete(key: DocumentKey): DocumentSet {\n const doc = this.get(key);\n if (!doc) {\n return this;\n }\n\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n }\n\n isEqual(other: DocumentSet | null | undefined): boolean {\n if (!(other instanceof DocumentSet)) {\n return false;\n }\n if (this.size !== other.size) {\n return false;\n }\n\n const thisIt = this.sortedSet.getIterator();\n const otherIt = other.sortedSet.getIterator();\n while (thisIt.hasNext()) {\n const thisDoc = thisIt.getNext().key;\n const otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc)) {\n return false;\n }\n }\n return true;\n }\n\n toString(): string {\n const docStrings: string[] = [];\n this.forEach(doc => {\n docStrings.push(doc.toString());\n });\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n } else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n }\n\n private copy(\n keyedMap: SortedMap<DocumentKey, Document>,\n sortedSet: SortedMap<Document, null>\n ): DocumentSet {\n const newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { fail } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentKeySet } from '../model/collections';\nimport { Query } from './query';\n\nexport const enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport const enum SyncState {\n Local,\n Synced\n}\n\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */\nexport class DocumentChangeSet {\n private changeMap = new SortedMap<DocumentKey, DocumentViewChange>(\n DocumentKey.comparator\n );\n\n track(change: DocumentViewChange): void {\n const key = change.doc.key;\n const oldChange = this.changeMap.get(key);\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n }\n\n // Merge the new change with the existing change.\n if (\n change.type !== ChangeType.Added &&\n oldChange.type === ChangeType.Metadata\n ) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (\n change.type === ChangeType.Metadata &&\n oldChange.type !== ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Modified &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Added\n ) {\n this.changeMap = this.changeMap.remove(key);\n } else if (\n change.type === ChangeType.Removed &&\n oldChange.type === ChangeType.Modified\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (\n change.type === ChangeType.Added &&\n oldChange.type === ChangeType.Removed\n ) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else {\n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n fail(\n 'unsupported combination of changes: ' +\n JSON.stringify(change) +\n ' after ' +\n JSON.stringify(oldChange)\n );\n }\n }\n\n getChanges(): DocumentViewChange[] {\n const changes: DocumentViewChange[] = [];\n this.changeMap.inorderTraversal(\n (key: DocumentKey, change: DocumentViewChange) => {\n changes.push(change);\n }\n );\n return changes;\n }\n}\n\nexport class ViewSnapshot {\n constructor(\n readonly query: Query,\n readonly docs: DocumentSet,\n readonly oldDocs: DocumentSet,\n readonly docChanges: DocumentViewChange[],\n readonly mutatedKeys: DocumentKeySet,\n readonly fromCache: boolean,\n readonly syncStateChanged: boolean,\n readonly excludesMetadataChanges: boolean\n ) {}\n\n /** Returns a view snapshot as if all documents in the snapshot were added. */\n static fromInitialDocuments(\n query: Query,\n documents: DocumentSet,\n mutatedKeys: DocumentKeySet,\n fromCache: boolean\n ): ViewSnapshot {\n const changes: DocumentViewChange[] = [];\n documents.forEach(doc => {\n changes.push({ type: ChangeType.Added, doc });\n });\n\n return new ViewSnapshot(\n query,\n documents,\n DocumentSet.emptySet(documents),\n changes,\n mutatedKeys,\n fromCache,\n /* syncStateChanged= */ true,\n /* excludesMetadataChanges= */ false\n );\n }\n\n get hasPendingWrites(): boolean {\n return !this.mutatedKeys.isEmpty();\n }\n\n isEqual(other: ViewSnapshot): boolean {\n if (\n this.fromCache !== other.fromCache ||\n this.syncStateChanged !== other.syncStateChanged ||\n !this.mutatedKeys.isEqual(other.mutatedKeys) ||\n !this.query.isEqual(other.query) ||\n !this.docs.isEqual(other.docs) ||\n !this.oldDocs.isEqual(other.oldDocs)\n ) {\n return false;\n }\n const changes: DocumentViewChange[] = this.docChanges;\n const otherChanges: DocumentViewChange[] = other.docChanges;\n if (changes.length !== otherChanges.length) {\n return false;\n }\n for (let i = 0; i < changes.length; i++) {\n if (\n changes[i].type !== otherChanges[i].type ||\n !changes[i].doc.isEqual(otherChanges[i].doc)\n ) {\n return false;\n }\n }\n return true;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport {\n documentKeySet,\n DocumentKeySet,\n maybeDocumentMap,\n MaybeDocumentMap,\n targetIdSet\n} from '../model/collections';\nimport { SortedSet } from '../util/sorted_set';\nimport { ByteString } from '../util/byte_string';\n\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */\nexport class RemoteEvent {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n readonly snapshotVersion: SnapshotVersion,\n /**\n * A map from target to changes to the target. See TargetChange.\n */\n readonly targetChanges: { [targetId: number]: TargetChange },\n /**\n * A set of targets that is known to be inconsistent. Listens for these\n * targets should be re-established without resume tokens.\n */\n readonly targetMismatches: SortedSet<TargetId>,\n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n readonly documentUpdates: MaybeDocumentMap,\n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n readonly resolvedLimboDocuments: DocumentKeySet\n ) {}\n\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(\n targetId: TargetId,\n current: boolean\n ): RemoteEvent {\n const targetChanges = {\n [targetId]: TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current\n )\n };\n return new RemoteEvent(\n SnapshotVersion.MIN,\n targetChanges,\n targetIdSet(),\n maybeDocumentMap(),\n documentKeySet()\n );\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */\nexport class TargetChange {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n readonly resumeToken: ByteString,\n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n readonly current: boolean,\n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n readonly addedDocuments: DocumentKeySet,\n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n readonly modifiedDocuments: DocumentKeySet,\n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n readonly removedDocuments: DocumentKeySet\n ) {}\n\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */\n static createSynthesizedTargetChangeForCurrentChange(\n targetId: TargetId,\n current: boolean\n ): TargetChange {\n return new TargetChange(\n ByteString.EMPTY_BYTE_STRING,\n current,\n documentKeySet(),\n documentKeySet(),\n documentKeySet()\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Blob } from '../api/blob';\nimport { GeoPoint } from '../api/geo_point';\nimport { Timestamp } from '../api/timestamp';\nimport { DatabaseId } from '../core/database_info';\nimport {\n Bound,\n Direction,\n FieldFilter,\n Filter,\n LimitType,\n Operator,\n OrderBy,\n Query\n} from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { TargetId } from '../core/types';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport * as fieldValue from '../model/field_value';\nimport {\n DeleteMutation,\n FieldMask,\n FieldTransform,\n Mutation,\n MutationResult,\n PatchMutation,\n Precondition,\n SetMutation,\n TransformMutation,\n VerifyMutation\n} from '../model/mutation';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as obj from '../util/obj';\nimport { ByteString } from '../util/byte_string';\nimport * as typeUtils from '../util/types';\n\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform,\n TransformOperation\n} from '../model/transform_operation';\nimport { ExistenceFilter } from './existence_filter';\nimport { mapCodeFromRpcCode, mapRpcCodeFromCode } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n WatchChange,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\n\nconst DIRECTIONS = (() => {\n const dirs: { [dir: string]: api.OrderDirection } = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n})();\n\nconst OPERATORS = (() => {\n const ops: { [op: string]: api.FieldFilterOp } = {};\n ops[Operator.LESS_THAN.name] = 'LESS_THAN';\n ops[Operator.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[Operator.GREATER_THAN.name] = 'GREATER_THAN';\n ops[Operator.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[Operator.EQUAL.name] = 'EQUAL';\n ops[Operator.ARRAY_CONTAINS.name] = 'ARRAY_CONTAINS';\n ops[Operator.IN.name] = 'IN';\n ops[Operator.ARRAY_CONTAINS_ANY.name] = 'ARRAY_CONTAINS_ANY';\n return ops;\n})();\n\n// A RegExp matching ISO 8601 UTC timestamps with optional fraction.\nconst ISO_REG_EXP = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\nfunction assertPresent(value: unknown, description: string): asserts value {\n assert(!typeUtils.isNullOrUndefined(value), description + ' is missing');\n}\n\nfunction parseInt64(value: number | string): number {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n if (typeof value === 'number') {\n return value;\n } else if (typeof value === 'string') {\n return Number(value);\n } else {\n return fail(\"can't parse \" + value);\n }\n}\n\n// This is a supplement to the generated proto interfaces, which fail to account\n// for the fact that a timestamp may be encoded as either a string OR this.\ninterface TimestampProto {\n seconds?: string;\n nanos?: number;\n}\n\nexport interface SerializerOptions {\n /**\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting this flag to true, the serializer will use the Proto3 JSON format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n */\n useProto3Json: boolean;\n}\n\n/**\n * Generates JsonObject values for the Datastore API suitable for sending to\n * either GRPC stub methods or via the JSON/HTTP REST API.\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nexport class JsonProtoSerializer {\n constructor(\n private databaseId: DatabaseId,\n private options: SerializerOptions\n ) {}\n\n fromRpcStatus(status: api.Status): FirestoreError {\n const code =\n status.code === undefined\n ? Code.UNKNOWN\n : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n }\n\n /**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */\n private toInt32Value(val: number | null): number | null {\n if (this.options.useProto3Json || typeUtils.isNullOrUndefined(val)) {\n return val;\n } else {\n // ProtobufJS requires that we wrap Int32Values.\n // Use any because we need to match generated Proto types.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return { value: val } as any;\n }\n }\n\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as accepting \"number\" because that's what\n * our generated proto interfaces say Int32Value must be, but it actually\n * accepts { value: number } to match our serialization in toInt32Value().\n */\n private fromInt32Value(val: number | undefined): number | null {\n let result;\n if (typeof val === 'object') {\n // Use any because we need to match generated Proto types.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n result = (val as any).value;\n } else {\n // We accept raw numbers (without the {value: ... } wrapper) for\n // compatibility with legacy persisted data.\n result = val;\n }\n return typeUtils.isNullOrUndefined(result) ? null : result;\n }\n\n /**\n * Returns a value for a Date that's appropriate to put into a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say dates must be. But it's easier and safer\n * to actually return a Timestamp proto.\n */\n private toTimestamp(timestamp: Timestamp): string {\n if (this.options.useProto3Json) {\n // Serialize to ISO-8601 date format, but with full nano resolution.\n // Since JS Date has only millis, let's only use it for the seconds and\n // then manually add the fractions to the end.\n const jsDateStr = new Date(timestamp.seconds * 1000).toISOString();\n // Remove .xxx frac part and Z in the end.\n const strUntilSeconds = jsDateStr.replace(/\\.\\d*/, '').replace('Z', '');\n // Pad the fraction out to 9 digits (nanos).\n const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9);\n\n return `${strUntilSeconds}.${nanoStr}Z`;\n } else {\n return {\n seconds: '' + timestamp.seconds,\n nanos: timestamp.nanoseconds\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n }\n }\n\n private fromTimestamp(date: string | TimestampProto): Timestamp {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (typeof date === 'string') {\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return this.fromIso8601String(date);\n } else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.');\n // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n const seconds = parseInt64(date.seconds || '0');\n const nanos = date.nanos || 0;\n return new Timestamp(seconds, nanos);\n }\n }\n\n private fromIso8601String(utc: string): Timestamp {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n\n // Parse the nanos right out of the string.\n let nanos = 0;\n const fraction = ISO_REG_EXP.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n }\n\n // Parse the date to get the seconds.\n const date = new Date(utc);\n const seconds = Math.floor(date.getTime() / 1000);\n\n return new Timestamp(seconds, nanos);\n }\n\n /**\n * Returns a value for bytes that's appropriate to put in a proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"string\" because that's what\n * our generated proto interfaces say bytes must be. But it should return\n * an Uint8Array in Node.\n *\n * Visible for testing.\n */\n toBytes(bytes: Blob | ByteString): string {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n } else {\n return (bytes.toUint8Array() as unknown) as string;\n }\n }\n\n /**\n * Returns a ByteString based on the proto string value.\n */\n fromBytes(value: string | Uint8Array | undefined): ByteString {\n if (this.options.useProto3Json) {\n assert(\n value === undefined || typeof value === 'string',\n 'value must be undefined or a string when using proto3 Json'\n );\n return ByteString.fromBase64String(value ? value : '');\n } else {\n assert(\n value === undefined || value instanceof Uint8Array,\n 'value must be undefined or Uint8Array'\n );\n return ByteString.fromUint8Array(value ? value : new Uint8Array());\n }\n }\n\n /**\n * Parse the blob from the protos into the internal Blob class. Note that the\n * typings assume all blobs are strings, but they are actually Uint8Arrays\n * on Node.\n */\n private fromBlob(blob: string | Uint8Array): Blob {\n if (typeof blob === 'string') {\n assert(\n this.options.useProto3Json,\n 'Expected bytes to be passed in as Uint8Array, but got a string instead.'\n );\n return Blob.fromBase64String(blob);\n } else {\n assert(\n !this.options.useProto3Json,\n 'Expected bytes to be passed in as Uint8Array, but got a string instead.'\n );\n return Blob.fromUint8Array(blob);\n }\n }\n\n toVersion(version: SnapshotVersion): string {\n return this.toTimestamp(version.toTimestamp());\n }\n\n fromVersion(version: string): SnapshotVersion {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n }\n\n toResourceName(databaseId: DatabaseId, path: ResourcePath): string {\n return this.fullyQualifiedPrefixPath(databaseId)\n .child('documents')\n .child(path)\n .canonicalString();\n }\n\n fromResourceName(name: string): ResourcePath {\n const resource = ResourcePath.fromString(name);\n assert(\n this.isValidResourceName(resource),\n 'Tried to deserialize invalid key ' + resource.toString()\n );\n return resource;\n }\n\n toName(key: DocumentKey): string {\n return this.toResourceName(this.databaseId, key.path);\n }\n\n fromName(name: string): DocumentKey {\n const resource = this.fromResourceName(name);\n assert(\n resource.get(1) === this.databaseId.projectId,\n 'Tried to deserialize key from different project: ' +\n resource.get(1) +\n ' vs ' +\n this.databaseId.projectId\n );\n assert(\n (!resource.get(3) && !this.databaseId.database) ||\n resource.get(3) === this.databaseId.database,\n 'Tried to deserialize key from different database: ' +\n resource.get(3) +\n ' vs ' +\n this.databaseId.database\n );\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\n }\n\n toQueryPath(path: ResourcePath): string {\n return this.toResourceName(this.databaseId, path);\n }\n\n fromQueryPath(name: string): ResourcePath {\n const resourceName = this.fromResourceName(name);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n if (resourceName.length === 4) {\n return ResourcePath.EMPTY_PATH;\n }\n return this.extractLocalPathFromResourceName(resourceName);\n }\n\n get encodedDatabaseId(): string {\n const path = new ResourcePath([\n 'projects',\n this.databaseId.projectId,\n 'databases',\n this.databaseId.database\n ]);\n return path.canonicalString();\n }\n\n private fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {\n return new ResourcePath([\n 'projects',\n databaseId.projectId,\n 'databases',\n databaseId.database\n ]);\n }\n\n private extractLocalPathFromResourceName(\n resourceName: ResourcePath\n ): ResourcePath {\n assert(\n resourceName.length > 4 && resourceName.get(4) === 'documents',\n 'tried to deserialize invalid key ' + resourceName.toString()\n );\n return resourceName.popFirst(5);\n }\n\n private isValidResourceName(path: ResourcePath): boolean {\n // Resource names have at least 4 components (project ID, database ID)\n return (\n path.length >= 4 &&\n path.get(0) === 'projects' &&\n path.get(2) === 'databases'\n );\n }\n\n toValue(val: fieldValue.FieldValue): api.Value {\n if (val instanceof fieldValue.NullValue) {\n return { nullValue: 'NULL_VALUE' };\n } else if (val instanceof fieldValue.BooleanValue) {\n return { booleanValue: val.value() };\n } else if (val instanceof fieldValue.IntegerValue) {\n return { integerValue: '' + val.value() };\n } else if (val instanceof fieldValue.DoubleValue) {\n const doubleValue = val.value();\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return { doubleValue: 'NaN' } as {};\n } else if (doubleValue === Infinity) {\n return { doubleValue: 'Infinity' } as {};\n } else if (doubleValue === -Infinity) {\n return { doubleValue: '-Infinity' } as {};\n } else if (typeUtils.isNegativeZero(doubleValue)) {\n return { doubleValue: '-0' } as {};\n }\n }\n return { doubleValue: val.value() };\n } else if (val instanceof fieldValue.StringValue) {\n return { stringValue: val.value() };\n } else if (val instanceof fieldValue.ObjectValue) {\n return { mapValue: this.toMapValue(val) };\n } else if (val instanceof fieldValue.ArrayValue) {\n return { arrayValue: this.toArrayValue(val) };\n } else if (val instanceof fieldValue.TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n } else if (val instanceof fieldValue.GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n } else if (val instanceof fieldValue.BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n } else if (val instanceof fieldValue.RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n } else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n }\n\n fromValue(obj: api.Value): fieldValue.FieldValue {\n if ('nullValue' in obj) {\n return fieldValue.NullValue.INSTANCE;\n } else if ('booleanValue' in obj) {\n return fieldValue.BooleanValue.of(obj.booleanValue!);\n } else if ('integerValue' in obj) {\n return new fieldValue.IntegerValue(parseInt64(obj.integerValue!));\n } else if ('doubleValue' in obj) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if ((obj.doubleValue as {}) === 'NaN') {\n return fieldValue.DoubleValue.NAN;\n } else if ((obj.doubleValue as {}) === 'Infinity') {\n return fieldValue.DoubleValue.POSITIVE_INFINITY;\n } else if ((obj.doubleValue as {}) === '-Infinity') {\n return fieldValue.DoubleValue.NEGATIVE_INFINITY;\n } else if ((obj.doubleValue as {}) === '-0') {\n return new fieldValue.DoubleValue(-0);\n }\n }\n\n return new fieldValue.DoubleValue(obj.doubleValue!);\n } else if ('stringValue' in obj) {\n return new fieldValue.StringValue(obj.stringValue!);\n } else if ('mapValue' in obj) {\n return this.fromFields(obj.mapValue!.fields || {});\n } else if ('arrayValue' in obj) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n const values = obj.arrayValue.values || [];\n return new fieldValue.ArrayValue(values.map(v => this.fromValue(v)));\n } else if ('timestampValue' in obj) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new fieldValue.TimestampValue(\n this.fromTimestamp(obj.timestampValue!)\n );\n } else if ('geoPointValue' in obj) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n const latitude = obj.geoPointValue.latitude || 0;\n const longitude = obj.geoPointValue.longitude || 0;\n return new fieldValue.GeoPointValue(new GeoPoint(latitude, longitude));\n } else if ('bytesValue' in obj) {\n assertPresent(obj.bytesValue, 'bytesValue');\n const blob = this.fromBlob(obj.bytesValue);\n return new fieldValue.BlobValue(blob);\n } else if ('referenceValue' in obj) {\n assertPresent(obj.referenceValue, 'referenceValue');\n const resourceName = this.fromResourceName(obj.referenceValue);\n const dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\n const key = new DocumentKey(\n this.extractLocalPathFromResourceName(resourceName)\n );\n return new fieldValue.RefValue(dbId, key);\n } else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n }\n\n /** Creates an api.Document from key and fields (but no create/update time) */\n toMutationDocument(\n key: DocumentKey,\n fields: fieldValue.ObjectValue\n ): api.Document {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n }\n\n toDocument(document: Document): api.Document {\n assert(\n !document.hasLocalMutations,\n \"Can't serialize documents with mutations.\"\n );\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data()),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n }\n\n fromDocument(\n document: api.Document,\n hasCommittedMutations?: boolean\n ): Document {\n const key = this.fromName(document.name!);\n const version = this.fromVersion(document.updateTime!);\n return new Document(\n key,\n version,\n { hasCommittedMutations: !!hasCommittedMutations },\n undefined,\n document,\n v => this.fromValue(v)\n );\n }\n\n toFields(fields: fieldValue.ObjectValue): { [key: string]: api.Value } {\n const result: { [key: string]: api.Value } = {};\n fields.forEach((key, value) => {\n result[key] = this.toValue(value);\n });\n return result;\n }\n\n fromFields(object: {}): fieldValue.ObjectValue {\n // Proto map<string, Value> gets mapped to Object, so cast it.\n const map = object as { [key: string]: api.Value };\n const result = fieldValue.ObjectValue.newBuilder();\n obj.forEach(map, (key, value) => {\n result.set(new FieldPath([key]), this.fromValue(value));\n });\n return result.build();\n }\n\n toMapValue(map: fieldValue.ObjectValue): api.MapValue {\n return {\n fields: this.toFields(map)\n };\n }\n\n toArrayValue(array: fieldValue.ArrayValue): api.ArrayValue {\n const result: api.Value[] = [];\n array.forEach(value => {\n result.push(this.toValue(value));\n });\n return { values: result };\n }\n\n private fromFound(doc: api.BatchGetDocumentsResponse): Document {\n assert(\n !!doc.found,\n 'Tried to deserialize a found document from a missing document.'\n );\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n const key = this.fromName(doc.found.name);\n const version = this.fromVersion(doc.found.updateTime);\n return new Document(key, version, {}, undefined, doc.found, v =>\n this.fromValue(v)\n );\n }\n\n private fromMissing(result: api.BatchGetDocumentsResponse): NoDocument {\n assert(\n !!result.missing,\n 'Tried to deserialize a missing document from a found document.'\n );\n assert(\n !!result.readTime,\n 'Tried to deserialize a missing document without a read time.'\n );\n const key = this.fromName(result.missing);\n const version = this.fromVersion(result.readTime);\n return new NoDocument(key, version);\n }\n\n fromMaybeDocument(result: api.BatchGetDocumentsResponse): MaybeDocument {\n if ('found' in result) {\n return this.fromFound(result);\n } else if ('missing' in result) {\n return this.fromMissing(result);\n }\n return fail('invalid batch get response: ' + JSON.stringify(result));\n }\n\n private toWatchTargetChangeState(\n state: WatchTargetChangeState\n ): api.TargetChangeTargetChangeType {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n case WatchTargetChangeState.Reset:\n return 'RESET';\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n }\n\n toTestWatchChange(watchChange: WatchChange): api.ListenResponse {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof Document) {\n const doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data()),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n } else if (watchChange.newDoc instanceof NoDocument) {\n const doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n } else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n if (watchChange instanceof WatchTargetChange) {\n let cause: api.Status | undefined = undefined;\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.toBytes(watchChange.resumeToken),\n cause\n }\n };\n }\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n }\n\n fromWatchChange(change: api.ListenResponse): WatchChange {\n let watchChange: WatchChange;\n if ('targetChange' in change) {\n assertPresent(change.targetChange, 'targetChange');\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const state = this.fromWatchTargetChangeState(\n change.targetChange.targetChangeType || 'NO_CHANGE'\n );\n const targetIds: TargetId[] = change.targetChange.targetIds || [];\n\n const resumeToken = this.fromBytes(change.targetChange.resumeToken);\n const causeProto = change.targetChange!.cause;\n const cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(\n state,\n targetIds,\n resumeToken,\n cause || null\n );\n } else if ('documentChange' in change) {\n assertPresent(change.documentChange, 'documentChange');\n const entityChange = change.documentChange;\n assertPresent(entityChange.document, 'documentChange.name');\n assertPresent(entityChange.document.name, 'documentChange.document.name');\n assertPresent(\n entityChange.document.updateTime,\n 'documentChange.document.updateTime'\n );\n const key = this.fromName(entityChange.document.name);\n const version = this.fromVersion(entityChange.document.updateTime);\n const doc = new Document(\n key,\n version,\n {},\n undefined,\n entityChange.document!,\n v => this.fromValue(v)\n );\n const updatedTargetIds = entityChange.targetIds || [];\n const removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(\n updatedTargetIds,\n removedTargetIds,\n doc.key,\n doc\n );\n } else if ('documentDelete' in change) {\n assertPresent(change.documentDelete, 'documentDelete');\n const docDelete = change.documentDelete;\n assertPresent(docDelete.document, 'documentDelete.document');\n const key = this.fromName(docDelete.document);\n const version = docDelete.readTime\n ? this.fromVersion(docDelete.readTime)\n : SnapshotVersion.forDeletedDoc();\n const doc = new NoDocument(key, version);\n const removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if ('documentRemove' in change) {\n assertPresent(change.documentRemove, 'documentRemove');\n const docRemove = change.documentRemove;\n assertPresent(docRemove.document, 'documentRemove');\n const key = this.fromName(docRemove.document);\n const removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if ('filter' in change) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n const filter = change.filter;\n assertPresent(filter.targetId, 'filter.targetId');\n const count = filter.count || 0;\n const existenceFilter = new ExistenceFilter(count);\n const targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n return watchChange;\n }\n\n fromWatchTargetChangeState(\n state: api.TargetChangeTargetChangeType\n ): WatchTargetChangeState {\n if (state === 'NO_CHANGE') {\n return WatchTargetChangeState.NoChange;\n } else if (state === 'ADD') {\n return WatchTargetChangeState.Added;\n } else if (state === 'REMOVE') {\n return WatchTargetChangeState.Removed;\n } else if (state === 'CURRENT') {\n return WatchTargetChangeState.Current;\n } else if (state === 'RESET') {\n return WatchTargetChangeState.Reset;\n } else {\n return fail('Got unexpected TargetChange.state: ' + state);\n }\n }\n\n versionFromListenResponse(change: api.ListenResponse): SnapshotVersion {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!('targetChange' in change)) {\n return SnapshotVersion.MIN;\n }\n const targetChange = change.targetChange!;\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.MIN;\n }\n if (!targetChange.readTime) {\n return SnapshotVersion.MIN;\n }\n return this.fromVersion(targetChange.readTime);\n }\n\n toMutation(mutation: Mutation): api.Write {\n let result: api.Write;\n if (mutation instanceof SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = { delete: this.toName(mutation.key) };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(transform =>\n this.toFieldTransform(transform)\n )\n }\n };\n } else if (mutation instanceof VerifyMutation) {\n result = {\n verify: this.toName(mutation.key)\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n\n return result;\n }\n\n fromMutation(proto: api.Write): Mutation {\n const precondition = proto.currentDocument\n ? this.fromPrecondition(proto.currentDocument)\n : Precondition.NONE;\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n const key = this.fromName(proto.update.name);\n const value = this.fromFields(proto.update.fields || {});\n if (proto.updateMask) {\n const fieldMask = this.fromDocumentMask(proto.updateMask);\n return new PatchMutation(key, value, fieldMask, precondition);\n } else {\n return new SetMutation(key, value, precondition);\n }\n } else if (proto.delete) {\n const key = this.fromName(proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.transform) {\n const key = this.fromName(proto.transform.document!);\n const fieldTransforms = proto.transform.fieldTransforms!.map(transform =>\n this.fromFieldTransform(transform)\n );\n assert(\n precondition.exists === true,\n 'Transforms only support precondition \"exists == true\"'\n );\n return new TransformMutation(key, fieldTransforms);\n } else if (proto.verify) {\n const key = this.fromName(proto.verify);\n return new VerifyMutation(key, precondition);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n }\n\n private toPrecondition(precondition: Precondition): api.Precondition {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return { exists: precondition.exists };\n } else {\n return fail('Unknown precondition');\n }\n }\n\n private fromPrecondition(precondition: api.Precondition): Precondition {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.NONE;\n }\n }\n\n private fromWriteResult(\n proto: api.WriteResult,\n commitTime: string\n ): MutationResult {\n // NOTE: Deletes don't have an updateTime.\n let version = proto.updateTime\n ? this.fromVersion(proto.updateTime)\n : this.fromVersion(commitTime);\n\n if (version.isEqual(SnapshotVersion.MIN)) {\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n version = this.fromVersion(commitTime);\n }\n\n let transformResults: fieldValue.FieldValue[] | null = null;\n if (proto.transformResults && proto.transformResults.length > 0) {\n transformResults = proto.transformResults.map(result =>\n this.fromValue(result)\n );\n }\n return new MutationResult(version, transformResults);\n }\n\n fromWriteResults(\n protos: api.WriteResult[] | undefined,\n commitTime?: string\n ): MutationResult[] {\n if (protos && protos.length > 0) {\n assert(\n commitTime !== undefined,\n 'Received a write result without a commit time'\n );\n return protos.map(proto => this.fromWriteResult(proto, commitTime));\n } else {\n return [];\n }\n }\n\n private toFieldTransform(fieldTransform: FieldTransform): api.FieldTransform {\n const transform = fieldTransform.transform;\n if (transform instanceof ServerTimestampTransform) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n setToServerValue: 'REQUEST_TIME'\n };\n } else if (transform instanceof ArrayUnionTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n appendMissingElements: {\n values: transform.elements.map(v => this.toValue(v))\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements.map(v => this.toValue(v))\n }\n };\n } else if (transform instanceof NumericIncrementTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n increment: this.toValue(transform.operand)\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n }\n\n private fromFieldTransform(proto: api.FieldTransform): FieldTransform {\n let transform: TransformOperation | null = null;\n if ('setToServerValue' in proto) {\n assert(\n proto.setToServerValue === 'REQUEST_TIME',\n 'Unknown server value transform proto: ' + JSON.stringify(proto)\n );\n transform = ServerTimestampTransform.instance;\n } else if ('appendMissingElements' in proto) {\n const values = proto.appendMissingElements!.values || [];\n transform = new ArrayUnionTransformOperation(\n values.map(v => this.fromValue(v))\n );\n } else if ('removeAllFromArray' in proto) {\n const values = proto.removeAllFromArray!.values || [];\n transform = new ArrayRemoveTransformOperation(\n values.map(v => this.fromValue(v))\n );\n } else if ('increment' in proto) {\n const operand = this.fromValue(proto.increment!);\n assert(\n operand instanceof fieldValue.NumberValue,\n 'NUMERIC_ADD transform requires a NumberValue'\n );\n transform = new NumericIncrementTransformOperation(\n operand as fieldValue.NumberValue\n );\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);\n return new FieldTransform(fieldPath, transform!);\n }\n\n toDocumentsTarget(target: Target): api.DocumentsTarget {\n return { documents: [this.toQueryPath(target.path)] };\n }\n\n fromDocumentsTarget(documentsTarget: api.DocumentsTarget): Target {\n const count = documentsTarget.documents!.length;\n assert(\n count === 1,\n 'DocumentsTarget contained other than 1 document: ' + count\n );\n const name = documentsTarget.documents![0];\n return Query.atPath(this.fromQueryPath(name)).toTarget();\n }\n\n toQueryTarget(target: Target): api.QueryTarget {\n // Dissect the path into parent, collectionId, and optional key filter.\n const result: api.QueryTarget = { structuredQuery: {} };\n const path = target.path;\n if (target.collectionGroup !== null) {\n assert(\n path.length % 2 === 0,\n 'Collection Group queries should be within a document path or root.'\n );\n result.parent = this.toQueryPath(path);\n result.structuredQuery!.from = [\n {\n collectionId: target.collectionGroup,\n allDescendants: true\n }\n ];\n } else {\n assert(\n path.length % 2 !== 0,\n 'Document queries with filters are not supported.'\n );\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery!.from = [{ collectionId: path.lastSegment() }];\n }\n\n const where = this.toFilter(target.filters);\n if (where) {\n result.structuredQuery!.where = where;\n }\n\n const orderBy = this.toOrder(target.orderBy);\n if (orderBy) {\n result.structuredQuery!.orderBy = orderBy;\n }\n\n const limit = this.toInt32Value(target.limit);\n if (limit !== null) {\n result.structuredQuery!.limit = limit;\n }\n\n if (target.startAt) {\n result.structuredQuery!.startAt = this.toCursor(target.startAt);\n }\n if (target.endAt) {\n result.structuredQuery!.endAt = this.toCursor(target.endAt);\n }\n\n return result;\n }\n\n fromQueryTarget(target: api.QueryTarget): Target {\n let path = this.fromQueryPath(target.parent!);\n\n const query = target.structuredQuery!;\n const fromCount = query.from ? query.from.length : 0;\n let collectionGroup: string | null = null;\n if (fromCount > 0) {\n assert(\n fromCount === 1,\n 'StructuredQuery.from with more than one collection is not supported.'\n );\n const from = query.from![0];\n if (from.allDescendants) {\n collectionGroup = from.collectionId!;\n } else {\n path = path.child(from.collectionId!);\n }\n }\n\n let filterBy: Filter[] = [];\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n\n let orderBy: OrderBy[] = [];\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n\n let limit: number | null = null;\n if (query.limit) {\n limit = this.fromInt32Value(query.limit);\n }\n\n let startAt: Bound | null = null;\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n\n let endAt: Bound | null = null;\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n\n return new Query(\n path,\n collectionGroup,\n orderBy,\n filterBy,\n limit,\n LimitType.First,\n startAt,\n endAt\n ).toTarget();\n }\n\n toListenRequestLabels(\n targetData: TargetData\n ): api.ApiClientObjectMap<string> | null {\n const value = this.toLabel(targetData.purpose);\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n }\n\n private toLabel(purpose: TargetPurpose): string | null {\n switch (purpose) {\n case TargetPurpose.Listen:\n return null;\n case TargetPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n case TargetPurpose.LimboResolution:\n return 'limbo-document';\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n }\n\n toTarget(targetData: TargetData): api.Target {\n let result: api.Target;\n const target = targetData.target;\n\n if (target.isDocumentQuery()) {\n result = { documents: this.toDocumentsTarget(target) };\n } else {\n result = { query: this.toQueryTarget(target) };\n }\n\n result.targetId = targetData.targetId;\n\n if (targetData.resumeToken.approximateByteSize() > 0) {\n result.resumeToken = this.toBytes(targetData.resumeToken);\n }\n\n return result;\n }\n\n private toFilter(filters: Filter[]): api.Filter | undefined {\n if (filters.length === 0) {\n return;\n }\n const protos = filters.map(filter => {\n if (filter instanceof FieldFilter) {\n return this.toUnaryOrFieldFilter(filter);\n } else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n });\n if (protos.length === 1) {\n return protos[0];\n }\n return { compositeFilter: { op: 'AND', filters: protos } };\n }\n\n private fromFilter(filter: api.Filter | undefined): Filter[] {\n if (!filter) {\n return [];\n } else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n } else if (filter.fieldFilter !== undefined) {\n return [this.fromFieldFilter(filter)];\n } else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter\n .filters!.map(f => this.fromFilter(f))\n .reduce((accum, current) => accum.concat(current));\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n }\n\n private toOrder(orderBys: OrderBy[]): api.Order[] | undefined {\n if (orderBys.length === 0) {\n return;\n }\n return orderBys.map(order => this.toPropertyOrder(order));\n }\n\n private fromOrder(orderBys: api.Order[]): OrderBy[] {\n return orderBys.map(order => this.fromPropertyOrder(order));\n }\n\n private toCursor(cursor: Bound): api.Cursor {\n return {\n before: cursor.before,\n values: cursor.position.map(component => this.toValue(component))\n };\n }\n\n private fromCursor(cursor: api.Cursor): Bound {\n const before = !!cursor.before;\n const position = cursor.values!.map(component => this.fromValue(component));\n return new Bound(position, before);\n }\n\n // visible for testing\n toDirection(dir: Direction): api.OrderDirection {\n return DIRECTIONS[dir.name];\n }\n\n // visible for testing\n fromDirection(dir: api.OrderDirection | undefined): Direction | undefined {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n case 'DESCENDING':\n return Direction.DESCENDING;\n default:\n return undefined;\n }\n }\n\n // visible for testing\n toOperatorName(op: Operator): api.FieldFilterOp {\n return OPERATORS[op.name];\n }\n\n fromOperatorName(op: api.FieldFilterOp): Operator {\n switch (op) {\n case 'EQUAL':\n return Operator.EQUAL;\n case 'GREATER_THAN':\n return Operator.GREATER_THAN;\n case 'GREATER_THAN_OR_EQUAL':\n return Operator.GREATER_THAN_OR_EQUAL;\n case 'LESS_THAN':\n return Operator.LESS_THAN;\n case 'LESS_THAN_OR_EQUAL':\n return Operator.LESS_THAN_OR_EQUAL;\n case 'ARRAY_CONTAINS':\n return Operator.ARRAY_CONTAINS;\n case 'IN':\n return Operator.IN;\n case 'ARRAY_CONTAINS_ANY':\n return Operator.ARRAY_CONTAINS_ANY;\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified operator');\n default:\n return fail('Unknown operator');\n }\n }\n\n toFieldPathReference(path: FieldPath): api.FieldReference {\n return { fieldPath: path.canonicalString() };\n }\n\n fromFieldPathReference(fieldReference: api.FieldReference): FieldPath {\n return FieldPath.fromServerFormat(fieldReference.fieldPath!);\n }\n\n // visible for testing\n toPropertyOrder(orderBy: OrderBy): api.Order {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n }\n\n fromPropertyOrder(orderBy: api.Order): OrderBy {\n return new OrderBy(\n this.fromFieldPathReference(orderBy.field!),\n this.fromDirection(orderBy.direction)\n );\n }\n\n fromFieldFilter(filter: api.Filter): Filter {\n return FieldFilter.create(\n this.fromFieldPathReference(filter.fieldFilter!.field!),\n this.fromOperatorName(filter.fieldFilter!.op!),\n this.fromValue(filter.fieldFilter!.value!)\n );\n }\n\n // visible for testing\n toUnaryOrFieldFilter(filter: FieldFilter): api.Filter {\n if (filter.op === Operator.EQUAL) {\n if (filter.value.isEqual(fieldValue.DoubleValue.NAN)) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (filter.value.isEqual(fieldValue.NullValue.INSTANCE)) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n }\n }\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n }\n\n fromUnaryFilter(filter: api.Filter): Filter {\n switch (filter.unaryFilter!.op!) {\n case 'IS_NAN':\n const nanField = this.fromFieldPathReference(\n filter.unaryFilter!.field!\n );\n return FieldFilter.create(\n nanField,\n Operator.EQUAL,\n fieldValue.DoubleValue.NAN\n );\n case 'IS_NULL':\n const nullField = this.fromFieldPathReference(\n filter.unaryFilter!.field!\n );\n return FieldFilter.create(\n nullField,\n Operator.EQUAL,\n fieldValue.NullValue.INSTANCE\n );\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n default:\n return fail('Unknown filter');\n }\n }\n\n toDocumentMask(fieldMask: FieldMask): api.DocumentMask {\n const canonicalFields: string[] = [];\n fieldMask.fields.forEach(field =>\n canonicalFields.push(field.canonicalString())\n );\n return {\n fieldPaths: canonicalFields\n };\n }\n\n fromDocumentMask(proto: api.DocumentMask): FieldMask {\n const paths = proto.fieldPaths || [];\n const fields = paths.map(path => FieldPath.fromServerFormat(path));\n return FieldMask.fromArray(fields);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { Connection } from '../remote/connection';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { fail } from '../util/assert';\nimport { ConnectivityMonitor } from './../remote/connectivity_monitor';\n\n/**\n * Provides a common interface to load anything platform dependent, e.g.\n * the connection implementation.\n *\n * An implementation of this must be provided at compile time for the platform.\n */\n// TODO: Consider only exposing the APIs of 'document' and 'window' that we\n// use in our client.\nexport interface Platform {\n loadConnection(databaseInfo: DatabaseInfo): Promise<Connection>;\n newConnectivityMonitor(): ConnectivityMonitor;\n newSerializer(databaseId: DatabaseId): JsonProtoSerializer;\n\n /** Formats an object as a JSON string, suitable for logging. */\n formatJSON(value: unknown): string;\n\n /** Converts a Base64 encoded string to a binary string. */\n atob(encoded: string): string;\n\n /** Converts a binary string to a Base64 encoded string. */\n btoa(raw: string): string;\n\n /**\n * Generates `nBytes` of random bytes. If `nBytes` is negative, an empty array\n * will be returned.\n */\n randomBytes(nBytes: number): Uint8Array;\n\n /** The Platform's 'window' implementation or null if not available. */\n readonly window: Window | null;\n\n /** The Platform's 'document' implementation or null if not available. */\n readonly document: Document | null;\n\n /** True if and only if the Base64 conversion functions are available. */\n readonly base64Available: boolean;\n}\n\n/**\n * Provides singleton helpers where setup code can inject a platform at runtime.\n * setPlatform needs to be set before Firestore is used and must be set exactly\n * once.\n */\nexport class PlatformSupport {\n private static platform: Platform;\n static setPlatform(platform: Platform): void {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n PlatformSupport.platform = platform;\n }\n\n static getPlatform(): Platform {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n return PlatformSupport.platform;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { SDK_VERSION } from '../core/version';\nimport { PlatformSupport } from '../platform/platform';\n\nconst logClient = new Logger('@firebase/firestore');\n\nexport const enum LogLevel {\n DEBUG,\n ERROR,\n SILENT\n}\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n if (logClient.logLevel === FirebaseLogLevel.DEBUG) {\n return LogLevel.DEBUG;\n } else if (logClient.logLevel === FirebaseLogLevel.SILENT) {\n return LogLevel.SILENT;\n } else {\n return LogLevel.ERROR;\n }\n}\nexport function setLogLevel(newLevel: LogLevel): void {\n /**\n * Map the new log level to the associated Firebase Log Level\n */\n switch (newLevel) {\n case LogLevel.DEBUG:\n logClient.logLevel = FirebaseLogLevel.DEBUG;\n break;\n case LogLevel.ERROR:\n logClient.logLevel = FirebaseLogLevel.ERROR;\n break;\n case LogLevel.SILENT:\n logClient.logLevel = FirebaseLogLevel.SILENT;\n break;\n default:\n logClient.error(\n `Firestore (${SDK_VERSION}): Invalid value passed to \\`setLogLevel\\``\n );\n }\n}\n\nexport function debug(tag: string, msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= FirebaseLogLevel.DEBUG) {\n const args = obj.map(argToString);\n logClient.debug(`Firestore (${SDK_VERSION}) [${tag}]: ${msg}`, ...args);\n }\n}\n\nexport function error(msg: string, ...obj: unknown[]): void {\n if (logClient.logLevel <= FirebaseLogLevel.ERROR) {\n const args = obj.map(argToString);\n logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */\nfunction argToString(obj: unknown): string | unknown {\n if (typeof obj === 'string') {\n return obj;\n } else {\n const platform = PlatformSupport.getPlatform();\n try {\n return platform.formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SDK_VERSION } from '../core/version';\n\nimport { error } from './log';\n\n/**\n * Unconditionally fails, throwing an Error with the given message.\n *\n * Returns any so it can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */\nexport function fail(failure: string): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const message =\n `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ` + failure;\n error(message);\n\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw new Error(message);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n */\nexport function assert(assertion: boolean, message: string): asserts assertion {\n if (!assertion) {\n fail(message);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { primitiveComparator } from '../util/misc';\n\nexport class DatabaseInfo {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId The database to use.\n * @param persistenceKey A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host The Firestore backend host to connect to.\n * @param ssl Whether to use SSL when connecting.\n * @param forceLongPolling Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n */\n constructor(\n readonly databaseId: DatabaseId,\n readonly persistenceKey: string,\n readonly host: string,\n readonly ssl: boolean,\n readonly forceLongPolling: boolean\n ) {}\n}\n\n/** The default database name for a project. */\nconst DEFAULT_DATABASE_NAME = '(default)';\n\n/** Represents the database ID a Firestore client is associated with. */\nexport class DatabaseId {\n readonly database: string;\n constructor(readonly projectId: string, database?: string) {\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n get isDefaultDatabase(): boolean {\n return this.database === DEFAULT_DATABASE_NAME;\n }\n\n isEqual(other: {}): boolean {\n return (\n other instanceof DatabaseId &&\n other.projectId === this.projectId &&\n other.database === this.database\n );\n }\n\n compareTo(other: DatabaseId): number {\n return (\n primitiveComparator(this.projectId, other.projectId) ||\n primitiveComparator(this.database, other.database)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 interface Resolver<R> {\n (value?: R | Promise<R>): void;\n}\n\nexport interface Rejecter {\n (reason?: Error): void;\n}\n\nexport interface CancelablePromise<T> extends Promise<T> {\n cancel(): void;\n}\n\nexport class Deferred<R> {\n promise: Promise<R>;\n // Assigned synchronously in constructor by Promise constructor callback.\n resolve!: Resolver<R>;\n reject!: Rejecter;\n\n constructor() {\n this.promise = new Promise((resolve: Resolver<R>, reject: Rejecter) => {\n this.resolve = resolve;\n this.reject = reject;\n });\n }\n}\n\n/**\n * Takes an array of values and a function from a value to a Promise. The function is run on each\n * value sequentially, waiting for the previous promise to resolve before starting the next one.\n * The returned promise resolves once the function has been run on all values.\n */\nexport function sequence<T>(\n values: T[],\n fn: (value: T) => Promise<void>\n): Promise<void> {\n let p = Promise.resolve();\n for (const value of values) {\n p = p.then(() => fn(value));\n }\n return p;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId } from '../core/types';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\nimport { ByteString } from '../util/byte_string';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentVersionMap,\n documentVersionMap,\n MaybeDocumentMap\n} from './collections';\nimport { MaybeDocument } from './document';\nimport { DocumentKey } from './document_key';\nimport { Mutation, MutationResult } from './mutation';\n\nexport const BATCHID_UNKNOWN = -1;\n\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */\nexport class MutationBatch {\n /**\n * @param batchId The unique ID of this mutation batch.\n * @param localWriteTime The original write time of this mutation.\n * @param baseMutations Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(\n public batchId: BatchId,\n public localWriteTime: Timestamp,\n public baseMutations: Mutation[],\n public mutations: Mutation[]\n ) {\n assert(mutations.length > 0, 'Cannot create an empty mutation batch');\n }\n\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to create a new remote document\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n * @param batchResult The result of applying the MutationBatch to the\n * backend.\n */\n applyToRemoteDocument(\n docKey: DocumentKey,\n maybeDoc: MaybeDocument | null,\n batchResult: MutationBatchResult\n ): MaybeDocument | null {\n if (maybeDoc) {\n assert(\n maybeDoc.key.isEqual(docKey),\n `applyToRemoteDocument: key ${docKey} should match maybeDoc key\n ${maybeDoc.key}`\n );\n }\n\n const mutationResults = batchResult.mutationResults;\n assert(\n mutationResults.length === this.mutations.length,\n `Mismatch between mutations length\n (${this.mutations.length}) and mutation results length\n (${mutationResults.length}).`\n );\n\n for (let i = 0; i < this.mutations.length; i++) {\n const mutation = this.mutations[i];\n if (mutation.key.isEqual(docKey)) {\n const mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n return maybeDoc;\n }\n\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param docKey The key of the document to apply mutations to.\n * @param maybeDoc The document to apply mutations to.\n */\n applyToLocalView(\n docKey: DocumentKey,\n maybeDoc: MaybeDocument | null\n ): MaybeDocument | null {\n if (maybeDoc) {\n assert(\n maybeDoc.key.isEqual(docKey),\n `applyToLocalDocument: key ${docKey} should match maybeDoc key\n ${maybeDoc.key}`\n );\n }\n\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const mutation of this.baseMutations) {\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(\n maybeDoc,\n maybeDoc,\n this.localWriteTime\n );\n }\n }\n\n const baseDoc = maybeDoc;\n\n // Second, apply all user-provided mutations.\n for (const mutation of this.mutations) {\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(\n maybeDoc,\n baseDoc,\n this.localWriteTime\n );\n }\n }\n return maybeDoc;\n }\n\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch.\n */\n applyToLocalDocumentSet(maybeDocs: MaybeDocumentMap): MaybeDocumentMap {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n let mutatedDocuments = maybeDocs;\n this.mutations.forEach(m => {\n const mutatedDocument = this.applyToLocalView(\n m.key,\n maybeDocs.get(m.key)\n );\n if (mutatedDocument) {\n mutatedDocuments = mutatedDocuments.insert(m.key, mutatedDocument);\n }\n });\n return mutatedDocuments;\n }\n\n keys(): DocumentKeySet {\n return this.mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n }\n\n isEqual(other: MutationBatch): boolean {\n return (\n this.batchId === other.batchId &&\n misc.arrayEquals(this.mutations, other.mutations) &&\n misc.arrayEquals(this.baseMutations, other.baseMutations)\n );\n }\n}\n\n/** The result of applying a mutation batch to the backend. */\nexport class MutationBatchResult {\n private constructor(\n readonly batch: MutationBatch,\n readonly commitVersion: SnapshotVersion,\n readonly mutationResults: MutationResult[],\n readonly streamToken: ByteString,\n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n readonly docVersions: DocumentVersionMap\n ) {}\n\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=>version mapping (docVersions).\n */\n static from(\n batch: MutationBatch,\n commitVersion: SnapshotVersion,\n results: MutationResult[],\n streamToken: ByteString\n ): MutationBatchResult {\n assert(\n batch.mutations.length === results.length,\n 'Mutations sent ' +\n batch.mutations.length +\n ' must equal results received ' +\n results.length\n );\n\n let versionMap = documentVersionMap();\n const mutations = batch.mutations;\n for (let i = 0; i < mutations.length; i++) {\n versionMap = versionMap.insert(mutations[i].key, results[i].version);\n }\n\n return new MutationBatchResult(\n batch,\n commitVersion,\n results,\n streamToken,\n versionMap\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Equatable } from './misc';\nimport * as objUtil from './obj';\n\ntype Entry<K, V> = [K, V];\n\n/**\n * A map implementation that uses objects as keys. Objects must implement the\n * Equatable interface and must be immutable. Entries in the map are stored\n * together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nexport class ObjectMap<KeyType extends Equatable<KeyType>, ValueType> {\n /**\n * The inner map for a key -> value pair. Due to the possibility of\n * collisions we keep a list of entries that we do a linear search through\n * to find an actual match. Note that collisions should be rare, so we still\n * expect near constant time lookups in practice.\n */\n private inner: {\n [canonicalId: string]: Array<Entry<KeyType, ValueType>>;\n } = {};\n\n constructor(private mapKeyFn: (key: KeyType) => string) {}\n\n /** Get a value for this key, or undefined if it does not exist. */\n get(key: KeyType): ValueType | undefined {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return undefined;\n }\n for (const [otherKey, value] of matches) {\n if (otherKey.isEqual(key)) {\n return value;\n }\n }\n return undefined;\n }\n\n has(key: KeyType): boolean {\n return this.get(key) !== undefined;\n }\n\n /** Put this key and value in the map. */\n set(key: KeyType, value: ValueType): void {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n matches.push([key, value]);\n }\n\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */\n delete(key: KeyType): boolean {\n const id = this.mapKeyFn(key);\n const matches = this.inner[id];\n if (matches === undefined) {\n return false;\n }\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n return true;\n }\n }\n return false;\n }\n\n forEach(fn: (key: KeyType, val: ValueType) => void): void {\n objUtil.forEach(this.inner, (_, entries) => {\n for (const [k, v] of entries) {\n fn(k, v);\n }\n });\n }\n\n isEmpty(): boolean {\n return objUtil.isEmpty(this.inner);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { TargetId } from '../core/types';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\n\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nexport class LocalViewChanges {\n constructor(\n readonly targetId: TargetId,\n readonly fromCache: boolean,\n readonly addedKeys: DocumentKeySet,\n readonly removedKeys: DocumentKeySet\n ) {}\n\n static fromSnapshot(\n targetId: TargetId,\n viewSnapshot: ViewSnapshot\n ): LocalViewChanges {\n let addedKeys = documentKeySet();\n let removedKeys = documentKeySet();\n\n for (const docChange of viewSnapshot.docChanges) {\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n default:\n // do nothing\n }\n }\n\n return new LocalViewChanges(\n targetId,\n viewSnapshot.fromCache,\n addedKeys,\n removedKeys\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, fail } from './assert';\nimport { Code, FirestoreError } from './error';\nimport * as log from './log';\nimport { CancelablePromise, Deferred } from './promise';\n\n// Accept any return type from setTimeout().\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype TimerHandle = any;\n\n/**\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\n * AsyncQueue. These IDs can then be used from tests to check for the presence\n * of operations or to run them early.\n *\n * The string values are used when encoding these timer IDs in JSON spec tests.\n */\nexport const enum TimerId {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n All = 'all',\n\n /**\n * The following 4 timers are used in persistent_stream.ts for the listen and\n * write streams. The \"Idle\" timer is used to close the stream due to\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\n * the appropriate backoff delay has elapsed.\n */\n ListenStreamIdle = 'listen_stream_idle',\n ListenStreamConnectionBackoff = 'listen_stream_connection_backoff',\n WriteStreamIdle = 'write_stream_idle',\n WriteStreamConnectionBackoff = 'write_stream_connection_backoff',\n\n /**\n * A timer used in online_state_tracker.ts to transition from\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\n * indefinitely for success or failure.\n */\n OnlineStateTimeout = 'online_state_timeout',\n\n /**\n * A timer used to update the client metadata in IndexedDb, which is used\n * to determine the primary leaseholder.\n */\n ClientMetadataRefresh = 'client_metadata_refresh',\n\n /** A timer used to periodically attempt LRU Garbage collection */\n LruGarbageCollection = 'lru_garbage_collection',\n\n /**\n * A timer used to retry transactions. Since there can be multiple concurrent\n * transactions, multiple of these may be in the queue at a given time.\n */\n RetryTransaction = 'retry_transaction'\n}\n\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n */\nclass DelayedOperation<T extends unknown> implements CancelablePromise<T> {\n // handle for use with clearTimeout(), or null if the operation has been\n // executed or canceled already.\n private timerHandle: TimerHandle | null;\n\n private readonly deferred = new Deferred<T>();\n\n private constructor(\n private readonly asyncQueue: AsyncQueue,\n readonly timerId: TimerId,\n readonly targetTimeMs: number,\n private readonly op: () => Promise<T>,\n private readonly removalCallback: (op: DelayedOperation<T>) => void\n ) {\n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch(err => {});\n }\n\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue The queue to schedule the operation on.\n * @param id A Timer ID identifying the type of operation this is.\n * @param delayMs The delay (ms) before the operation should be scheduled.\n * @param op The operation to run.\n * @param removalCallback A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */\n static createAndSchedule<R extends unknown>(\n asyncQueue: AsyncQueue,\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<R>,\n removalCallback: (op: DelayedOperation<R>) => void\n ): DelayedOperation<R> {\n const targetTime = Date.now() + delayMs;\n const delayedOp = new DelayedOperation(\n asyncQueue,\n timerId,\n targetTime,\n op,\n removalCallback\n );\n delayedOp.start(delayMs);\n return delayedOp;\n }\n\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */\n private start(delayMs: number): void {\n this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs);\n }\n\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */\n skipDelay(): void {\n return this.handleDelayElapsed();\n }\n\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */\n cancel(reason?: string): void {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(\n new FirestoreError(\n Code.CANCELLED,\n 'Operation cancelled' + (reason ? ': ' + reason : '')\n )\n );\n }\n }\n\n // Promise implementation.\n readonly [Symbol.toStringTag]: 'Promise';\n then = this.deferred.promise.then.bind(this.deferred.promise);\n catch = this.deferred.promise.catch.bind(this.deferred.promise);\n\n private handleDelayElapsed(): void {\n this.asyncQueue.enqueueAndForget(() => {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n return this.op().then(result => {\n return this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n }\n\n private clearTimeout(): void {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n }\n}\n\nexport class AsyncQueue {\n // The last promise in the queue.\n private tail: Promise<unknown> = Promise.resolve();\n\n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n private _isShuttingDown: boolean = false;\n\n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n private delayedOperations: Array<DelayedOperation<unknown>> = [];\n\n // visible for testing\n failure: Error | null = null;\n\n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n private operationInProgress = false;\n\n // List of TimerIds to fast-forward delays for.\n private timerIdsToSkip: TimerId[] = [];\n\n // Is this AsyncQueue being shut down? If true, this instance will not enqueue\n // any new operations, Promises from enqueue requests will not resolve.\n get isShuttingDown(): boolean {\n return this._isShuttingDown;\n }\n\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */\n enqueueAndForget<T extends unknown>(op: () => Promise<T>): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(op);\n }\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue without waiting for it to complete (i.e. we ignore the Promise result).\n */\n enqueueAndForgetEvenAfterShutdown<T extends unknown>(\n op: () => Promise<T>\n ): void {\n this.verifyNotFailed();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueueInternal(op);\n }\n\n /**\n * Regardless if the queue has initialized shutdown, adds a new operation to the\n * queue.\n */\n private enqueueEvenAfterShutdown<T extends unknown>(\n op: () => Promise<T>\n ): Promise<T> {\n this.verifyNotFailed();\n return this.enqueueInternal(op);\n }\n\n /**\n * Adds a new operation to the queue and initialize the shut down of this queue.\n * Returns a promise that will be resolved when the promise returned by the new\n * operation is (with its value).\n * Once this method is called, the only possible way to request running an operation\n * is through `enqueueAndForgetEvenAfterShutdown`.\n */\n async enqueueAndInitiateShutdown(op: () => Promise<void>): Promise<void> {\n this.verifyNotFailed();\n if (!this._isShuttingDown) {\n this._isShuttingDown = true;\n await this.enqueueEvenAfterShutdown(op);\n }\n }\n\n /**\n * Adds a new operation to the queue. Returns a promise that will be resolved\n * when the promise returned by the new operation is (with its value).\n */\n enqueue<T extends unknown>(op: () => Promise<T>): Promise<T> {\n this.verifyNotFailed();\n if (this._isShuttingDown) {\n // Return a Promise which never resolves.\n return new Promise<T>(resolve => {});\n }\n return this.enqueueInternal(op);\n }\n\n private enqueueInternal<T extends unknown>(op: () => Promise<T>): Promise<T> {\n const newTail = this.tail.then(() => {\n this.operationInProgress = true;\n return op()\n .catch((error: FirestoreError) => {\n this.failure = error;\n this.operationInProgress = false;\n const message = error.stack || error.message || '';\n log.error('INTERNAL UNHANDLED ERROR: ', message);\n\n // Escape the promise chain and throw the error globally so that\n // e.g. any global crash reporting library detects and reports it.\n // (but not for simulated errors in our tests since this breaks mocha)\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\n setTimeout(() => {\n throw error;\n }, 0);\n }\n\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw error;\n })\n .then(result => {\n this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n }\n\n /**\n * Schedules an operation to be queued on the AsyncQueue once the specified\n * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel\n * the operation prior to its running.\n */\n enqueueAfterDelay<T extends unknown>(\n timerId: TimerId,\n delayMs: number,\n op: () => Promise<T>\n ): CancelablePromise<T> {\n this.verifyNotFailed();\n\n assert(\n delayMs >= 0,\n `Attempted to schedule an operation with a negative delay of ${delayMs}`\n );\n\n // Fast-forward delays for timerIds that have been overriden.\n if (this.timerIdsToSkip.indexOf(timerId) > -1) {\n delayMs = 0;\n }\n\n const delayedOp = DelayedOperation.createAndSchedule<T>(\n this,\n timerId,\n delayMs,\n op,\n removedOp =>\n this.removeDelayedOperation(removedOp as DelayedOperation<unknown>)\n );\n this.delayedOperations.push(delayedOp as DelayedOperation<unknown>);\n return delayedOp;\n }\n\n private verifyNotFailed(): void {\n if (this.failure) {\n fail(\n 'AsyncQueue is already failed: ' +\n (this.failure.stack || this.failure.message)\n );\n }\n }\n\n /**\n * Verifies there's an operation currently in-progress on the AsyncQueue.\n * Unfortunately we can't verify that the running code is in the promise chain\n * of that operation, so this isn't a foolproof check, but it should be enough\n * to catch some bugs.\n */\n verifyOperationInProgress(): void {\n assert(\n this.operationInProgress,\n 'verifyOpInProgress() called when no op in progress on this queue.'\n );\n }\n\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */\n async drain(): Promise<void> {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let currentTail: Promise<unknown>;\n do {\n currentTail = this.tail;\n await currentTail;\n } while (currentTail !== this.tail);\n }\n\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */\n containsDelayedOperation(timerId: TimerId): boolean {\n for (const op of this.delayedOperations) {\n if (op.timerId === timerId) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId Delayed operations up to and including this TimerId will\n * be drained. Throws if no such operation exists. Pass TimerId.All to run\n * all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */\n runDelayedOperationsEarly(lastTimerId: TimerId): Promise<void> {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.drain().then(() => {\n assert(\n lastTimerId === TimerId.All ||\n this.containsDelayedOperation(lastTimerId),\n `Attempted to drain to missing operation ${lastTimerId}`\n );\n\n // Run ops in the same order they'd run if they ran naturally.\n this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs);\n\n for (const op of this.delayedOperations) {\n op.skipDelay();\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return this.drain();\n });\n }\n\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */\n skipDelaysForTimerId(timerId: TimerId): void {\n this.timerIdsToSkip.push(timerId);\n }\n\n /** Called once a DelayedOperation is run or canceled. */\n private removeDelayedOperation(op: DelayedOperation<unknown>): void {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const index = this.delayedOperations.indexOf(op);\n assert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { fail } from '../util/assert';\n\nexport type FulfilledHandler<T, R> =\n | ((result: T) => R | PersistencePromise<R>)\n | null;\nexport type RejectedHandler<R> =\n | ((reason: Error) => R | PersistencePromise<R>)\n | null;\nexport type Resolver<T> = (value?: T) => void;\nexport type Rejector = (error: Error) => void;\n\n/**\n * PersistencePromise<> is essentially a re-implementation of Promise<> except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise<> implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */\nexport class PersistencePromise<T> {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n private nextCallback: FulfilledHandler<T, unknown> = null;\n private catchCallback: RejectedHandler<unknown> = null;\n\n // When the operation resolves, we'll set result or error and mark isDone.\n private result: T | undefined = undefined;\n private error: Error | undefined = undefined;\n private isDone = false;\n\n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n private callbackAttached = false;\n\n constructor(callback: (resolve: Resolver<T>, reject: Rejector) => void) {\n callback(\n value => {\n this.isDone = true;\n this.result = value;\n if (this.nextCallback) {\n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(value!);\n }\n },\n error => {\n this.isDone = true;\n this.error = error;\n if (this.catchCallback) {\n this.catchCallback(error);\n }\n }\n );\n }\n\n catch<R>(\n fn: (error: Error) => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n return this.next(undefined, fn);\n }\n\n next<R>(\n nextFn?: FulfilledHandler<T, R>,\n catchFn?: RejectedHandler<R>\n ): PersistencePromise<R> {\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n this.callbackAttached = true;\n if (this.isDone) {\n if (!this.error) {\n return this.wrapSuccess(nextFn, this.result!);\n } else {\n return this.wrapFailure(catchFn, this.error);\n }\n } else {\n return new PersistencePromise<R>((resolve, reject) => {\n this.nextCallback = (value: T) => {\n this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n this.catchCallback = (error: Error) => {\n this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n }\n\n toPromise(): Promise<T> {\n return new Promise((resolve, reject) => {\n this.next(resolve, reject);\n });\n }\n\n private wrapUserFunction<R>(\n fn: () => R | PersistencePromise<R>\n ): PersistencePromise<R> {\n try {\n const result = fn();\n if (result instanceof PersistencePromise) {\n return result;\n } else {\n return PersistencePromise.resolve(result);\n }\n } catch (e) {\n return PersistencePromise.reject<R>(e);\n }\n }\n\n private wrapSuccess<R>(\n nextFn: FulfilledHandler<T, R> | undefined,\n value: T\n ): PersistencePromise<R> {\n if (nextFn) {\n return this.wrapUserFunction(() => nextFn(value));\n } else {\n // If there's no nextFn, then R must be the same as T\n return PersistencePromise.resolve<R>((value as unknown) as R);\n }\n }\n\n private wrapFailure<R>(\n catchFn: RejectedHandler<R> | undefined,\n error: Error\n ): PersistencePromise<R> {\n if (catchFn) {\n return this.wrapUserFunction(() => catchFn(error));\n } else {\n return PersistencePromise.reject<R>(error);\n }\n }\n\n static resolve(): PersistencePromise<void>;\n static resolve<R>(result: R): PersistencePromise<R>;\n static resolve<R>(result?: R): PersistencePromise<R | void> {\n return new PersistencePromise<R | void>((resolve, reject) => {\n resolve(result);\n });\n }\n\n static reject<R>(error: Error): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n reject(error);\n });\n }\n\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n all: { forEach: (cb: (el: PersistencePromise<any>) => void) => void }\n ): PersistencePromise<void> {\n return new PersistencePromise<void>((resolve, reject) => {\n let expectedCount = 0;\n let resolvedCount = 0;\n let done = false;\n\n all.forEach(element => {\n ++expectedCount;\n element.next(\n () => {\n ++resolvedCount;\n if (done && resolvedCount === expectedCount) {\n resolve();\n }\n },\n err => reject(err)\n );\n });\n\n done = true;\n if (resolvedCount === expectedCount) {\n resolve();\n }\n });\n }\n\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */\n static or(\n predicates: Array<() => PersistencePromise<boolean>>\n ): PersistencePromise<boolean> {\n let p: PersistencePromise<boolean> = PersistencePromise.resolve<boolean>(\n false\n );\n for (const predicate of predicates) {\n p = p.next(isTrue => {\n if (isTrue) {\n return PersistencePromise.resolve<boolean>(isTrue);\n } else {\n return predicate();\n }\n });\n }\n return p;\n }\n\n /**\n * Given an iterable, call the given function on each element in the\n * collection and wait for all of the resulting concurrent PersistencePromises\n * to resolve.\n */\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s: S) => void) => void },\n f:\n | ((r: R, s: S) => PersistencePromise<void>)\n | ((r: R) => PersistencePromise<void>)\n ): PersistencePromise<void>;\n static forEach<R>(\n collection: { forEach: (cb: (r: R) => void) => void },\n f: (r: R) => PersistencePromise<void>\n ): PersistencePromise<void>;\n static forEach<R, S>(\n collection: { forEach: (cb: (r: R, s?: S) => void) => void },\n f: (r: R, s?: S) => PersistencePromise<void>\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n collection.forEach((r, s) => {\n promises.push(f.call(this, r, s));\n });\n return this.waitFor(promises);\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { assert } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { CancelablePromise } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetData } from './target_data';\n\n/**\n * Persistence layers intending to use LRU Garbage collection should have reference delegates that\n * implement this interface. This interface defines the operations that the LRU garbage collector\n * needs from the persistence layer.\n */\nexport interface LruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n /** Enumerates all the targets in the TargetCache. */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (target: TargetData) => void\n ): PersistencePromise<void>;\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number>;\n\n /**\n * Enumerates sequence numbers for documents not associated with a target.\n * Note that this may include duplicate sequence numbers.\n */\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void>;\n\n /**\n * Removes all targets that have a sequence number less than or equal to `upperBound`, and are not\n * present in the `activeTargetIds` set.\n *\n * @return the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number>;\n\n /**\n * Removes all unreferenced documents from the cache that have a sequence number less than or\n * equal to the given `upperBound`.\n *\n * @return the number of documents removed.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number>;\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number>;\n}\n\n/**\n * Describes a map whose keys are active target ids. We do not care about the type of the\n * values.\n */\nexport type ActiveTargets = SortedMap<TargetId, unknown>;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet<BufferEntry> = new SortedSet<BufferEntry>(\n bufferEntryComparator\n );\n\n private previousIndex = 0;\n\n constructor(private readonly maxElements: number) {}\n\n private nextIndex(): number {\n return ++this.previousIndex;\n }\n\n addElement(sequenceNumber: ListenSequenceNumber): void {\n const entry: BufferEntry = [sequenceNumber, this.nextIndex()];\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n const highestValue = this.buffer.last()!;\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n }\n\n get maxValue(): ListenSequenceNumber {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()![0];\n }\n}\n\n/**\n * Describes the results of a garbage collection run. `didRun` will be set to\n * `false` if collection was skipped (either it is disabled or the cache size\n * has not hit the threshold). If collection ran, the other fields will be\n * filled in with the details of the results.\n */\nexport interface LruResults {\n readonly didRun: boolean;\n readonly sequenceNumbersCollected: number;\n readonly targetsRemoved: number;\n readonly documentsRemoved: number;\n}\n\nconst GC_DID_NOT_RUN: LruResults = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nexport class LruParams {\n static readonly COLLECTION_DISABLED = -1;\n static readonly MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n static readonly DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n private static readonly DEFAULT_COLLECTION_PERCENTILE = 10;\n private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n\n static withCacheSize(cacheSize: number): LruParams {\n return new LruParams(\n cacheSize,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n }\n\n static readonly DEFAULT: LruParams = new LruParams(\n LruParams.DEFAULT_CACHE_SIZE_BYTES,\n LruParams.DEFAULT_COLLECTION_PERCENTILE,\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT\n );\n\n static readonly DISABLED: LruParams = new LruParams(\n LruParams.COLLECTION_DISABLED,\n 0,\n 0\n );\n\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n readonly cacheSizeCollectionThreshold: number,\n // The percentage of sequence numbers that we will attempt to collect\n readonly percentileToCollect: number,\n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n readonly maximumSequenceNumbersToCollect: number\n ) {}\n}\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */\nexport class LruScheduler {\n private hasRun: boolean = false;\n private gcTask: CancelablePromise<void> | null;\n\n constructor(\n private readonly garbageCollector: LruGarbageCollector,\n private readonly asyncQueue: AsyncQueue\n ) {\n this.gcTask = null;\n }\n\n start(localStore: LocalStore): void {\n assert(\n this.gcTask === null,\n 'Cannot start an already started LruScheduler'\n );\n if (\n this.garbageCollector.params.cacheSizeCollectionThreshold !==\n LruParams.COLLECTION_DISABLED\n ) {\n this.scheduleGC(localStore);\n }\n }\n\n stop(): void {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n }\n\n get started(): boolean {\n return this.gcTask !== null;\n }\n\n private scheduleGC(localStore: LocalStore): void {\n assert(this.gcTask === null, 'Cannot schedule GC while a task is pending');\n const delay = this.hasRun ? REGULAR_GC_DELAY_MS : INITIAL_GC_DELAY_MS;\n log.debug(\n 'LruGarbageCollector',\n `Garbage collection scheduled in ${delay}ms`\n );\n this.gcTask = this.asyncQueue.enqueueAfterDelay(\n TimerId.LruGarbageCollection,\n delay,\n () => {\n this.gcTask = null;\n this.hasRun = true;\n return localStore\n .collectGarbage(this.garbageCollector)\n .then(() => this.scheduleGC(localStore))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n );\n }\n}\n\n/** Implements the steps for LRU garbage collection. */\nexport class LruGarbageCollector {\n constructor(\n private readonly delegate: LruDelegate,\n readonly params: LruParams\n ) {}\n\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n calculateTargetCount(\n txn: PersistenceTransaction,\n percentile: number\n ): PersistencePromise<number> {\n return this.delegate.getSequenceNumberCount(txn).next(targetCount => {\n return Math.floor((percentile / 100.0) * targetCount);\n });\n }\n\n /** Returns the nth sequence number, counting in order from the smallest. */\n nthSequenceNumber(\n txn: PersistenceTransaction,\n n: number\n ): PersistencePromise<ListenSequenceNumber> {\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n const buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate\n .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber))\n .next(() => {\n return this.delegate.forEachOrphanedDocumentSequenceNumber(\n txn,\n sequenceNumber => buffer.addElement(sequenceNumber)\n );\n })\n .next(() => buffer.maxValue);\n }\n\n /**\n * Removes targets with a sequence number equal to or less than the given upper bound, and removes\n * document associations with those targets.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n }\n\n /**\n * Removes documents that have a sequence number equal to or less than the upper bound and are not\n * otherwise pinned.\n */\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n }\n\n collect(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n if (\n this.params.cacheSizeCollectionThreshold === LruParams.COLLECTION_DISABLED\n ) {\n log.debug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(cacheSize => {\n if (cacheSize < this.params.cacheSizeCollectionThreshold) {\n log.debug(\n 'LruGarbageCollector',\n `Garbage collection skipped; Cache size ${cacheSize} ` +\n `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`\n );\n return GC_DID_NOT_RUN;\n } else {\n return this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.delegate.getCacheSize(txn);\n }\n\n private runGarbageCollection(\n txn: PersistenceTransaction,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<LruResults> {\n let upperBoundSequenceNumber: number;\n let sequenceNumbersToCollect: number, targetsRemoved: number;\n // Timestamps for various pieces of the process\n let countedTargetsTs: number,\n foundUpperBoundTs: number,\n removedTargetsTs: number,\n removedDocumentsTs: number;\n const startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect)\n .next(sequenceNumbers => {\n // Cap at the configured max\n if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) {\n log.debug(\n 'LruGarbageCollector',\n 'Capping sequence numbers to collect down ' +\n `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` +\n `from ${sequenceNumbers}`\n );\n sequenceNumbersToCollect = this.params\n .maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n countedTargetsTs = Date.now();\n\n return this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n })\n .next(upperBound => {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n\n return this.removeTargets(\n txn,\n upperBoundSequenceNumber,\n activeTargetIds\n );\n })\n .next(numTargetsRemoved => {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n\n return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n })\n .next(documentsRemoved => {\n removedDocumentsTs = Date.now();\n\n if (log.getLogLevel() <= log.LogLevel.DEBUG) {\n const desc =\n 'LRU Garbage Collection\\n' +\n `\\tCounted targets in ${countedTargetsTs - startTs}ms\\n` +\n `\\tDetermined least recently used ${sequenceNumbersToCollect} in ` +\n `${foundUpperBoundTs - countedTargetsTs}ms\\n` +\n `\\tRemoved ${targetsRemoved} targets in ` +\n `${removedTargetsTs - foundUpperBoundTs}ms\\n` +\n `\\tRemoved ${documentsRemoved} documents in ` +\n `${removedDocumentsTs - removedTargetsTs}ms\\n` +\n `Total Duration: ${removedDocumentsTs - startTs}ms`;\n log.debug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve<LruResults>({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved,\n documentsRemoved\n });\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { BatchId, TargetId } from '../core/types';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */\nexport class ReferenceSet {\n // A set of outstanding references to a document sorted by key.\n private refsByKey = new SortedSet(DocReference.compareByKey);\n\n // A set of outstanding references to a document sorted by target id.\n private refsByTarget = new SortedSet(DocReference.compareByTargetId);\n\n /** Returns true if the reference set contains no references. */\n isEmpty(): boolean {\n return this.refsByKey.isEmpty();\n }\n\n /** Adds a reference to the given document key for the given ID. */\n addReference(key: DocumentKey, id: TargetId | BatchId): void {\n const ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n }\n\n /** Add references to the given document keys for the given ID. */\n addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.addReference(key, id));\n }\n\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */\n removeReference(key: DocumentKey, id: TargetId | BatchId): void {\n this.removeRef(new DocReference(key, id));\n }\n\n removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void {\n keys.forEach(key => this.removeReference(key, id));\n }\n\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */\n removeReferencesForId(id: TargetId | BatchId): DocumentKey[] {\n const emptyKey = DocumentKey.EMPTY;\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n const keys: DocumentKey[] = [];\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n this.removeRef(ref);\n keys.push(ref.key);\n });\n return keys;\n }\n\n removeAllReferences(): void {\n this.refsByKey.forEach(ref => this.removeRef(ref));\n }\n\n private removeRef(ref: DocReference): void {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n }\n\n referencesForId(id: TargetId | BatchId): DocumentKeySet {\n const emptyKey = DocumentKey.EMPTY;\n const startRef = new DocReference(emptyKey, id);\n const endRef = new DocReference(emptyKey, id + 1);\n let keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], ref => {\n keys = keys.add(ref.key);\n });\n return keys;\n }\n\n containsKey(key: DocumentKey): boolean {\n const ref = new DocReference(key, 0);\n const firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return firstRef !== null && key.isEqual(firstRef.key);\n }\n}\n\nexport class DocReference {\n constructor(\n public key: DocumentKey,\n public targetOrBatchId: TargetId | BatchId\n ) {}\n\n /** Compare by key then by ID */\n static compareByKey(left: DocReference, right: DocReference): number {\n return (\n DocumentKey.comparator(left.key, right.key) ||\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)\n );\n }\n\n /** Compare by ID then by key */\n static compareByTargetId(left: DocReference, right: DocReference): number {\n return (\n primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) ||\n DocumentKey.comparator(left.key, right.key)\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DocumentKeySet, NullableMaybeDocumentMap } from '../model/collections';\nimport { MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { assert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SnapshotVersion } from '../core/snapshot_version';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written (or null if any\n // existing cache entry should be removed).\n protected changes: ObjectMap<\n DocumentKey,\n MaybeDocument | null\n > = new ObjectMap(key => key.toString());\n\n // The read time to use for all added documents in this change buffer.\n private _readTime: SnapshotVersion | undefined;\n\n private changesApplied = false;\n\n protected abstract getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null>;\n\n protected abstract getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap>;\n\n protected abstract applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void>;\n\n protected set readTime(value: SnapshotVersion) {\n // Right now (for simplicity) we just track a single readTime for all the\n // added entries since we expect them to all be the same, but we could\n // rework to store per-entry readTimes if necessary.\n assert(\n this._readTime === undefined || this._readTime.isEqual(value),\n 'All changes in a RemoteDocumentChangeBuffer must have the same read time'\n );\n this._readTime = value;\n }\n\n protected get readTime(): SnapshotVersion {\n assert(\n this._readTime !== undefined,\n 'Read time is not set. All removeEntry() calls must include a readTime if `trackRemovals` is used.'\n );\n return this._readTime;\n }\n\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n addEntry(maybeDocument: MaybeDocument, readTime: SnapshotVersion): void {\n this.assertNotApplied();\n this.readTime = readTime;\n this.changes.set(maybeDocument.key, maybeDocument);\n }\n\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */\n removeEntry(key: DocumentKey, readTime?: SnapshotVersion): void {\n this.assertNotApplied();\n if (readTime) {\n this.readTime = readTime;\n }\n this.changes.set(key, null);\n }\n\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKey The key of the entry to look up.\n * @return The cached Document or NoDocument entry, or null if we have nothing\n * cached.\n */\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n this.assertNotApplied();\n const bufferedEntry = this.changes.get(documentKey);\n if (bufferedEntry !== undefined) {\n return PersistencePromise.resolve<MaybeDocument | null>(bufferedEntry);\n } else {\n return this.getFromCache(transaction, documentKey);\n }\n }\n\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction The transaction in which to perform any persistence\n * operations.\n * @param documentKeys The keys of the entries to look up.\n * @return A map of cached `Document`s or `NoDocument`s, indexed by key. If an\n * entry cannot be found, the corresponding key will be mapped to a null\n * value.\n */\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n return this.getAllFromCache(transaction, documentKeys);\n }\n\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */\n apply(transaction: PersistenceTransaction): PersistencePromise<void> {\n this.assertNotApplied();\n this.changesApplied = true;\n return this.applyChanges(transaction);\n }\n\n /** Helper to assert this.changes is not null */\n protected assertNotApplied(): void {\n assert(!this.changesApplied, 'Changes have already been applied.');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { User } from '../auth/user';\nimport { Query } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { Target } from '../core/target';\nimport { BatchId, TargetId } from '../core/types';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap,\n maybeDocumentMap,\n MaybeDocumentMap\n} from '../model/collections';\nimport { MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation, PatchMutation, Precondition } from '../model/mutation';\nimport {\n BATCHID_UNKNOWN,\n MutationBatch,\n MutationBatchResult\n} from '../model/mutation_batch';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { LocalDocumentsView } from './local_documents_view';\nimport { LocalViewChanges } from './local_view_changes';\nimport { LruGarbageCollector, LruResults } from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport {\n Persistence,\n PersistenceTransaction,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetCache } from './target_cache';\nimport { QueryEngine } from './query_engine';\nimport { ReferenceSet } from './reference_set';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { ClientId } from './shared_client_state';\nimport { TargetData, TargetPurpose } from './target_data';\nimport { ByteString } from '../util/byte_string';\n\nconst LOG_TAG = 'LocalStore';\n\n/** The result of a write to the local store. */\nexport interface LocalWriteResult {\n batchId: BatchId;\n changes: MaybeDocumentMap;\n}\n\n/** The result of a user-change operation in the local store. */\nexport interface UserChangeResult {\n readonly affectedDocuments: MaybeDocumentMap;\n readonly removedBatchIds: BatchId[];\n readonly addedBatchIds: BatchId[];\n}\n\n/** The result of executing a query against the local store. */\nexport interface QueryResult {\n readonly documents: DocumentMap;\n readonly remoteKeys: DocumentKeySet;\n}\n\n/**\n * Local storage in the Firestore client. Coordinates persistence components\n * like the mutation queue and remote document cache to present a\n * latency-compensated view of stored data.\n *\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\n * Writes from the client are put into a queue as provisional Mutations until\n * they are processed by the RemoteStore and confirmed as having been written\n * to the server.\n *\n * The local store provides the local version of documents that have been\n * modified locally. It maintains the constraint:\n *\n * LocalDocument = RemoteDocument + Active(LocalMutations)\n *\n * (Active mutations are those that are enqueued and have not been previously\n * acknowledged or rejected).\n *\n * The RemoteDocument (\"ground truth\") state is provided via the\n * applyChangeBatch method. It will be some version of a server-provided\n * document OR will be a server-provided document PLUS acknowledged mutations:\n *\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\n *\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\n * server base version, since it has LocalMutations added to it pending getting\n * an authoritative copy from the server.\n *\n * Since LocalMutations can be rejected by the server, we have to be able to\n * revert a LocalMutation that has already been applied to the LocalDocument\n * (typically done by replaying all remaining LocalMutations to the\n * RemoteDocument to re-apply).\n *\n * The LocalStore is responsible for the garbage collection of the documents it\n * contains. For now, it every doc referenced by a view, the mutation queue, or\n * the RemoteStore.\n *\n * It also maintains the persistence of mapping queries to resume tokens and\n * target ids. It needs to know this data about queries to properly know what\n * docs it would be allowed to garbage collect.\n *\n * The LocalStore must be able to efficiently execute queries against its local\n * cache of the documents, to provide the initial set of results before any\n * remote changes have been received.\n *\n * Note: In TypeScript, most methods return Promises since the implementation\n * may rely on fetching data from IndexedDB which is async.\n * These Promises will only be rejected on an I/O error or other internal\n * (unexpected) failure (e.g. failed assert) and always represent an\n * unrecoverable error (should be caught / reported by the async_queue).\n */\nexport class LocalStore {\n /**\n * The maximum time to leave a resume token buffered without writing it out.\n * This value is arbitrary: it's long enough to avoid several writes\n * (possibly indefinitely if updates come more frequently than this) but\n * short enough that restarting after crashing will still have a pretty\n * recent resume token.\n */\n private static readonly RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationQueue;\n\n /** The set of all cached remote documents. */\n private remoteDocuments: RemoteDocumentCache;\n\n /**\n * The \"local\" view of all documents (layering mutationQueue on top of\n * remoteDocumentCache).\n */\n private localDocuments: LocalDocumentsView;\n\n /**\n * The set of document references maintained by any local views.\n */\n private localViewReferences = new ReferenceSet();\n\n /** Maps a target to its `TargetData`. */\n private targetCache: TargetCache;\n\n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n private targetDataByTarget = new SortedMap<TargetId, TargetData>(\n primitiveComparator\n );\n\n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n private targetIdByTarget = new ObjectMap<Target, TargetId>(t =>\n t.canonicalId()\n );\n\n /**\n * The read time of the last entry processed by `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n private lastDocumentChangeReadTime = SnapshotVersion.MIN;\n\n constructor(\n /** Manages our in-memory or durable persistence. */\n private persistence: Persistence,\n private queryEngine: QueryEngine,\n initialUser: User\n ) {\n assert(\n persistence.started,\n 'LocalStore was passed an unstarted persistence implementation'\n );\n this.persistence.referenceDelegate.setInMemoryPins(\n this.localViewReferences\n );\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.targetCache = persistence.getTargetCache();\n this.localDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n this.mutationQueue,\n this.persistence.getIndexManager()\n );\n this.queryEngine.setLocalDocumentsView(this.localDocuments);\n }\n\n /** Starts the LocalStore. */\n start(): Promise<void> {\n return this.synchronizeLastDocumentChangeReadTime();\n }\n\n /**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n // PORTING NOTE: Android and iOS only return the documents affected by the\n // change.\n async handleUserChange(user: User): Promise<UserChangeResult> {\n let newMutationQueue = this.mutationQueue;\n let newLocalDocuments = this.localDocuments;\n\n const result = await this.persistence.runTransaction(\n 'Handle user change',\n 'readonly',\n txn => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let oldBatches: MutationBatch[];\n return this.mutationQueue\n .getAllMutationBatches(txn)\n .next(promisedOldBatches => {\n oldBatches = promisedOldBatches;\n\n newMutationQueue = this.persistence.getMutationQueue(user);\n\n // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n newLocalDocuments = new LocalDocumentsView(\n this.remoteDocuments,\n newMutationQueue,\n this.persistence.getIndexManager()\n );\n return newMutationQueue.getAllMutationBatches(txn);\n })\n .next(newBatches => {\n const removedBatchIds: BatchId[] = [];\n const addedBatchIds: BatchId[] = [];\n\n // Union the old/new changed keys.\n let changedKeys = documentKeySet();\n\n for (const batch of oldBatches) {\n removedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n for (const batch of newBatches) {\n addedBatchIds.push(batch.batchId);\n for (const mutation of batch.mutations) {\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return newLocalDocuments\n .getDocuments(txn, changedKeys)\n .next(affectedDocuments => {\n return {\n affectedDocuments,\n removedBatchIds,\n addedBatchIds\n };\n });\n });\n }\n );\n\n this.mutationQueue = newMutationQueue;\n this.localDocuments = newLocalDocuments;\n this.queryEngine.setLocalDocumentsView(this.localDocuments);\n\n return result;\n }\n\n /* Accept locally generated Mutations and commit them to storage. */\n localWrite(mutations: Mutation[]): Promise<LocalWriteResult> {\n const localWriteTime = Timestamp.now();\n const keys = mutations.reduce(\n (keys, m) => keys.add(m.key),\n documentKeySet()\n );\n\n let existingDocs: MaybeDocumentMap;\n\n return this.persistence\n .runTransaction('Locally write mutations', 'readwrite', txn => {\n // Load and apply all existing mutations. This lets us compute the\n // current base state for all non-idempotent transforms before applying\n // any additional user-provided writes.\n return this.localDocuments.getDocuments(txn, keys).next(docs => {\n existingDocs = docs;\n\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const baseMutations: Mutation[] = [];\n\n for (const mutation of mutations) {\n const baseValue = mutation.extractBaseValue(\n existingDocs.get(mutation.key)\n );\n if (baseValue != null) {\n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n baseMutations.push(\n new PatchMutation(\n mutation.key,\n baseValue,\n baseValue.fieldMask(),\n Precondition.exists(true)\n )\n );\n }\n }\n\n return this.mutationQueue.addMutationBatch(\n txn,\n localWriteTime,\n baseMutations,\n mutations\n );\n });\n })\n .then(batch => {\n const changes = batch.applyToLocalDocumentSet(existingDocs);\n return { batchId: batch.batchId, changes };\n });\n }\n\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-tab only.\n lookupMutationDocuments(batchId: BatchId): Promise<MaybeDocumentMap | null> {\n return this.persistence.runTransaction(\n 'Lookup mutation documents',\n 'readonly',\n txn => {\n return this.mutationQueue\n .lookupMutationKeys(txn, batchId)\n .next(keys => {\n if (keys) {\n return this.localDocuments.getDocuments(\n txn,\n keys\n ) as PersistencePromise<MaybeDocumentMap | null>;\n } else {\n return PersistencePromise.resolve<MaybeDocumentMap | null>(null);\n }\n });\n }\n );\n }\n\n /**\n * Acknowledge the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\n acknowledgeBatch(\n batchResult: MutationBatchResult\n ): Promise<MaybeDocumentMap> {\n return this.persistence.runTransaction(\n 'Acknowledge batch',\n 'readwrite-primary',\n txn => {\n const affected = batchResult.batch.keys();\n const documentBuffer = this.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n return this.mutationQueue\n .acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken)\n .next(() =>\n this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer)\n )\n .next(() => documentBuffer.apply(txn))\n .next(() => this.mutationQueue.performConsistencyCheck(txn))\n .next(() => this.localDocuments.getDocuments(txn, affected));\n }\n );\n }\n\n /**\n * Remove mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */\n rejectBatch(batchId: BatchId): Promise<MaybeDocumentMap> {\n return this.persistence.runTransaction(\n 'Reject batch',\n 'readwrite-primary',\n txn => {\n let affectedKeys: DocumentKeySet;\n return this.mutationQueue\n .lookupMutationBatch(txn, batchId)\n .next((batch: MutationBatch | null) => {\n assert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return this.mutationQueue.removeMutationBatch(txn, batch);\n })\n .next(() => {\n return this.mutationQueue.performConsistencyCheck(txn);\n })\n .next(() => {\n return this.localDocuments.getDocuments(txn, affectedKeys);\n });\n }\n );\n }\n\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending server response.\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */\n getHighestUnacknowledgedBatchId(): Promise<BatchId> {\n return this.persistence.runTransaction(\n 'Get highest unacknowledged batch id',\n 'readonly',\n txn => {\n return this.mutationQueue.getHighestUnacknowledgedBatchId(txn);\n }\n );\n }\n\n /** Returns the last recorded stream token for the current user. */\n getLastStreamToken(): Promise<ByteString> {\n return this.persistence.runTransaction(\n 'Get last stream token',\n 'readonly',\n txn => {\n return this.mutationQueue.getLastStreamToken(txn);\n }\n );\n }\n\n /**\n * Sets the stream token for the current user without acknowledging any\n * mutation batch. This is usually only useful after a stream handshake or in\n * response to an error that requires clearing the stream token.\n */\n setLastStreamToken(streamToken: ByteString): Promise<void> {\n return this.persistence.runTransaction(\n 'Set last stream token',\n 'readwrite-primary',\n txn => {\n return this.mutationQueue.setLastStreamToken(txn, streamToken);\n }\n );\n }\n\n /**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\n getLastRemoteSnapshotVersion(): Promise<SnapshotVersion> {\n return this.persistence.runTransaction(\n 'Get last remote snapshot version',\n 'readonly',\n txn => this.targetCache.getLastRemoteSnapshotVersion(txn)\n );\n }\n\n /**\n * Update the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\n applyRemoteEvent(remoteEvent: RemoteEvent): Promise<MaybeDocumentMap> {\n const remoteVersion = remoteEvent.snapshotVersion;\n let newTargetDataByTargetMap = this.targetDataByTarget;\n\n return this.persistence\n .runTransaction('Apply remote event', 'readwrite-primary', txn => {\n const documentBuffer = this.remoteDocuments.newChangeBuffer({\n trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()`\n });\n\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n newTargetDataByTargetMap = this.targetDataByTarget;\n\n const promises = [] as Array<PersistencePromise<void>>;\n objUtils.forEachNumber(\n remoteEvent.targetChanges,\n (targetId: TargetId, change: TargetChange) => {\n const oldTargetData = newTargetDataByTargetMap.get(targetId);\n if (!oldTargetData) {\n return;\n }\n\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n promises.push(\n this.targetCache\n .removeMatchingKeys(txn, change.removedDocuments, targetId)\n .next(() => {\n return this.targetCache.addMatchingKeys(\n txn,\n change.addedDocuments,\n targetId\n );\n })\n );\n\n const resumeToken = change.resumeToken;\n // Update the resume token if the change includes one.\n if (resumeToken.approximateByteSize() > 0) {\n const newTargetData = oldTargetData\n .withResumeToken(resumeToken, remoteVersion)\n .withSequenceNumber(txn.currentSequenceNumber);\n newTargetDataByTargetMap = newTargetDataByTargetMap.insert(\n targetId,\n newTargetData\n );\n\n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n if (\n LocalStore.shouldPersistTargetData(\n oldTargetData,\n newTargetData,\n change\n )\n ) {\n promises.push(\n this.targetCache.updateTargetData(txn, newTargetData)\n );\n }\n }\n }\n );\n\n let changedDocs = maybeDocumentMap();\n let updatedKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach((key, doc) => {\n updatedKeys = updatedKeys.add(key);\n });\n\n // Each loop iteration only affects its \"own\" doc, so it's safe to get all the remote\n // documents in advance in a single call.\n promises.push(\n documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => {\n remoteEvent.documentUpdates.forEach((key, doc) => {\n const existingDoc = existingDocs.get(key);\n\n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.MIN) never add documents to\n // cache.\n if (\n doc instanceof NoDocument &&\n doc.version.isEqual(SnapshotVersion.MIN)\n ) {\n // NoDocuments with SnapshotVersion.MIN are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n documentBuffer.removeEntry(key, remoteVersion);\n changedDocs = changedDocs.insert(key, doc);\n } else if (\n existingDoc == null ||\n doc.version.compareTo(existingDoc.version) > 0 ||\n (doc.version.compareTo(existingDoc.version) === 0 &&\n existingDoc.hasPendingWrites)\n ) {\n assert(\n !SnapshotVersion.MIN.isEqual(remoteVersion),\n 'Cannot add a document when the remote version is zero'\n );\n documentBuffer.addEntry(doc, remoteVersion);\n changedDocs = changedDocs.insert(key, doc);\n } else {\n log.debug(\n LOG_TAG,\n 'Ignoring outdated watch update for ',\n key,\n '. Current version:',\n existingDoc.version,\n ' Watch version:',\n doc.version\n );\n }\n\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(\n this.persistence.referenceDelegate.updateLimboDocument(\n txn,\n key\n )\n );\n }\n });\n })\n );\n\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (!remoteVersion.isEqual(SnapshotVersion.MIN)) {\n const updateRemoteVersion = this.targetCache\n .getLastRemoteSnapshotVersion(txn)\n .next(lastRemoteSnapshotVersion => {\n assert(\n remoteVersion.compareTo(lastRemoteSnapshotVersion) >= 0,\n 'Watch stream reverted to previous snapshot?? ' +\n remoteVersion +\n ' < ' +\n lastRemoteSnapshotVersion\n );\n return this.targetCache.setTargetsMetadata(\n txn,\n txn.currentSequenceNumber,\n remoteVersion\n );\n });\n promises.push(updateRemoteVersion);\n }\n\n return PersistencePromise.waitFor(promises)\n .next(() => documentBuffer.apply(txn))\n .next(() => {\n return this.localDocuments.getLocalViewOfDocuments(\n txn,\n changedDocs\n );\n });\n })\n .then(changedDocs => {\n this.targetDataByTarget = newTargetDataByTargetMap;\n return changedDocs;\n });\n }\n\n /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n private static shouldPersistTargetData(\n oldTargetData: TargetData,\n newTargetData: TargetData,\n change: TargetChange\n ): boolean {\n assert(\n newTargetData.resumeToken.approximateByteSize() > 0,\n 'Attempted to persist target data with no resume token'\n );\n\n // Always persist target data if we don't already have a resume token.\n if (oldTargetData.resumeToken.approximateByteSize() === 0) {\n return true;\n }\n\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n const timeDelta =\n newTargetData.snapshotVersion.toMicroseconds() -\n oldTargetData.snapshotVersion.toMicroseconds();\n if (timeDelta >= this.RESUME_TOKEN_MAX_AGE_MICROS) {\n return true;\n }\n\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n const changes =\n change.addedDocuments.size +\n change.modifiedDocuments.size +\n change.removedDocuments.size;\n return changes > 0;\n }\n\n /**\n * Notify local store of the changed views to locally pin documents.\n */\n notifyLocalViewChanges(viewChanges: LocalViewChanges[]): Promise<void> {\n for (const viewChange of viewChanges) {\n const targetId = viewChange.targetId;\n\n this.localViewReferences.addReferences(viewChange.addedKeys, targetId);\n this.localViewReferences.removeReferences(\n viewChange.removedKeys,\n targetId\n );\n\n if (!viewChange.fromCache) {\n const targetData = this.targetDataByTarget.get(targetId);\n assert(\n targetData !== null,\n `Can't set limbo-free snapshot version for unknown target: ${targetId}`\n );\n\n // Advance the last limbo free snapshot version\n const lastLimboFreeSnapshotVersion = targetData.snapshotVersion;\n const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(\n lastLimboFreeSnapshotVersion\n );\n this.targetDataByTarget = this.targetDataByTarget.insert(\n targetId,\n updatedTargetData\n );\n }\n }\n return this.persistence.runTransaction(\n 'notifyLocalViewChanges',\n 'readwrite',\n txn => {\n return PersistencePromise.forEach(\n viewChanges,\n (viewChange: LocalViewChanges) => {\n return PersistencePromise.forEach(\n viewChange.removedKeys,\n (key: DocumentKey) =>\n this.persistence.referenceDelegate.removeReference(txn, key)\n );\n }\n );\n }\n );\n }\n\n /**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\n nextMutationBatch(afterBatchId?: BatchId): Promise<MutationBatch | null> {\n return this.persistence.runTransaction(\n 'Get next mutation batch',\n 'readonly',\n txn => {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n return this.mutationQueue.getNextMutationBatchAfterBatchId(\n txn,\n afterBatchId\n );\n }\n );\n }\n\n /**\n * Read the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n readDocument(key: DocumentKey): Promise<MaybeDocument | null> {\n return this.persistence.runTransaction('read document', 'readonly', txn => {\n return this.localDocuments.getDocument(txn, key);\n });\n }\n\n /**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\n allocateTarget(target: Target): Promise<TargetData> {\n return this.persistence\n .runTransaction('Allocate target', 'readwrite', txn => {\n let targetData: TargetData;\n return this.targetCache\n .getTargetData(txn, target)\n .next((cached: TargetData | null) => {\n if (cached) {\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n targetData = cached;\n return PersistencePromise.resolve(targetData);\n } else {\n return this.targetCache.allocateTargetId(txn).next(targetId => {\n targetData = new TargetData(\n target,\n targetId,\n TargetPurpose.Listen,\n txn.currentSequenceNumber\n );\n return this.targetCache\n .addTargetData(txn, targetData)\n .next(() => targetData);\n });\n }\n });\n })\n .then(targetData => {\n if (this.targetDataByTarget.get(targetData.targetId) === null) {\n this.targetDataByTarget = this.targetDataByTarget.insert(\n targetData.targetId,\n targetData\n );\n this.targetIdByTarget.set(target, targetData.targetId);\n }\n return targetData;\n });\n }\n\n /**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n // Visible for testing.\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\n const targetId = this.targetIdByTarget.get(target);\n if (targetId !== undefined) {\n return PersistencePromise.resolve<TargetData | null>(\n this.targetDataByTarget.get(targetId)\n );\n } else {\n return this.targetCache.getTargetData(transaction, target);\n }\n }\n\n /**\n * Unpin all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n // PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\n releaseTarget(\n targetId: number,\n keepPersistedTargetData: boolean\n ): Promise<void> {\n const targetData = this.targetDataByTarget.get(targetId);\n assert(\n targetData !== null,\n `Tried to release nonexistent target: ${targetId}`\n );\n\n const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary';\n return this.persistence\n .runTransaction('Release target', mode, txn => {\n // References for documents sent via Watch are automatically removed\n // when we delete a target's data from the reference delegate.\n // Since this does not remove references for locally mutated documents,\n // we have to remove the target associations for these documents\n // manually.\n // This operation needs to be run inside the transaction since EagerGC\n // uses the local view references during the transaction's commit.\n // Fortunately, the operation is safe to be re-run in case the\n // transaction fails since there are no side effects if the target has\n // already been removed.\n const removed = this.localViewReferences.removeReferencesForId(\n targetId\n );\n\n if (!keepPersistedTargetData) {\n return PersistencePromise.forEach(removed, (key: DocumentKey) =>\n this.persistence.referenceDelegate.removeReference(txn, key)\n ).next(() => {\n this.persistence.referenceDelegate.removeTarget(txn, targetData!);\n });\n } else {\n return PersistencePromise.resolve();\n }\n })\n .then(() => {\n this.targetDataByTarget = this.targetDataByTarget.remove(targetId);\n this.targetIdByTarget.delete(targetData!.target);\n });\n }\n\n /**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults Whether results from previous executions can\n * be used to optimize this query execution.\n */\n executeQuery(\n query: Query,\n usePreviousResults: boolean\n ): Promise<QueryResult> {\n let lastLimboFreeSnapshotVersion = SnapshotVersion.MIN;\n let remoteKeys = documentKeySet();\n\n return this.persistence.runTransaction('Execute query', 'readonly', txn => {\n return this.getTargetData(txn, query.toTarget())\n .next(targetData => {\n if (targetData) {\n lastLimboFreeSnapshotVersion =\n targetData.lastLimboFreeSnapshotVersion;\n return this.targetCache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(result => {\n remoteKeys = result;\n });\n }\n })\n .next(() =>\n this.queryEngine.getDocumentsMatchingQuery(\n txn,\n query,\n usePreviousResults\n ? lastLimboFreeSnapshotVersion\n : SnapshotVersion.MIN,\n usePreviousResults ? remoteKeys : documentKeySet()\n )\n )\n .next(documents => {\n return { documents, remoteKeys };\n });\n });\n }\n\n /**\n * Returns the keys of the documents that are associated with the given\n * target id in the remote table.\n */\n remoteDocumentKeys(targetId: TargetId): Promise<DocumentKeySet> {\n return this.persistence.runTransaction(\n 'Remote document keys',\n 'readonly',\n txn => {\n return this.targetCache.getMatchingKeysForTargetId(txn, targetId);\n }\n );\n }\n\n // PORTING NOTE: Multi-tab only.\n getActiveClients(): Promise<ClientId[]> {\n return this.persistence.getActiveClients();\n }\n\n // PORTING NOTE: Multi-tab only.\n removeCachedMutationBatchMetadata(batchId: BatchId): void {\n this.mutationQueue.removeCachedMutationKeys(batchId);\n }\n\n // PORTING NOTE: Multi-tab only.\n setNetworkEnabled(networkEnabled: boolean): void {\n this.persistence.setNetworkEnabled(networkEnabled);\n }\n\n private applyWriteToRemoteDocuments(\n txn: PersistenceTransaction,\n batchResult: MutationBatchResult,\n documentBuffer: RemoteDocumentChangeBuffer\n ): PersistencePromise<void> {\n const batch = batchResult.batch;\n const docKeys = batch.keys();\n let promiseChain = PersistencePromise.resolve();\n docKeys.forEach(docKey => {\n promiseChain = promiseChain\n .next(() => {\n return documentBuffer.getEntry(txn, docKey);\n })\n .next((remoteDoc: MaybeDocument | null) => {\n let doc = remoteDoc;\n const ackVersion = batchResult.docVersions.get(docKey);\n assert(\n ackVersion !== null,\n 'ackVersions should contain every doc in the write.'\n );\n if (!doc || doc.version.compareTo(ackVersion!) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n if (!doc) {\n assert(\n !remoteDoc,\n 'Mutation batch ' +\n batch +\n ' applied to document ' +\n remoteDoc +\n ' resulted in null'\n );\n } else {\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n documentBuffer.addEntry(doc, batchResult.commitVersion);\n }\n }\n });\n });\n return promiseChain.next(() =>\n this.mutationQueue.removeMutationBatch(txn, batch)\n );\n }\n\n collectGarbage(garbageCollector: LruGarbageCollector): Promise<LruResults> {\n return this.persistence.runTransaction(\n 'Collect garbage',\n 'readwrite-primary',\n txn => garbageCollector.collect(txn, this.targetDataByTarget)\n );\n }\n\n // PORTING NOTE: Multi-tab only.\n getTarget(targetId: TargetId): Promise<Target | null> {\n const cachedTargetData = this.targetDataByTarget.get(targetId);\n\n if (cachedTargetData) {\n return Promise.resolve(cachedTargetData.target);\n } else {\n return this.persistence.runTransaction(\n 'Get target data',\n 'readonly',\n txn => {\n return this.targetCache\n .getTargetDataForTarget(txn, targetId)\n .next(targetData => (targetData ? targetData.target : null));\n }\n );\n }\n }\n\n /**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document changes since\n * the point of rejection.\n */\n // PORTING NOTE: Multi-tab only.\n getNewDocumentChanges(): Promise<MaybeDocumentMap> {\n return this.persistence\n .runTransaction('Get new document changes', 'readonly', txn =>\n this.remoteDocuments.getNewDocumentChanges(\n txn,\n this.lastDocumentChangeReadTime\n )\n )\n .then(({ changedDocs, readTime }) => {\n this.lastDocumentChangeReadTime = readTime;\n return changedDocs;\n });\n }\n\n /**\n * Reads the newest document change from persistence and forwards the internal\n * synchronization marker so that calls to `getNewDocumentChanges()`\n * only return changes that happened after client initialization.\n */\n // PORTING NOTE: Multi-tab only.\n async synchronizeLastDocumentChangeReadTime(): Promise<void> {\n this.lastDocumentChangeReadTime = await this.persistence.runTransaction(\n 'Synchronize last document change read time',\n 'readonly',\n txn => this.remoteDocuments.getLastReadTime(txn)\n );\n }\n}\n\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err An error returned by a LocalStore operation.\n * @return A Promise that resolves after we recovered, or the original error.\n */\nexport async function ignoreIfPrimaryLeaseLoss(\n err: FirestoreError\n): Promise<void> {\n if (\n err.code === Code.FAILED_PRECONDITION &&\n err.message === PRIMARY_LEASE_LOST_ERROR_MSG\n ) {\n log.debug(LOG_TAG, 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { QueryTargetState } from './shared_client_state_syncer';\nimport { assert } from '../util/assert';\nimport { ClientId } from './shared_client_state';\nimport { User } from '../auth/user';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients_<persistence_prefix>_<instance_key>\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n assert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations_<persistence_prefix>_<batch_id>\n// (for unauthenticated users)\n// or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets_<persistence_prefix>_<target_id>\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_<persistence_prefix>\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_<persistence_prefix>'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { Platform } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { debug, error } from '../util/log';\nimport * as objUtils from '../util/obj';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger } from '../util/types';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n syncEngine: SharedClientStateSyncer | null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(targetId: TargetId): QueryTargetState;\n\n /** Removes the Query Target ID association from the local client. */\n removeLocalQueryTarget(targetId: TargetId): void;\n\n /** Checks whether the target is associated with the local client. */\n isLocalQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Processes an update to a query target.\n *\n * Called by the primary client to notify secondary clients of document\n * changes or state transitions that affect the provided query target.\n */\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void;\n\n /**\n * Removes the target's metadata entry.\n *\n * Called by the primary client when all clients stopped listening to a query\n * target.\n */\n clearQueryState(targetId: TargetId): void;\n\n /**\n * Gets the active Query Targets IDs for all active clients.\n *\n * The implementation for this may require O(n) runtime, where 'n' is the size\n * of the result set.\n */\n // Visible for testing\n getAllActiveQueryTargets(): SortedSet<TargetId>;\n\n /**\n * Checks whether the provided target ID is currently being listened to by\n * any of the active clients.\n *\n * The implementation may require O(n*log m) runtime, where 'n' is the number\n * of clients and 'm' the number of targets.\n */\n isActiveQueryTarget(targetId: TargetId): boolean;\n\n /**\n * Starts the SharedClientState, reads existing client data and registers\n * listeners for updates to new and existing clients.\n */\n start(): Promise<void>;\n\n /** Shuts down the `SharedClientState` and its listeners. */\n shutdown(): void;\n\n /**\n * Changes the active user and removes all existing user-specific data. The\n * user change does not call back into SyncEngine (for example, no mutations\n * will be marked as removed).\n */\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void;\n\n /** Changes the shared online state of all clients. */\n setOnlineState(onlineState: OnlineState): void;\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n}\n\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nexport class MutationMetadata {\n constructor(\n readonly user: User,\n readonly batchId: BatchId,\n readonly state: MutationBatchState,\n readonly error?: FirestoreError\n ) {\n assert(\n (error !== undefined) === (state === 'rejected'),\n `MutationMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n user: User,\n batchId: BatchId,\n value: string\n ): MutationMetadata | null {\n const mutationBatch = JSON.parse(value) as MutationMetadataSchema;\n\n let validData =\n typeof mutationBatch === 'object' &&\n ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !==\n -1 &&\n (mutationBatch.error === undefined ||\n typeof mutationBatch.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && mutationBatch.error) {\n validData =\n typeof mutationBatch.error.message === 'string' &&\n typeof mutationBatch.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n mutationBatch.error.code as Code,\n mutationBatch.error.message\n );\n }\n }\n\n if (validData) {\n return new MutationMetadata(\n user,\n batchId,\n mutationBatch.state,\n firestoreError\n );\n } else {\n error(\n LOG_TAG,\n `Failed to parse mutation state for ID '${batchId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const batchMetadata: MutationMetadataSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n batchMetadata.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(batchMetadata);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nexport class QueryTargetMetadata {\n constructor(\n readonly targetId: TargetId,\n readonly state: QueryTargetState,\n readonly error?: FirestoreError\n ) {\n assert(\n (error !== undefined) === (state === 'rejected'),\n `QueryTargetMetadata must contain an error iff state is 'rejected'`\n );\n }\n\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n targetId: TargetId,\n value: string\n ): QueryTargetMetadata | null {\n const targetState = JSON.parse(value) as QueryTargetStateSchema;\n\n let validData =\n typeof targetState === 'object' &&\n ['not-current', 'current', 'rejected'].indexOf(targetState.state) !==\n -1 &&\n (targetState.error === undefined ||\n typeof targetState.error === 'object');\n\n let firestoreError: FirestoreError | undefined = undefined;\n\n if (validData && targetState.error) {\n validData =\n typeof targetState.error.message === 'string' &&\n typeof targetState.error.code === 'string';\n if (validData) {\n firestoreError = new FirestoreError(\n targetState.error.code as Code,\n targetState.error.message\n );\n }\n }\n\n if (validData) {\n return new QueryTargetMetadata(\n targetId,\n targetState.state,\n firestoreError\n );\n } else {\n error(\n LOG_TAG,\n `Failed to parse target state for ID '${targetId}': ${value}`\n );\n return null;\n }\n }\n\n toWebStorageJSON(): string {\n const targetState: QueryTargetStateSchema = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n\n if (this.error) {\n targetState.error = {\n code: this.error.code,\n message: this.error.message\n };\n }\n\n return JSON.stringify(targetState);\n }\n}\n\n/**\n * Metadata state of a single client denoting the query targets it is actively\n * listening to.\n */\n// Visible for testing.\nexport interface ClientState {\n readonly activeTargetIds: TargetIdSet;\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */\nclass RemoteClientState implements ClientState {\n private constructor(\n readonly clientId: ClientId,\n readonly activeTargetIds: TargetIdSet\n ) {}\n\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(\n clientId: ClientId,\n value: string\n ): RemoteClientState | null {\n const clientState = JSON.parse(value) as ClientStateSchema;\n\n let validData =\n typeof clientState === 'object' &&\n clientState.activeTargetIds instanceof Array;\n\n let activeTargetIdsSet = targetIdSet();\n\n for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\n validData = isSafeInteger(clientState.activeTargetIds[i]);\n activeTargetIdsSet = activeTargetIdsSet.add(\n clientState.activeTargetIds[i]\n );\n }\n\n if (validData) {\n return new RemoteClientState(clientId, activeTargetIdsSet);\n } else {\n error(\n LOG_TAG,\n `Failed to parse client data for instance '${clientId}': ${value}`\n );\n return null;\n }\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */\nexport class SharedOnlineState {\n constructor(readonly clientId: string, readonly onlineState: OnlineState) {}\n\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */\n static fromWebStorageEntry(value: string): SharedOnlineState | null {\n const onlineState = JSON.parse(value) as SharedOnlineStateSchema;\n\n const validData =\n typeof onlineState === 'object' &&\n ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !==\n -1 &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n onlineState.onlineState as OnlineState\n );\n } else {\n error(LOG_TAG, `Failed to parse online state: ${value}`);\n return null;\n }\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nexport class LocalClientState implements ClientState {\n activeTargetIds = targetIdSet();\n\n addQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.add(targetId);\n }\n\n removeQueryTarget(targetId: TargetId): void {\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\n }\n\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */\n toWebStorageJSON(): string {\n const data: ClientStateSchema = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n };\n return JSON.stringify(data);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */\nexport class WebStorageSharedClientState implements SharedClientState {\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n private readonly storage: Storage;\n private readonly localClientStorageKey: string;\n private readonly sequenceNumberKey: string;\n private readonly activeClients: { [key: string]: ClientState } = {};\n private readonly storageListener = this.handleWebStorageEvent.bind(this);\n private readonly onlineStateKey: string;\n private readonly clientStateKeyRe: RegExp;\n private readonly mutationBatchKeyRe: RegExp;\n private readonly queryTargetKeyRe: RegExp;\n private started = false;\n private currentUser: User;\n\n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n private earlyEvents: StorageEvent[] = [];\n\n constructor(\n private readonly queue: AsyncQueue,\n private readonly platform: Platform,\n private readonly persistenceKey: string,\n private readonly localClientId: ClientId,\n initialUser: User\n ) {\n if (!WebStorageSharedClientState.isAvailable(this.platform)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'LocalStorage is not available on this platform.'\n );\n }\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const escapedPersistenceKey = persistenceKey.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&'\n );\n\n this.storage = this.platform.window!.localStorage;\n this.currentUser = initialUser;\n this.localClientStorageKey = createWebStorageClientStateKey(\n this.persistenceKey,\n this.localClientId\n );\n this.sequenceNumberKey = createWebStorageSequenceNumberKey(\n this.persistenceKey\n );\n this.activeClients[this.localClientId] = new LocalClientState();\n\n this.clientStateKeyRe = new RegExp(\n `^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`\n );\n this.mutationBatchKeyRe = new RegExp(\n `^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)(?:_(.*))?$`\n );\n this.queryTargetKeyRe = new RegExp(\n `^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\\\d+)$`\n );\n\n this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey);\n\n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.platform.window!.addEventListener('storage', this.storageListener);\n }\n\n /** Returns 'true' if WebStorage is available in the current environment. */\n static isAvailable(platform: Platform): boolean {\n return !!(platform.window && platform.window.localStorage != null);\n }\n\n async start(): Promise<void> {\n assert(!this.started, 'WebStorageSharedClientState already started');\n assert(\n this.syncEngine !== null,\n 'syncEngine property must be set before calling start()'\n );\n assert(\n this.onlineStateHandler !== null,\n 'onlineStateHandler property must be set before calling start()'\n );\n\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const existingClients = await this.syncEngine!.getActiveClients();\n\n for (const clientId of existingClients) {\n if (clientId === this.localClientId) {\n continue;\n }\n\n const storageItem = this.getItem(\n createWebStorageClientStateKey(this.persistenceKey, clientId)\n );\n if (storageItem) {\n const clientState = RemoteClientState.fromWebStorageEntry(\n clientId,\n storageItem\n );\n if (clientState) {\n this.activeClients[clientState.clientId] = clientState;\n }\n }\n }\n\n this.persistClientState();\n\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n if (onlineStateJSON) {\n const onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n if (onlineState) {\n this.handleOnlineStateEvent(onlineState);\n }\n }\n\n for (const event of this.earlyEvents) {\n this.handleWebStorageEvent(event);\n }\n\n this.earlyEvents = [];\n\n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.platform.window!.addEventListener('unload', () => this.shutdown());\n\n this.started = true;\n }\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n let activeTargets = targetIdSet();\n objUtils.forEach(this.activeClients, (key, value) => {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n // This is not using `obj.forEach` since `forEach` doesn't support early\n // return.\n for (const clientId in this.activeClients) {\n if (this.activeClients.hasOwnProperty(clientId)) {\n if (this.activeClients[clientId].activeTargetIds.has(targetId)) {\n return true;\n }\n }\n }\n return false;\n }\n\n addPendingMutation(batchId: BatchId): void {\n this.persistMutationState(batchId, 'pending');\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n this.persistMutationState(batchId, state, error);\n\n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.removeMutationState(batchId);\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n let queryState: QueryTargetState = 'not-current';\n\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(targetId)) {\n const storageItem = this.storage.getItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n\n if (storageItem) {\n const metadata = QueryTargetMetadata.fromWebStorageEntry(\n targetId,\n storageItem\n );\n if (metadata) {\n queryState = metadata.state;\n }\n }\n }\n\n this.localClientState.addQueryTarget(targetId);\n this.persistClientState();\n\n return queryState;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localClientState.removeQueryTarget(targetId);\n this.persistClientState();\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localClientState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n this.removeItem(\n createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)\n );\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.persistQueryTargetState(targetId, state, error);\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n removedBatchIds.forEach(batchId => {\n this.removeMutationState(batchId);\n });\n this.currentUser = user;\n addedBatchIds.forEach(batchId => {\n this.addPendingMutation(batchId);\n });\n }\n\n setOnlineState(onlineState: OnlineState): void {\n this.persistOnlineState(onlineState);\n }\n\n shutdown(): void {\n if (this.started) {\n this.platform.window!.removeEventListener(\n 'storage',\n this.storageListener\n );\n this.removeItem(this.localClientStorageKey);\n this.started = false;\n }\n }\n\n private getItem(key: string): string | null {\n const value = this.storage.getItem(key);\n debug(LOG_TAG, 'READ', key, value);\n return value;\n }\n\n private setItem(key: string, value: string): void {\n debug(LOG_TAG, 'SET', key, value);\n this.storage.setItem(key, value);\n }\n\n private removeItem(key: string): void {\n debug(LOG_TAG, 'REMOVE', key);\n this.storage.removeItem(key);\n }\n\n private handleWebStorageEvent(event: StorageEvent): void {\n if (event.storageArea === this.storage) {\n debug(LOG_TAG, 'EVENT', event.key, event.newValue);\n\n if (event.key === this.localClientStorageKey) {\n error(\n 'Received WebStorage notification for local change. Another client might have ' +\n 'garbage-collected our state'\n );\n return;\n }\n\n this.queue.enqueueAndForget(async () => {\n if (!this.started) {\n this.earlyEvents.push(event);\n return;\n }\n\n if (event.key === null) {\n return;\n }\n\n if (this.clientStateKeyRe.test(event.key)) {\n if (event.newValue != null) {\n const clientState = this.fromWebStorageClientState(\n event.key,\n event.newValue\n );\n if (clientState) {\n return this.handleClientStateEvent(\n clientState.clientId,\n clientState\n );\n }\n } else {\n const clientId = this.fromWebStorageClientStateKey(event.key)!;\n return this.handleClientStateEvent(clientId, null);\n }\n } else if (this.mutationBatchKeyRe.test(event.key)) {\n if (event.newValue !== null) {\n const mutationMetadata = this.fromWebStorageMutationMetadata(\n event.key,\n event.newValue\n );\n if (mutationMetadata) {\n return this.handleMutationBatchEvent(mutationMetadata);\n }\n }\n } else if (this.queryTargetKeyRe.test(event.key)) {\n if (event.newValue !== null) {\n const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(\n event.key,\n event.newValue\n );\n if (queryTargetMetadata) {\n return this.handleQueryTargetEvent(queryTargetMetadata);\n }\n }\n } else if (event.key === this.onlineStateKey) {\n if (event.newValue !== null) {\n const onlineState = this.fromWebStorageOnlineState(event.newValue);\n if (onlineState) {\n return this.handleOnlineStateEvent(onlineState);\n }\n }\n } else if (event.key === this.sequenceNumberKey) {\n assert(!!this.sequenceNumberHandler, 'Missing sequenceNumberHandler');\n const sequenceNumber = fromWebStorageSequenceNumber(event.newValue);\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler!(sequenceNumber);\n }\n }\n });\n }\n }\n\n private get localClientState(): LocalClientState {\n return this.activeClients[this.localClientId] as LocalClientState;\n }\n\n private persistClientState(): void {\n this.setItem(\n this.localClientStorageKey,\n this.localClientState.toWebStorageJSON()\n );\n }\n\n private persistMutationState(\n batchId: BatchId,\n state: MutationBatchState,\n error?: FirestoreError\n ): void {\n const mutationState = new MutationMetadata(\n this.currentUser,\n batchId,\n state,\n error\n );\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n }\n\n private removeMutationState(batchId: BatchId): void {\n const mutationKey = createWebStorageMutationBatchKey(\n this.persistenceKey,\n this.currentUser,\n batchId\n );\n this.removeItem(mutationKey);\n }\n\n private persistOnlineState(onlineState: OnlineState): void {\n const entry: SharedOnlineStateSchema = {\n clientId: this.localClientId,\n onlineState\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n }\n\n private persistQueryTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n const targetKey = createWebStorageQueryTargetMetadataKey(\n this.persistenceKey,\n targetId\n );\n const targetMetadata = new QueryTargetMetadata(targetId, state, error);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n }\n\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */\n private fromWebStorageClientStateKey(key: string): ClientId | null {\n const match = this.clientStateKeyRe.exec(key);\n return match ? match[1] : null;\n }\n\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */\n private fromWebStorageClientState(\n key: string,\n value: string\n ): RemoteClientState | null {\n const clientId = this.fromWebStorageClientStateKey(key);\n assert(clientId !== null, `Cannot parse client state key '${key}'`);\n return RemoteClientState.fromWebStorageEntry(clientId, value);\n }\n\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageMutationMetadata(\n key: string,\n value: string\n ): MutationMetadata | null {\n const match = this.mutationBatchKeyRe.exec(key);\n assert(match !== null, `Cannot parse mutation batch key '${key}'`);\n\n const batchId = Number(match[1]);\n const userId = match[2] !== undefined ? match[2] : null;\n return MutationMetadata.fromWebStorageEntry(\n new User(userId),\n batchId,\n value\n );\n }\n\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageQueryTargetMetadata(\n key: string,\n value: string\n ): QueryTargetMetadata | null {\n const match = this.queryTargetKeyRe.exec(key);\n assert(match !== null, `Cannot parse query target key '${key}'`);\n\n const targetId = Number(match[1]);\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n }\n\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */\n private fromWebStorageOnlineState(value: string): SharedOnlineState | null {\n return SharedOnlineState.fromWebStorageEntry(value);\n }\n\n private async handleMutationBatchEvent(\n mutationBatch: MutationMetadata\n ): Promise<void> {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n debug(\n LOG_TAG,\n `Ignoring mutation for non-active user ${mutationBatch.user.uid}`\n );\n return;\n }\n\n return this.syncEngine!.applyBatchState(\n mutationBatch.batchId,\n mutationBatch.state,\n mutationBatch.error\n );\n }\n\n private handleQueryTargetEvent(\n targetMetadata: QueryTargetMetadata\n ): Promise<void> {\n return this.syncEngine!.applyTargetState(\n targetMetadata.targetId,\n targetMetadata.state,\n targetMetadata.error\n );\n }\n\n private handleClientStateEvent(\n clientId: ClientId,\n clientState: RemoteClientState | null\n ): Promise<void> {\n const existingTargets = this.getAllActiveQueryTargets();\n\n if (clientState) {\n this.activeClients[clientId] = clientState;\n } else {\n delete this.activeClients[clientId];\n }\n\n const newTargets = this.getAllActiveQueryTargets();\n\n const addedTargets: TargetId[] = [];\n const removedTargets: TargetId[] = [];\n\n newTargets.forEach(async targetId => {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n });\n\n existingTargets.forEach(async targetId => {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n });\n\n return this.syncEngine!.applyActiveTargetsChange(\n addedTargets,\n removedTargets\n );\n }\n\n private handleOnlineStateEvent(onlineState: SharedOnlineState): void {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n if (this.activeClients[onlineState.clientId]) {\n this.onlineStateHandler!(onlineState.onlineState);\n }\n }\n}\n\nfunction fromWebStorageSequenceNumber(\n seqString: string | null\n): ListenSequenceNumber {\n let sequenceNumber = ListenSequence.INVALID;\n if (seqString != null) {\n try {\n const parsed = JSON.parse(seqString);\n assert(typeof parsed === 'number', 'Found non-numeric sequence number');\n sequenceNumber = parsed;\n } catch (e) {\n error(LOG_TAG, 'Failed to read sequence number from WebStorage', e);\n }\n }\n return sequenceNumber;\n}\n\n/**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */\nexport class MemorySharedClientState implements SharedClientState {\n private localState = new LocalClientState();\n private queryState: { [targetId: number]: QueryTargetState } = {};\n\n syncEngine: SharedClientStateSyncer | null = null;\n onlineStateHandler: ((onlineState: OnlineState) => void) | null = null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null = null;\n\n addPendingMutation(batchId: BatchId): void {\n // No op.\n }\n\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void {\n // No op.\n }\n\n addLocalQueryTarget(targetId: TargetId): QueryTargetState {\n this.localState.addQueryTarget(targetId);\n return this.queryState[targetId] || 'not-current';\n }\n\n updateQueryState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): void {\n this.queryState[targetId] = state;\n }\n\n removeLocalQueryTarget(targetId: TargetId): void {\n this.localState.removeQueryTarget(targetId);\n }\n\n isLocalQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n clearQueryState(targetId: TargetId): void {\n delete this.queryState[targetId];\n }\n\n getAllActiveQueryTargets(): TargetIdSet {\n return this.localState.activeTargetIds;\n }\n\n isActiveQueryTarget(targetId: TargetId): boolean {\n return this.localState.activeTargetIds.has(targetId);\n }\n\n start(): Promise<void> {\n this.localState = new LocalClientState();\n return Promise.resolve();\n }\n\n handleUserChange(\n user: User,\n removedBatchIds: BatchId[],\n addedBatchIds: BatchId[]\n ): void {\n // No op.\n }\n\n setOnlineState(onlineState: OnlineState): void {\n // No op.\n }\n\n shutdown(): void {}\n\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { User } from '../auth/user';\n\nimport { ListenSequenceNumber } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexManager } from './index_manager';\nimport { LocalStore } from './local_store';\nimport { MutationQueue } from './mutation_queue';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetCache } from './target_cache';\nimport { ReferenceSet } from './reference_set';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { ClientId, SharedClientState } from './shared_client_state';\nimport { TargetData } from './target_data';\nimport { DatabaseInfo } from '../core/database_info';\nimport { PersistenceSettings } from '../core/firestore_client';\nimport { Platform } from '../platform/platform';\nimport { AsyncQueue } from '../util/async_queue';\n\nexport const PRIMARY_LEASE_LOST_ERROR_MSG =\n 'The current tab is not in the required state to perform this operation. ' +\n 'It might be necessary to refresh the browser tab.';\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */\nexport abstract class PersistenceTransaction {\n private readonly onCommittedListeners: Array<() => void> = [];\n\n abstract readonly currentSequenceNumber: ListenSequenceNumber;\n\n addOnCommittedListener(listener: () => void): void {\n this.onCommittedListeners.push(listener);\n }\n\n raiseOnCommittedEvent(): void {\n this.onCommittedListeners.forEach(listener => listener());\n }\n}\n\n/** The different modes supported by `IndexedDbPersistence.runTransaction()`. */\nexport type PersistenceTransactionMode =\n | 'readonly'\n | 'readwrite'\n | 'readwrite-primary';\n\n/**\n * Callback type for primary state notifications. This callback can be\n * registered with the persistence layer to get notified when we transition from\n * primary to secondary state and vice versa.\n *\n * Note: Instances can only toggle between Primary and Secondary state if\n * IndexedDB persistence is enabled and multiple clients are active. If this\n * listener is registered with MemoryPersistence, the callback will be called\n * exactly once marking the current instance as Primary.\n */\nexport type PrimaryStateListener = (isPrimary: boolean) => Promise<void>;\n\n/**\n * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This\n * includes being added to a target, being removed from a target, being subject to mutation, and\n * being mutated by the user.\n *\n * Different implementations may do different things with each of these events. Not every\n * implementation needs to do something with every lifecycle hook.\n *\n * PORTING NOTE: since sequence numbers are attached to transactions in this\n * client, the ReferenceDelegate does not need to deal in transactional\n * semantics (onTransactionStarted/Committed()), nor does it need to track and\n * generate sequence numbers (getCurrentSequenceNumber()).\n */\nexport interface ReferenceDelegate {\n /**\n * Registers a ReferenceSet of documents that should be considered 'referenced' and not eligible\n * for removal during garbage collection.\n */\n setInMemoryPins(pins: ReferenceSet): void;\n\n /** Notify the delegate that the given document was added to a target. */\n addReference(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n\n /** Notify the delegate that the given document was removed from a target. */\n removeReference(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n\n /**\n * Notify the delegate that a target was removed. The delegate may, but is not obligated to,\n * actually delete the target and associated data.\n */\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void>;\n\n /** Notify the delegate that a document is no longer being mutated by the user. */\n removeMutationReference(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n\n /** Notify the delegate that a limbo document was updated. */\n updateLimboDocument(\n txn: PersistenceTransaction,\n doc: DocumentKey\n ): PersistencePromise<void>;\n}\n\n/**\n * Persistence is the lowest-level shared interface to persistent storage in\n * Firestore.\n *\n * Persistence is used to create MutationQueue and RemoteDocumentCache\n * instances backed by persistence (which might be in-memory or LevelDB).\n *\n * Persistence also exposes an API to create and run PersistenceTransactions\n * against persistence. All read / write operations must be wrapped in a\n * transaction. Implementations of PersistenceTransaction / Persistence only\n * need to guarantee that writes made against the transaction are not made to\n * durable storage until the transaction resolves its PersistencePromise.\n * Since memory-only storage components do not alter durable storage, they are\n * free to ignore the transaction.\n *\n * This contract is enough to allow the LocalStore be be written\n * independently of whether or not the stored state actually is durably\n * persisted. If persistent storage is enabled, writes are grouped together to\n * avoid inconsistent state that could cause crashes.\n *\n * Concretely, when persistent storage is enabled, the persistent versions of\n * MutationQueue, RemoteDocumentCache, and others (the mutators) will\n * defer their writes into a transaction. Once the local store has completed\n * one logical operation, it commits the transaction.\n *\n * When persistent storage is disabled, the non-persistent versions of the\n * mutators ignore the transaction. This short-cut is allowed because\n * memory-only storage leaves no state so it cannot be inconsistent.\n *\n * This simplifies the implementations of the mutators and allows memory-only\n * implementations to supplement the persistent ones without requiring any\n * special dual-store implementation of Persistence. The cost is that the\n * LocalStore needs to be slightly careful about the order of its reads and\n * writes in order to avoid relying on being able to read back uncommitted\n * writes.\n */\nexport interface Persistence {\n /**\n * Whether or not this persistence instance has been started.\n */\n readonly started: boolean;\n\n readonly referenceDelegate: ReferenceDelegate;\n\n /**\n * Releases any resources held during eager shutdown.\n */\n shutdown(): Promise<void>;\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise<void>;\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise<void>\n ): void;\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void;\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise<ClientId[]>;\n\n /**\n * Returns a MutationQueue representing the persisted mutations for the\n * given user.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called for a given user. In particular, the memory-backed\n * implementation does this to emulate the persisted implementation to the\n * extent possible (e.g. in the case of uid switching from\n * sally=>jack=>sally, sally's mutation queue will be preserved).\n */\n getMutationQueue(user: User): MutationQueue;\n\n /**\n * Returns a TargetCache representing the persisted cache of targets.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called. In particular, the memory-backed implementation does this\n * to emulate the persisted implementation to the extent possible.\n */\n getTargetCache(): TargetCache;\n\n /**\n * Returns a RemoteDocumentCache representing the persisted cache of remote\n * documents.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called. In particular, the memory-backed implementation does this\n * to emulate the persisted implementation to the extent possible.\n */\n getRemoteDocumentCache(): RemoteDocumentCache;\n\n /**\n * Returns an IndexManager instance that manages our persisted query indexes.\n *\n * Note: The implementation is free to return the same instance every time\n * this is called. In particular, the memory-backed implementation does this\n * to emulate the persisted implementation to the extent possible.\n */\n getIndexManager(): IndexManager;\n\n /**\n * Performs an operation inside a persistence transaction. Any reads or writes\n * against persistence must be performed within a transaction. Writes will be\n * committed atomically once the transaction completes.\n *\n * Persistence operations are asynchronous and therefore the provided\n * transactionOperation must return a PersistencePromise. When it is resolved,\n * the transaction will be committed and the Promise returned by this method\n * will resolve.\n *\n * @param action A description of the action performed by this transaction,\n * used for logging.\n * @param mode The underlying mode of the IndexedDb transaction. Can be\n * 'readonly`, 'readwrite' or 'readwrite-primary'. Transactions marked\n * 'readwrite-primary' can only be executed by the primary client. In this\n * mode, the transactionOperation will not be run if the primary lease cannot\n * be acquired and the returned promise will be rejected with a\n * FAILED_PRECONDITION error.\n * @param transactionOperation The operation to run inside a transaction.\n * @return A promise that is resolved once the transaction completes.\n */\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T>;\n}\n\n/**\n * Interface implemented by the LRU scheduler to start(), stop() and restart\n * garbage collection.\n */\nexport interface GarbageCollectionScheduler {\n readonly started: boolean;\n start(localStore: LocalStore): void;\n stop(): void;\n}\n\n/**\n * Provides all persistence components for Firestore. Consumers have to invoke\n * configure() once before accessing any of the individual components.\n */\nexport interface PersistenceProvider {\n initialize(\n asyncQueue: AsyncQueue,\n databaseInfo: DatabaseInfo,\n platform: Platform,\n clientId: ClientId,\n initialUser: User,\n settings: PersistenceSettings\n ): Promise<void>;\n\n getPersistence(): Persistence;\n\n getGarbageCollectionScheduler(): GarbageCollectionScheduler;\n\n getSharedClientState(): SharedClientState;\n\n clearPersistence(databaseId: DatabaseInfo): Promise<void>;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n documentKeySet,\n DocumentMap,\n documentMap,\n MaybeDocumentMap,\n maybeDocumentMap,\n NullableMaybeDocumentMap,\n nullableMaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\n\nimport { assert } from '../util/assert';\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { PatchMutation } from '../model/mutation';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @return Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKey(transaction, key)\n .next(batches => this.getDocumentInternal(transaction, key, batches));\n }\n\n /** Internal version of `getDocument` that allows reusing batches. */\n private getDocumentInternal(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n inBatches: MutationBatch[]\n ): PersistencePromise<MaybeDocument | null> {\n return this.remoteDocumentCache.getEntry(transaction, key).next(doc => {\n for (const batch of inBatches) {\n doc = batch.applyToLocalView(key, doc);\n }\n return doc;\n });\n }\n\n // Returns the view of the given `docs` as they would appear after applying\n // all mutations in the given `batches`.\n private applyLocalMutationsToDocuments(\n transaction: PersistenceTransaction,\n docs: NullableMaybeDocumentMap,\n batches: MutationBatch[]\n ): NullableMaybeDocumentMap {\n let results = nullableMaybeDocumentMap();\n docs.forEach((key, localView) => {\n for (const batch of batches) {\n localView = batch.applyToLocalView(key, localView);\n }\n results = results.insert(key, localView);\n });\n return results;\n }\n\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */\n getDocuments(\n transaction: PersistenceTransaction,\n keys: DocumentKeySet\n ): PersistencePromise<MaybeDocumentMap> {\n return this.remoteDocumentCache\n .getEntries(transaction, keys)\n .next(docs => this.getLocalViewOfDocuments(transaction, docs));\n }\n\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n */\n getLocalViewOfDocuments(\n transaction: PersistenceTransaction,\n baseDocs: NullableMaybeDocumentMap\n ): PersistencePromise<MaybeDocumentMap> {\n return this.mutationQueue\n .getAllMutationBatchesAffectingDocumentKeys(transaction, baseDocs)\n .next(batches => {\n const docs = this.applyLocalMutationsToDocuments(\n transaction,\n baseDocs,\n batches\n );\n let results = maybeDocumentMap();\n docs.forEach((key, maybeDoc) => {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\n }\n results = results.insert(key, maybeDoc);\n });\n\n return results;\n });\n }\n\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction The persistence transaction.\n * @param query The query to match documents against.\n * @param sinceReadTime If not set to SnapshotVersion.MIN, return only\n * documents that have been read since this snapshot version (exclusive).\n */\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n if (query.isDocumentQuery()) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else if (query.isCollectionGroupQuery()) {\n return this.getDocumentsMatchingCollectionGroupQuery(\n transaction,\n query,\n sinceReadTime\n );\n } else {\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n query,\n sinceReadTime\n );\n }\n }\n\n private getDocumentsMatchingDocumentQuery(\n transaction: PersistenceTransaction,\n docPath: ResourcePath\n ): PersistencePromise<DocumentMap> {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(\n maybeDoc => {\n let result = documentMap();\n if (maybeDoc instanceof Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n return result;\n }\n );\n }\n\n private getDocumentsMatchingCollectionGroupQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n assert(\n query.path.isEmpty(),\n 'Currently we only support collection group queries at the root.'\n );\n const collectionId = query.collectionGroup!;\n let results = documentMap();\n return this.indexManager\n .getCollectionParents(transaction, collectionId)\n .next(parents => {\n // Perform a collection query against each parent that contains the\n // collectionId and aggregate the results.\n return PersistencePromise.forEach(parents, (parent: ResourcePath) => {\n const collectionQuery = query.asCollectionQueryAtPath(\n parent.child(collectionId)\n );\n return this.getDocumentsMatchingCollectionQuery(\n transaction,\n collectionQuery,\n sinceReadTime\n ).next(r => {\n r.forEach((key, doc) => {\n results = results.insert(key, doc);\n });\n });\n }).next(() => results);\n });\n }\n\n private getDocumentsMatchingCollectionQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n // Query the remote documents and overlay mutations.\n let results: DocumentMap;\n let mutationBatches: MutationBatch[];\n return this.remoteDocumentCache\n .getDocumentsMatchingQuery(transaction, query, sinceReadTime)\n .next(queryResults => {\n results = queryResults;\n return this.mutationQueue.getAllMutationBatchesAffectingQuery(\n transaction,\n query\n );\n })\n .next(matchingMutationBatches => {\n mutationBatches = matchingMutationBatches;\n // It is possible that a PatchMutation can make a document match a query, even if\n // the version in the RemoteDocumentCache is not a match yet (waiting for server\n // to ack). To handle this, we find all document keys affected by the PatchMutations\n // that are not in `result` yet, and back fill them via `remoteDocumentCache.getEntries`,\n // otherwise those `PatchMutations` will be ignored because no base document can be found,\n // and lead to missing result for the query.\n return this.addMissingBaseDocuments(\n transaction,\n mutationBatches,\n results\n ).next(mergedDocuments => {\n results = mergedDocuments;\n\n for (const batch of mutationBatches) {\n for (const mutation of batch.mutations) {\n const key = mutation.key;\n const baseDoc = results.get(key);\n const mutatedDoc = mutation.applyToLocalView(\n baseDoc,\n baseDoc,\n batch.localWriteTime\n );\n if (mutatedDoc instanceof Document) {\n results = results.insert(key, mutatedDoc);\n } else {\n results = results.remove(key);\n }\n }\n }\n });\n })\n .next(() => {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach((key, doc) => {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n\n return results;\n });\n }\n\n private addMissingBaseDocuments(\n transaction: PersistenceTransaction,\n matchingMutationBatches: MutationBatch[],\n existingDocuments: DocumentMap\n ): PersistencePromise<DocumentMap> {\n let missingBaseDocEntriesForPatching = documentKeySet();\n for (const batch of matchingMutationBatches) {\n for (const mutation of batch.mutations) {\n if (\n mutation instanceof PatchMutation &&\n existingDocuments.get(mutation.key) === null\n ) {\n missingBaseDocEntriesForPatching = missingBaseDocEntriesForPatching.add(\n mutation.key\n );\n }\n }\n }\n\n let mergedDocuments = existingDocuments;\n return this.remoteDocumentCache\n .getEntries(transaction, missingBaseDocEntriesForPatching)\n .next(missingBaseDocs => {\n missingBaseDocs.forEach((key, doc) => {\n if (doc !== null && doc instanceof Document) {\n mergedDocuments = mergedDocuments.insert(key, doc);\n }\n });\n return mergedDocuments;\n });\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { QueryEngine } from './query_engine';\nimport { LocalDocumentsView } from './local_documents_view';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { Query, LimitType } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentMap,\n MaybeDocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { assert } from '../util/assert';\nimport { debug, getLogLevel, LogLevel } from '../util/log';\nimport { SortedSet } from '../util/sorted_set';\n\n// TOOD(b/140938512): Drop SimpleQueryEngine and rename IndexFreeQueryEngine.\n\n/**\n * A query engine that takes advantage of the target document mapping in the\n * QueryCache. The IndexFreeQueryEngine optimizes query execution by only\n * reading the documents that previously matched a query plus any documents that were\n * edited after the query was last listened to.\n *\n * There are some cases where Index-Free queries are not guaranteed to produce\n * the same results as full collection scans. In these cases, the\n * IndexFreeQueryEngine falls back to full query processing. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of Limbo documents.\n */\nexport class IndexFreeQueryEngine implements QueryEngine {\n private localDocumentsView: LocalDocumentsView | undefined;\n\n setLocalDocumentsView(localDocuments: LocalDocumentsView): void {\n this.localDocumentsView = localDocuments;\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n lastLimboFreeSnapshotVersion: SnapshotVersion,\n remoteKeys: DocumentKeySet\n ): PersistencePromise<DocumentMap> {\n assert(\n this.localDocumentsView !== undefined,\n 'setLocalDocumentsView() not called'\n );\n\n // Queries that match all documents don't benefit from using\n // IndexFreeQueries. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n if (query.matchesAllDocuments()) {\n return this.executeFullCollectionScan(transaction, query);\n }\n\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.MIN)) {\n return this.executeFullCollectionScan(transaction, query);\n }\n\n return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(\n documents => {\n const previousResults = this.applyQuery(query, documents);\n\n if (\n (query.hasLimitToFirst() || query.hasLimitToLast()) &&\n this.needsRefill(\n query.limitType,\n previousResults,\n remoteKeys,\n lastLimboFreeSnapshotVersion\n )\n ) {\n return this.executeFullCollectionScan(transaction, query);\n }\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n debug(\n 'IndexFreeQueryEngine',\n 'Re-using previous result from %s to execute query: %s',\n lastLimboFreeSnapshotVersion.toString(),\n query.toString()\n );\n }\n\n // Retrieve all results for documents that were updated since the last\n // limbo-document free remote snapshot.\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n lastLimboFreeSnapshotVersion\n ).next(updatedResults => {\n // We merge `previousResults` into `updateResults`, since\n // `updateResults` is already a DocumentMap. If a document is\n // contained in both lists, then its contents are the same.\n previousResults.forEach(doc => {\n updatedResults = updatedResults.insert(doc.key, doc);\n });\n return updatedResults;\n });\n }\n );\n }\n\n /** Applies the query filter and sorting to the provided documents. */\n private applyQuery(\n query: Query,\n documents: MaybeDocumentMap\n ): SortedSet<Document> {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let queryResults = new SortedSet<Document>((d1, d2) =>\n query.docComparator(d1, d2)\n );\n documents.forEach((_, maybeDoc) => {\n if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n queryResults = queryResults.add(maybeDoc);\n }\n });\n return queryResults;\n }\n\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param sortedPreviousResults The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion The version of the snapshot when the query\n * was last synchronized.\n */\n private needsRefill(\n limitType: LimitType,\n sortedPreviousResults: SortedSet<Document>,\n remoteKeys: DocumentKeySet,\n limboFreeSnapshotVersion: SnapshotVersion\n ): boolean {\n // The query needs to be refilled if a previously matching document no\n // longer matches.\n if (remoteKeys.size !== sortedPreviousResults.size) {\n return true;\n }\n\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const docAtLimitEdge =\n limitType === LimitType.First\n ? sortedPreviousResults.last()\n : sortedPreviousResults.first();\n if (!docAtLimitEdge) {\n // We don't need to refill the query if there were already no documents.\n return false;\n }\n return (\n docAtLimitEdge.hasPendingWrites ||\n docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0\n );\n }\n\n private executeFullCollectionScan(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<DocumentMap> {\n if (getLogLevel() <= LogLevel.DEBUG) {\n debug(\n 'IndexFreeQueryEngine',\n 'Using full collection scan to execute query: %s',\n query.toString()\n );\n }\n\n return this.localDocumentsView!.getDocumentsMatchingQuery(\n transaction,\n query,\n SnapshotVersion.MIN\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encode(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decode(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n if (length === 2) {\n assert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 'Non-empty path ' + path + ' had length 2'\n );\n return ResourcePath.EMPTY_PATH;\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n\n/**\n * Computes the prefix successor of the given path, computed by encode above.\n * A prefix successor is the first key that cannot be prefixed by the given\n * path. It's useful for defining the end of a prefix scan such that all keys\n * in the scan have the same prefix.\n *\n * Note that this is not a general prefix successor implementation, which is\n * tricky to get right with Strings, given that they encode down to UTF-8.\n * Instead this relies on the fact that all paths encoded by this class are\n * always terminated with a separator, and so a successor can always be\n * cheaply computed by incrementing the last character of the path.\n */\nexport function prefixSuccessor(\n path: EncodedResourcePath\n): EncodedResourcePath {\n const c = path.charCodeAt(path.length - 1);\n // TODO(mcg): this really should be a general thing, but not worth it right\n // now\n assert(c === 1, 'successor may only operate on paths generated by encode');\n return path.substring(0, path.length - 1) + String.fromCharCode(c + 1);\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ResourcePath } from '../model/path';\nimport { assert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\nimport { IndexManager } from './index_manager';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n this.collectionParentIndex.add(collectionPath);\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n return PersistencePromise.resolve(\n this.collectionParentIndex.getEntries(collectionId)\n );\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */\nexport class MemoryCollectionParentIndex {\n private index = {} as {\n [collectionId: string]: SortedSet<ResourcePath>;\n };\n\n // Returns false if the entry already existed.\n add(collectionPath: ResourcePath): boolean {\n assert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n const added = !existingParents.has(parentPath);\n this.index[collectionId] = existingParents.add(parentPath);\n return added;\n }\n\n has(collectionPath: ResourcePath): boolean {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n const existingParents = this.index[collectionId];\n return existingParents && existingParents.has(parentPath);\n }\n\n getEntries(collectionId: string): ResourcePath[] {\n const parentPaths =\n this.index[collectionId] ||\n new SortedSet<ResourcePath>(ResourcePath.comparator);\n return parentPaths.toArray();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch, BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ByteString } from '../util/byte_string';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { MutationQueue } from './mutation_queue';\nimport { PersistenceTransaction, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { DocReference } from './reference_set';\n\nexport class MemoryMutationQueue implements MutationQueue {\n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n private mutationQueue: MutationBatch[] = [];\n\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n private nextBatchId: BatchId = 1;\n\n /** The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n */\n private lastStreamToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n\n /** An ordered mapping between documents and the mutations batch IDs. */\n private batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n\n constructor(\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n }\n\n acknowledgeBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch,\n streamToken: ByteString\n ): PersistencePromise<void> {\n const batchId = batch.batchId;\n const batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n assert(\n batchIndex === 0,\n 'Can only acknowledge the first batch in the mutation queue'\n );\n\n // Verify that the batch in the queue is the one to be acknowledged.\n const check = this.mutationQueue[batchIndex];\n assert(\n batchId === check.batchId,\n 'Queue ordering failure: expected batch ' +\n batchId +\n ', got batch ' +\n check.batchId\n );\n\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n }\n\n getLastStreamToken(\n transaction: PersistenceTransaction\n ): PersistencePromise<ByteString> {\n return PersistencePromise.resolve(this.lastStreamToken);\n }\n\n setLastStreamToken(\n transaction: PersistenceTransaction,\n streamToken: ByteString\n ): PersistencePromise<void> {\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise<MutationBatch> {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n\n const batchId = this.nextBatchId;\n this.nextBatchId++;\n\n if (this.mutationQueue.length > 0) {\n const prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(\n prior.batchId < batchId,\n 'Mutation batchIDs must be monotonically increasing order'\n );\n }\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n this.mutationQueue.push(batch);\n\n // Track references by document key and index collection parents.\n for (const mutation of mutations) {\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(\n new DocReference(mutation.key, batchId)\n );\n\n this.indexManager.addToCollectionParentIndex(\n transaction,\n mutation.key.path.popLast()\n );\n }\n\n return PersistencePromise.resolve(batch);\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n }\n\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<DocumentKeySet | null> {\n const mutationBatch = this.findMutationBatch(batchId);\n assert(mutationBatch != null, 'Failed to find local mutation batch.');\n return PersistencePromise.resolve<DocumentKeySet | null>(\n mutationBatch.keys()\n );\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n const nextBatchId = batchId + 1;\n\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n const rawIndex = this.indexOfBatchId(nextBatchId);\n const index = rawIndex < 0 ? 0 : rawIndex;\n return PersistencePromise.resolve(\n this.mutationQueue.length > index ? this.mutationQueue[index] : null\n );\n }\n\n getHighestUnacknowledgedBatchId(): PersistencePromise<BatchId> {\n return PersistencePromise.resolve(\n this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1\n );\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise<MutationBatch[]> {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutationBatch[]> {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n const result: MutationBatch[] = [];\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n assert(\n documentKey.isEqual(ref.key),\n \"Should only iterate over a single key's batches\"\n );\n const batch = this.findMutationBatch(ref.targetOrBatchId);\n assert(\n batch !== null,\n 'Batches in the index must exist in the main table'\n );\n result.push(batch!);\n });\n\n return PersistencePromise.resolve(result);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap<DocumentKey, unknown>\n ): PersistencePromise<MutationBatch[]> {\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n documentKeys.forEach(documentKey => {\n const start = new DocReference(documentKey, 0);\n const end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n this.batchesByDocumentKey.forEachInRange([start, end], ref => {\n assert(\n documentKey.isEqual(ref.key),\n \"For each key, should only iterate over a single key's batches\"\n );\n\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n });\n });\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<MutationBatch[]> {\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const prefix = query.path;\n const immediateChildrenPathLength = prefix.length + 1;\n\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let startPath = prefix;\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n\n const start = new DocReference(new DocumentKey(startPath), 0);\n\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let uniqueBatchIDs = new SortedSet<number>(primitiveComparator);\n\n this.batchesByDocumentKey.forEachWhile(ref => {\n const rowKeyPath = ref.key.path;\n if (!prefix.isPrefixOf(rowKeyPath)) {\n return false;\n } else {\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (rowKeyPath.length === immediateChildrenPathLength) {\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n }\n return true;\n }\n }, start);\n\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n }\n\n private findMutationBatches(batchIDs: SortedSet<number>): MutationBatch[] {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const result: MutationBatch[] = [];\n batchIDs.forEach(batchId => {\n const batch = this.findMutationBatch(batchId);\n if (batch !== null) {\n result.push(batch);\n }\n });\n return result;\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise<void> {\n // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n assert(\n batchIndex === 0,\n 'Can only remove the first entry of the mutation queue'\n );\n this.mutationQueue.shift();\n\n let references = this.batchesByDocumentKey;\n return PersistencePromise.forEach(batch.mutations, (mutation: Mutation) => {\n const ref = new DocReference(mutation.key, batch.batchId);\n references = references.delete(ref);\n return this.referenceDelegate.removeMutationReference(\n transaction,\n mutation.key\n );\n }).next(() => {\n this.batchesByDocumentKey = references;\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n const ref = new DocReference(key, 0);\n const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n if (this.mutationQueue.length === 0) {\n assert(\n this.batchesByDocumentKey.isEmpty(),\n 'Document leak -- detected dangling mutation references when queue is empty.'\n );\n }\n return PersistencePromise.resolve();\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId The batchId to search for\n * @param action A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */\n private indexOfExistingBatchId(batchId: BatchId, action: string): number {\n const index = this.indexOfBatchId(batchId);\n assert(\n index >= 0 && index < this.mutationQueue.length,\n 'Batches must exist to be ' + action\n );\n return index;\n }\n\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @return The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */\n private indexOfBatchId(batchId: BatchId): number {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\n }\n\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n const firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n }\n\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */\n private findMutationBatch(batchId: BatchId): MutationBatch | null {\n const index = this.indexOfBatchId(batchId);\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n\n const batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../core/query';\nimport {\n DocumentKeySet,\n DocumentMap,\n documentMap,\n DocumentSizeEntry,\n MaybeDocumentMap,\n NullableMaybeDocumentMap,\n nullableMaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\nimport { IndexManager } from './index_manager';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\n\nexport type DocumentSizer = (doc: MaybeDocument) => number;\n\n/** Miscellaneous collection types / constants. */\ninterface MemoryRemoteDocumentCacheEntry extends DocumentSizeEntry {\n readTime: SnapshotVersion;\n}\n\ntype DocumentEntryMap = SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>;\nfunction documentEntryMap(): DocumentEntryMap {\n return new SortedMap<DocumentKey, MemoryRemoteDocumentCacheEntry>(\n DocumentKey.comparator\n );\n}\n\nexport class MemoryRemoteDocumentCache implements RemoteDocumentCache {\n /** Underlying cache of documents and their read times. */\n private docs = documentEntryMap();\n\n /** Size of all cached documents. */\n private size = 0;\n\n /**\n * @param sizer Used to assess the size of a document. For eager GC, this is expected to just\n * return 0 to avoid unnecessarily doing the work of calculating the size.\n */\n constructor(\n private readonly indexManager: IndexManager,\n private readonly sizer: DocumentSizer\n ) {}\n\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n private addEntry(\n transaction: PersistenceTransaction,\n doc: MaybeDocument,\n readTime: SnapshotVersion\n ): PersistencePromise<void> {\n assert(\n !readTime.isEqual(SnapshotVersion.MIN),\n 'Cannot add a document with a read time of zero'\n );\n\n const key = doc.key;\n const entry = this.docs.get(key);\n const previousSize = entry ? entry.size : 0;\n const currentSize = this.sizer(doc);\n\n this.docs = this.docs.insert(key, {\n maybeDocument: doc,\n size: currentSize,\n readTime\n });\n\n this.size += currentSize - previousSize;\n\n return this.indexManager.addToCollectionParentIndex(\n transaction,\n key.path.popLast()\n );\n }\n\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */\n private removeEntry(documentKey: DocumentKey): void {\n const entry = this.docs.get(documentKey);\n if (entry) {\n this.docs = this.docs.remove(documentKey);\n this.size -= entry.size;\n }\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n const entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(entry ? entry.maybeDocument : null);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n let results = nullableMaybeDocumentMap();\n documentKeys.forEach(documentKey => {\n const entry = this.docs.get(documentKey);\n results = results.insert(documentKey, entry ? entry.maybeDocument : null);\n });\n return PersistencePromise.resolve(results);\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n let results = documentMap();\n\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const prefix = new DocumentKey(query.path.child(''));\n const iterator = this.docs.getIteratorFrom(prefix);\n while (iterator.hasNext()) {\n const {\n key,\n value: { maybeDocument, readTime }\n } = iterator.getNext();\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n if (readTime.compareTo(sinceReadTime) <= 0) {\n continue;\n }\n if (maybeDocument instanceof Document && query.matches(maybeDocument)) {\n results = results.insert(maybeDocument.key, maybeDocument);\n }\n }\n return PersistencePromise.resolve(results);\n }\n\n forEachDocumentKey(\n transaction: PersistenceTransaction,\n f: (key: DocumentKey) => PersistencePromise<void>\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(this.docs, (key: DocumentKey) => f(key));\n }\n\n getNewDocumentChanges(\n transaction: PersistenceTransaction,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<{\n changedDocs: MaybeDocumentMap;\n readTime: SnapshotVersion;\n }> {\n throw new Error(\n 'getNewDocumentChanges() is not supported with MemoryPersistence'\n );\n }\n\n getLastReadTime(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return PersistencePromise.resolve(SnapshotVersion.MIN);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new MemoryRemoteDocumentCache.RemoteDocumentChangeBuffer(this);\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return PersistencePromise.resolve(this.size);\n }\n\n /**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\n private static RemoteDocumentChangeBuffer = class extends RemoteDocumentChangeBuffer {\n constructor(private readonly documentCache: MemoryRemoteDocumentCache) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n this.changes.forEach((key, doc) => {\n if (doc) {\n promises.push(\n this.documentCache.addEntry(transaction, doc, this.readTime)\n );\n } else {\n this.documentCache.removeEntry(key);\n }\n });\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n return this.documentCache.getEntry(transaction, documentKey);\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n return this.documentCache.getEntries(transaction, documentKeys);\n }\n };\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../util/assert';\nimport { TargetId } from './types';\n\nconst RESERVED_BITS = 1;\n\nconst enum GeneratorIds {\n QueryCache = 0, // The target IDs for user-issued queries are even (end in 0).\n SyncEngine = 1 // The target IDs for limbo detection are odd (end in 1).\n}\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the query cache (via\n * forQueryCache()), and one for limbo documents (via forSyncEngine()). These\n * two generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\n// TODO(mrschmidt): Explore removing this class in favor of generating these IDs\n// directly in SyncEngine and LocalStore.\nexport class TargetIdGenerator {\n // Initialized in the constructor via call to seek().\n private nextId!: TargetId;\n\n /**\n * Instantiates a new TargetIdGenerator. If a seed is provided, the generator\n * will use the seed value as the next target ID.\n */\n constructor(private generatorId: number, seed?: number) {\n assert(\n (generatorId & RESERVED_BITS) === generatorId,\n `Generator ID ${generatorId} contains more than ${RESERVED_BITS} reserved bits`\n );\n this.seek(seed !== undefined ? seed : this.generatorId);\n }\n\n next(): TargetId {\n const nextId = this.nextId;\n this.nextId += 1 << RESERVED_BITS;\n return nextId;\n }\n\n /**\n * Returns the ID that follows the given ID. Subsequent calls to `next()`\n * use the newly returned target ID as their base.\n */\n // PORTING NOTE: Multi-tab only.\n after(targetId: TargetId): TargetId {\n this.seek(targetId + (1 << RESERVED_BITS));\n return this.next();\n }\n\n private seek(targetId: TargetId): void {\n assert(\n (targetId & RESERVED_BITS) === this.generatorId,\n 'Cannot supply target ID from different generator ID'\n );\n this.nextId = targetId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // We seed the query cache generator to return '2' as its first ID, as there\n // is no differentiation in the protocol layer between an unset number and\n // the number '0'. If we were to sent a target with target ID '0', the\n // backend would consider it unset and replace it with its own ID.\n const targetIdGenerator = new TargetIdGenerator(GeneratorIds.QueryCache, 2);\n return targetIdGenerator;\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { assert, fail } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { MemoryPersistence } from './memory_persistence';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\nimport { Target } from '../core/target';\n\nexport class MemoryTargetCache implements TargetCache {\n /**\n * Maps a target to the data about that target\n */\n private targets = new ObjectMap<Target, TargetData>(t => t.canonicalId());\n\n /** The last received snapshot version. */\n private lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n private highestTargetId: TargetId = 0;\n /** The highest sequence number encountered. */\n private highestSequenceNumber: ListenSequenceNumber = 0;\n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n private references = new ReferenceSet();\n\n private targetCount = 0;\n\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n constructor(private readonly persistence: MemoryPersistence) {}\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n this.targets.forEach((_, targetData) => f(targetData));\n return PersistencePromise.resolve();\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<ListenSequenceNumber> {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n }\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise<TargetId> {\n const nextTargetId = this.targetIdGenerator.after(this.highestTargetId);\n this.highestTargetId = nextTargetId;\n return PersistencePromise.resolve(nextTargetId);\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise<void> {\n if (lastRemoteSnapshotVersion) {\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = highestListenSequenceNumber;\n }\n return PersistencePromise.resolve();\n }\n\n private saveTargetData(targetData: TargetData): void {\n this.targets.set(targetData.target, targetData);\n const targetId = targetData.targetId;\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n if (targetData.sequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = targetData.sequenceNumber;\n }\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n assert(\n !this.targets.has(targetData.target),\n 'Adding a target that already exists'\n );\n this.saveTargetData(targetData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n assert(\n this.targets.has(targetData.target),\n 'Updating a non-existent target'\n );\n this.saveTargetData(targetData);\n return PersistencePromise.resolve();\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n assert(this.targetCount > 0, 'Removing a target from an empty cache');\n assert(\n this.targets.has(targetData.target),\n 'Removing a non-existent target from the cache'\n );\n this.targets.delete(targetData.target);\n this.references.removeReferencesForId(targetData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n }\n\n removeTargets(\n transaction: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n let count = 0;\n const removals: Array<PersistencePromise<void>> = [];\n this.targets.forEach((key, targetData) => {\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n this.targets.delete(key);\n removals.push(\n this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n );\n count++;\n }\n });\n return PersistencePromise.waitFor(removals).next(() => count);\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n return PersistencePromise.resolve(this.targetCount);\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\n const targetData = this.targets.get(target) || null;\n return PersistencePromise.resolve(targetData);\n }\n\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): never {\n // This method is only needed for multi-tab and we can't implement it\n // efficiently without additional data structures.\n return fail('Not yet implemented.');\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.addReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array<PersistencePromise<void>> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.addReference(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferences(keys, targetId);\n const referenceDelegate = this.persistence.referenceDelegate;\n const promises: Array<PersistencePromise<void>> = [];\n if (referenceDelegate) {\n keys.forEach(key => {\n promises.push(referenceDelegate.removeReference(txn, key));\n });\n }\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<void> {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<DocumentKeySet> {\n const matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.resolve(this.references.containsKey(key));\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { User } from '../auth/user';\nimport { Document, MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { debug } from '../util/log';\nimport * as obj from '../util/obj';\nimport { ObjectMap } from '../util/obj_map';\nimport { encode } from './encoded_resource_path';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\n\nimport { DatabaseInfo } from '../core/database_info';\nimport { PersistenceSettings } from '../core/firestore_client';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { AsyncQueue } from '../util/async_queue';\nimport { MemoryIndexManager } from './memory_index_manager';\nimport { MemoryMutationQueue } from './memory_mutation_queue';\nimport { MemoryRemoteDocumentCache } from './memory_remote_document_cache';\nimport { MemoryTargetCache } from './memory_target_cache';\nimport { MutationQueue } from './mutation_queue';\nimport {\n GarbageCollectionScheduler,\n Persistence,\n PersistenceProvider,\n PersistenceTransaction,\n PersistenceTransactionMode,\n PrimaryStateListener,\n ReferenceDelegate\n} from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { Platform } from '../platform/platform';\nimport { ReferenceSet } from './reference_set';\nimport {\n ClientId,\n MemorySharedClientState,\n SharedClientState\n} from './shared_client_state';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\n\nconst MEMORY_ONLY_PERSISTENCE_ERROR_MESSAGE =\n 'You are using the memory-only build of Firestore. Persistence support is ' +\n 'only available via the @firebase/firestore bundle or the ' +\n 'firebase-firestore.js build.';\n\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nexport class MemoryPersistence implements Persistence {\n /**\n * Note that these are retained here to make it easier to write tests\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\n * can create a new LocalStore wrapping this Persistence instance and this\n * will make the in-memory persistence layer behave as if it were actually\n * persisting values.\n */\n private readonly indexManager: MemoryIndexManager;\n private mutationQueues: { [user: string]: MemoryMutationQueue } = {};\n private readonly remoteDocumentCache: MemoryRemoteDocumentCache;\n private readonly targetCache: MemoryTargetCache;\n private readonly listenSequence = new ListenSequence(0);\n\n private _started = false;\n\n readonly referenceDelegate: MemoryReferenceDelegate;\n \n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(\n private readonly clientId: ClientId,\n referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate\n ) {\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.targetCache = new MemoryTargetCache(this);\n const sizer = (doc: MaybeDocument): number =>\n this.referenceDelegate.documentSize(doc);\n this.indexManager = new MemoryIndexManager();\n this.remoteDocumentCache = new MemoryRemoteDocumentCache(\n this.indexManager,\n sizer\n );\n }\n\n shutdown(): Promise<void> {\n // No durable state to ensure is closed on shutdown.\n this._started = false;\n return Promise.resolve();\n }\n\n get started(): boolean {\n return this._started;\n }\n\n async getActiveClients(): Promise<ClientId[]> {\n return [this.clientId];\n }\n\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise<void> {\n // All clients using memory persistence act as primary.\n return primaryStateListener(true);\n }\n\n setDatabaseDeletedListener(): void {\n // No op.\n }\n\n setNetworkEnabled(networkEnabled: boolean): void {\n // No op.\n }\n\n getIndexManager(): MemoryIndexManager {\n return this.indexManager;\n }\n\n getMutationQueue(user: User): MutationQueue {\n let queue = this.mutationQueues[user.toKey()];\n if (!queue) {\n queue = new MemoryMutationQueue(\n this.indexManager,\n this.referenceDelegate\n );\n this.mutationQueues[user.toKey()] = queue;\n }\n return queue;\n }\n\n getTargetCache(): MemoryTargetCache {\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): MemoryRemoteDocumentCache {\n return this.remoteDocumentCache;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n debug(LOG_TAG, 'Starting transaction:', action);\n const txn = new MemoryTransaction(this.listenSequence.next());\n this.referenceDelegate.onTransactionStarted();\n return transactionOperation(txn)\n .next(result => {\n return this.referenceDelegate\n .onTransactionCommitted(txn)\n .next(() => result);\n })\n .toPromise()\n .then(result => {\n txn.raiseOnCommittedEvent();\n return result;\n });\n }\n\n mutationQueuesContainKey(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or(\n obj\n .values(this.mutationQueues)\n .map(queue => () => queue.containsKey(transaction, key))\n );\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */\nexport class MemoryTransaction extends PersistenceTransaction {\n constructor(readonly currentSequenceNumber: ListenSequenceNumber) {\n super();\n }\n}\n\nexport interface MemoryReferenceDelegate extends ReferenceDelegate {\n documentSize(doc: MaybeDocument): number;\n onTransactionStarted(): void;\n onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise<void>;\n}\n\nexport class MemoryEagerDelegate implements MemoryReferenceDelegate {\n private inMemoryPins: ReferenceSet | null = null;\n private _orphanedDocuments: Set<DocumentKey> | null = null;\n\n constructor(private readonly persistence: MemoryPersistence) {}\n\n private get orphanedDocuments(): Set<DocumentKey> {\n if (!this._orphanedDocuments) {\n throw fail('orphanedDocuments is only valid during a transaction.');\n } else {\n return this._orphanedDocuments;\n }\n }\n\n setInMemoryPins(inMemoryPins: ReferenceSet): void {\n this.inMemoryPins = inMemoryPins;\n }\n\n addReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.delete(key);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.add(key);\n return PersistencePromise.resolve();\n }\n\n removeMutationReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedDocuments.add(key);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const cache = this.persistence.getTargetCache();\n return cache\n .getMatchingKeysForTargetId(txn, targetData.targetId)\n .next(keys => {\n keys.forEach(key => this.orphanedDocuments.add(key));\n })\n .next(() => cache.removeTargetData(txn, targetData));\n }\n\n onTransactionStarted(): void {\n this._orphanedDocuments = new Set<DocumentKey>();\n }\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n // Remove newly orphaned documents.\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n return PersistencePromise.forEach(\n this.orphanedDocuments,\n (key: DocumentKey) => {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (!isReferenced) {\n changeBuffer.removeEntry(key);\n }\n });\n }\n ).next(() => {\n this._orphanedDocuments = null;\n return changeBuffer.apply(txn);\n });\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return this.isReferenced(txn, key).next(isReferenced => {\n if (isReferenced) {\n this.orphanedDocuments.delete(key);\n } else {\n this.orphanedDocuments.add(key);\n }\n });\n }\n\n documentSize(doc: MaybeDocument): number {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n\n private isReferenced(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => PersistencePromise.resolve(this.inMemoryPins!.containsKey(key))\n ]);\n }\n}\n\nexport class MemoryLruDelegate implements ReferenceDelegate, LruDelegate {\n private inMemoryPins: ReferenceSet | null = null;\n private orphanedSequenceNumbers: ObjectMap<\n DocumentKey,\n ListenSequenceNumber\n > = new ObjectMap(k => encode(k.path));\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(\n private readonly persistence: MemoryPersistence,\n lruParams: LruParams\n ) {\n this.garbageCollector = new LruGarbageCollector(this, lruParams);\n }\n\n // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n onTransactionStarted(): void {}\n\n onTransactionCommitted(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n return PersistencePromise.resolve();\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return this.persistence.getTargetCache().forEachTarget(txn, f);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.persistence\n .getTargetCache()\n .getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n return PersistencePromise.forEach(\n this.orphanedSequenceNumbers,\n (key, sequenceNumber) => {\n // Pass in the exact sequence number as the upper bound so we know it won't be pinned by\n // being too recent.\n return this.isPinned(txn, key, sequenceNumber).next(isPinned => {\n if (!isPinned) {\n return f(sequenceNumber);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n );\n }\n\n setInMemoryPins(inMemoryPins: ReferenceSet): void {\n this.inMemoryPins = inMemoryPins;\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.persistence\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n let count = 0;\n const cache = this.persistence.getRemoteDocumentCache();\n const changeBuffer = cache.newChangeBuffer();\n const p = cache.forEachDocumentKey(txn, key => {\n return this.isPinned(txn, key, upperBound).next(isPinned => {\n if (!isPinned) {\n count++;\n changeBuffer.removeEntry(key);\n }\n });\n });\n return p.next(() => changeBuffer.apply(txn)).next(() => count);\n }\n\n removeMutationReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.persistence.getTargetCache().updateTargetData(txn, updated);\n }\n\n addReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n removeReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n }\n\n documentSize(maybeDoc: MaybeDocument): number {\n let documentSize = maybeDoc.key.toString().length;\n if (maybeDoc instanceof Document) {\n documentSize += maybeDoc.data().approximateByteSize();\n }\n return documentSize;\n }\n\n private isPinned(\n txn: PersistenceTransaction,\n key: DocumentKey,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<boolean> {\n return PersistencePromise.or([\n () => this.persistence.mutationQueuesContainKey(txn, key),\n () => PersistencePromise.resolve(this.inMemoryPins!.containsKey(key)),\n () => this.persistence.getTargetCache().containsKey(txn, key),\n () => {\n const orphanedAt = this.orphanedSequenceNumbers.get(key);\n return PersistencePromise.resolve(\n orphanedAt !== undefined && orphanedAt > upperBound\n );\n }\n ]);\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nexport class MemoryPersistenceProvider implements PersistenceProvider {\n private clientId: ClientId | undefined;\n\n initialize(\n asyncQueue: AsyncQueue,\n databaseInfo: DatabaseInfo,\n platform: Platform,\n clientId: ClientId,\n initialUser: User,\n settings: PersistenceSettings\n ): Promise<void> {\n if (settings.durable) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n MEMORY_ONLY_PERSISTENCE_ERROR_MESSAGE\n );\n }\n this.clientId = clientId;\n return Promise.resolve();\n }\n\n getGarbageCollectionScheduler(): GarbageCollectionScheduler {\n let started = false;\n return {\n started,\n start: () => (started = true),\n stop: () => (started = false)\n };\n }\n\n getPersistence(): Persistence {\n assert(!!this.clientId, 'initialize() not called');\n return new MemoryPersistence(\n this.clientId,\n p => new MemoryEagerDelegate(p)\n );\n }\n\n getSharedClientState(): SharedClientState {\n return new MemorySharedClientState();\n }\n\n clearPersistence(): never {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n MEMORY_ONLY_PERSISTENCE_ERROR_MESSAGE\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { AsyncQueue, TimerId } from '../util/async_queue';\nimport * as log from '../util/log';\nimport { CancelablePromise } from '../util/promise';\nconst LOG_TAG = 'ExponentialBackoff';\n\n/**\n * Initial backoff time in milliseconds after an error.\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\n */\nconst DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000;\n\nconst DEFAULT_BACKOFF_FACTOR = 1.5;\n\n/** Maximum backoff time in milliseconds */\nconst DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000;\n\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nexport class ExponentialBackoff {\n private currentBaseMs: number = 0;\n private timerPromise: CancelablePromise<void> | null = null;\n /** The last backoff attempt, as epoch milliseconds. */\n private lastAttemptTime = Date.now();\n\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n private readonly queue: AsyncQueue,\n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n private readonly timerId: TimerId,\n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n private readonly initialDelayMs: number = DEFAULT_BACKOFF_INITIAL_DELAY_MS,\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */\n private readonly backoffFactor: number = DEFAULT_BACKOFF_FACTOR,\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */\n private readonly maxDelayMs: number = DEFAULT_BACKOFF_MAX_DELAY_MS\n ) {\n this.reset();\n }\n\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */\n reset(): void {\n this.currentBaseMs = 0;\n }\n\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */\n resetToMax(): void {\n this.currentBaseMs = this.maxDelayMs;\n }\n\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */\n backoffAndRun(op: () => Promise<void>): void {\n // Cancel any pending backoff operation.\n this.cancel();\n\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const desiredDelayWithJitterMs = Math.floor(\n this.currentBaseMs + this.jitterDelayMs()\n );\n\n // Guard against lastAttemptTime being in the future due to a clock change.\n const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime);\n\n // Guard against the backoff delay already being past.\n const remainingDelayMs = Math.max(\n 0,\n desiredDelayWithJitterMs - delaySoFarMs\n );\n\n if (this.currentBaseMs > 0) {\n log.debug(\n LOG_TAG,\n `Backing off for ${remainingDelayMs} ms ` +\n `(base delay: ${this.currentBaseMs} ms, ` +\n `delay with jitter: ${desiredDelayWithJitterMs} ms, ` +\n `last attempt: ${delaySoFarMs} ms ago)`\n );\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(\n this.timerId,\n remainingDelayMs,\n () => {\n this.lastAttemptTime = Date.now();\n return op();\n }\n );\n\n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.currentBaseMs *= this.backoffFactor;\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n }\n\n cancel(): void {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n }\n\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n private jitterDelayMs(): number {\n return (Math.random() - 0.5) * this.currentBaseMs;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { CredentialsProvider, Token } from '../api/credentials';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { TargetId } from '../core/types';\nimport { TargetData } from '../local/target_data';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\n\nimport { CancelablePromise } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\nimport { ExponentialBackoff } from './backoff';\nimport { Connection, Stream } from './connection';\nimport { JsonProtoSerializer } from './serializer';\nimport { WatchChange } from './watch_change';\nimport { ByteString } from '../util/byte_string';\n\nconst LOG_TAG = 'PersistentStream';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface ListenRequest extends api.ListenRequest {\n database?: string;\n}\nexport interface WriteRequest extends api.WriteRequest {\n database?: string;\n}\n/**\n * PersistentStream can be in one of 5 states (each described in detail below)\n * based on the following state transition diagram:\n *\n * start() called auth & connection succeeded\n * INITIAL ----------------> STARTING -----------------------------> OPEN\n * ^ | |\n * | | error occurred |\n * | \\-----------------------------v-----/\n * | |\n * backoff | |\n * elapsed | start() called |\n * \\--- BACKOFF <---------------- ERROR\n *\n * [any state] --------------------------> INITIAL\n * stop() called or\n * idle timer expired\n */\nconst enum PersistentStreamState {\n /**\n * The streaming RPC is not yet running and there's no error condition.\n * Calling start() will start the stream immediately without backoff.\n * While in this state isStarted() will return false.\n */\n Initial,\n\n /**\n * The stream is starting, either waiting for an auth token or for the stream\n * to successfully open. While in this state, isStarted() will return true but\n * isOpen() will return false.\n */\n Starting,\n\n /**\n * The streaming RPC is up and running. Requests and responses can flow\n * freely. Both isStarted() and isOpen() will return true.\n */\n Open,\n\n /**\n * The stream encountered an error. The next start attempt will back off.\n * While in this state isStarted() will return false.\n */\n Error,\n\n /**\n * An in-between state after an error where the stream is waiting before\n * re-starting. After waiting is complete, the stream will try to open.\n * While in this state isStarted() will return true but isOpen() will return\n * false.\n */\n Backoff\n}\n\n/**\n * Provides a common interface that is shared by the listeners for stream\n * events by the concrete implementation classes.\n */\nexport interface PersistentStreamListener {\n /**\n * Called after the stream was established and can accept outgoing\n * messages\n */\n onOpen: () => Promise<void>;\n /**\n * Called after the stream has closed. If there was an error, the\n * FirestoreError will be set.\n */\n onClose: (err?: FirestoreError) => Promise<void>;\n}\n\n/** The time a stream stays open after it is marked idle. */\nconst IDLE_TIMEOUT_MS = 60 * 1000;\n\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nexport abstract class PersistentStream<\n SendType,\n ReceiveType,\n ListenerType extends PersistentStreamListener\n> {\n private state = PersistentStreamState.Initial;\n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n private closeCount = 0;\n\n private idleTimer: CancelablePromise<void> | null = null;\n private stream: Stream<SendType, ReceiveType> | null = null;\n\n protected backoff: ExponentialBackoff;\n\n constructor(\n private queue: AsyncQueue,\n connectionTimerId: TimerId,\n private idleTimerId: TimerId,\n protected connection: Connection,\n private credentialsProvider: CredentialsProvider,\n protected listener: ListenerType\n ) {\n this.backoff = new ExponentialBackoff(queue, connectionTimerId);\n }\n\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */\n isStarted(): boolean {\n return (\n this.state === PersistentStreamState.Starting ||\n this.state === PersistentStreamState.Open ||\n this.state === PersistentStreamState.Backoff\n );\n }\n\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */\n isOpen(): boolean {\n return this.state === PersistentStreamState.Open;\n }\n\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */\n start(): void {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.auth();\n }\n\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */\n async stop(): Promise<void> {\n if (this.isStarted()) {\n await this.close(PersistentStreamState.Initial);\n }\n }\n\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */\n inhibitBackoff(): void {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n }\n\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */\n markIdle(): void {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n if (this.isOpen() && this.idleTimer === null) {\n this.idleTimer = this.queue.enqueueAfterDelay(\n this.idleTimerId,\n IDLE_TIMEOUT_MS,\n () => this.handleIdleCloseTimer()\n );\n }\n }\n\n /** Sends a message to the underlying stream. */\n protected sendRequest(msg: SendType): void {\n this.cancelIdleCheck();\n this.stream!.send(msg);\n }\n\n /** Called by the idle timer when the stream should close due to inactivity. */\n private async handleIdleCloseTimer(): Promise<void> {\n if (this.isOpen()) {\n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(PersistentStreamState.Initial);\n }\n }\n\n /** Marks the stream as active again. */\n private cancelIdleCheck(): void {\n if (this.idleTimer) {\n this.idleTimer.cancel();\n this.idleTimer = null;\n }\n }\n\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState the intended state of the stream after closing.\n * @param error the error the connection was closed with.\n */\n private async close(\n finalState: PersistentStreamState,\n error?: FirestoreError\n ): Promise<void> {\n assert(this.isStarted(), 'Only started streams should be closed.');\n assert(\n finalState === PersistentStreamState.Error || isNullOrUndefined(error),\n \"Can't provide an error when not in an error state.\"\n );\n\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.cancelIdleCheck();\n this.backoff.cancel();\n\n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.closeCount++;\n\n if (finalState !== PersistentStreamState.Error) {\n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.backoff.reset();\n } else if (error && error.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n log.error(error.toString());\n log.error(\n 'Using maximum backoff delay to prevent overloading the backend.'\n );\n this.backoff.resetToMax();\n } else if (error && error.code === Code.UNAUTHENTICATED) {\n // \"unauthenticated\" error means the token was rejected. Try force refreshing it in case it\n // just expired.\n this.credentialsProvider.invalidateToken();\n }\n\n // Clean up the underlying stream because we are no longer interested in events.\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\n }\n\n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = finalState;\n\n // Notify the listener that the stream closed.\n await this.listener.onClose(error);\n }\n\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */\n protected tearDown(): void {}\n\n /**\n * Used by subclasses to start the concrete RPC and return the underlying\n * connection stream.\n */\n protected abstract startRpc(\n token: Token | null\n ): Stream<SendType, ReceiveType>;\n\n /**\n * Called after the stream has received a message. The function will be\n * called on the right queue and must return a Promise.\n * @param message The message received from the stream.\n */\n protected abstract onMessage(message: ReceiveType): Promise<void>;\n\n private auth(): void {\n assert(\n this.state === PersistentStreamState.Initial,\n 'Must be in initial state to auth'\n );\n\n this.state = PersistentStreamState.Starting;\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n const closeCount = this.closeCount;\n\n this.credentialsProvider.getToken().then(\n token => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n if (this.closeCount === closeCount) {\n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.startStream(token);\n }\n },\n (error: Error) => {\n dispatchIfNotClosed(() => {\n const rpcError = new FirestoreError(\n Code.UNKNOWN,\n 'Fetching auth token failed: ' + error.message\n );\n return this.handleStreamClose(rpcError);\n });\n }\n );\n }\n\n private startStream(token: Token | null): void {\n assert(\n this.state === PersistentStreamState.Starting,\n 'Trying to start stream in a non-starting state'\n );\n\n const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n\n this.stream = this.startRpc(token);\n this.stream.onOpen(() => {\n dispatchIfNotClosed(() => {\n assert(\n this.state === PersistentStreamState.Starting,\n 'Expected stream to be in state Starting, but was ' + this.state\n );\n this.state = PersistentStreamState.Open;\n return this.listener!.onOpen();\n });\n });\n this.stream.onClose((error?: FirestoreError) => {\n dispatchIfNotClosed(() => {\n return this.handleStreamClose(error);\n });\n });\n this.stream.onMessage((msg: ReceiveType) => {\n dispatchIfNotClosed(() => {\n return this.onMessage(msg);\n });\n });\n }\n\n private performBackoff(): void {\n assert(\n this.state === PersistentStreamState.Error,\n 'Should only perform backoff when in Error state'\n );\n this.state = PersistentStreamState.Backoff;\n\n this.backoff.backoffAndRun(async () => {\n assert(\n this.state === PersistentStreamState.Backoff,\n 'Backoff elapsed but state is now: ' + this.state\n );\n\n this.state = PersistentStreamState.Initial;\n this.start();\n assert(this.isStarted(), 'PersistentStream should have started');\n });\n }\n\n // Visible for tests\n handleStreamClose(error?: FirestoreError): Promise<void> {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n log.debug(LOG_TAG, `close with error: ${error}`);\n\n this.stream = null;\n\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return this.close(PersistentStreamState.Error, error);\n }\n\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */\n private getCloseGuardedDispatcher(\n startCloseCount: number\n ): (fn: () => Promise<void>) => void {\n return (fn: () => Promise<void>): void => {\n this.queue.enqueueAndForget(() => {\n if (this.closeCount === startCloseCount) {\n return fn();\n } else {\n log.debug(\n LOG_TAG,\n 'stream callback skipped by getCloseGuardedDispatcher.'\n );\n return Promise.resolve();\n }\n });\n };\n }\n}\n\n/** Listener for the PersistentWatchStream */\nexport interface WatchStreamListener extends PersistentStreamListener {\n /**\n * Called on a watchChange. The snapshot parameter will be MIN if the watch\n * change did not have a snapshot associated with it.\n */\n onWatchChange: (\n watchChange: WatchChange,\n snapshot: SnapshotVersion\n ) => Promise<void>;\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */\nexport class PersistentListenStream extends PersistentStream<\n api.ListenRequest,\n api.ListenResponse,\n WatchStreamListener\n> {\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n credentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WatchStreamListener\n ) {\n super(\n queue,\n TimerId.ListenStreamConnectionBackoff,\n TimerId.ListenStreamIdle,\n connection,\n credentials,\n listener\n );\n }\n\n protected startRpc(\n token: Token | null\n ): Stream<api.ListenRequest, api.ListenResponse> {\n return this.connection.openStream<api.ListenRequest, api.ListenResponse>(\n 'Listen',\n token\n );\n }\n\n protected onMessage(watchChangeProto: api.ListenResponse): Promise<void> {\n // A successful response means the stream is healthy\n this.backoff.reset();\n\n const watchChange = this.serializer.fromWatchChange(watchChangeProto);\n const snapshot = this.serializer.versionFromListenResponse(\n watchChangeProto\n );\n return this.listener!.onWatchChange(watchChange, snapshot);\n }\n\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */\n watch(targetData: TargetData): void {\n const request: ListenRequest = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(targetData);\n\n const labels = this.serializer.toListenRequestLabels(targetData);\n if (labels) {\n request.labels = labels;\n }\n\n this.sendRequest(request);\n }\n\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */\n unwatch(targetId: TargetId): void {\n const request: ListenRequest = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.sendRequest(request);\n }\n}\n\n/** Listener for the PersistentWriteStream */\nexport interface WriteStreamListener extends PersistentStreamListener {\n /**\n * Called by the PersistentWriteStream upon a successful handshake response\n * from the server, which is the receiver's cue to send any pending writes.\n */\n onHandshakeComplete: () => Promise<void>;\n\n /**\n * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse\n * from the server that contains a mutation result.\n */\n onMutationResult: (\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ) => Promise<void>;\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */\nexport class PersistentWriteStream extends PersistentStream<\n api.WriteRequest,\n api.WriteResponse,\n WriteStreamListener\n> {\n private handshakeComplete_ = false;\n\n constructor(\n queue: AsyncQueue,\n connection: Connection,\n credentials: CredentialsProvider,\n private serializer: JsonProtoSerializer,\n listener: WriteStreamListener\n ) {\n super(\n queue,\n TimerId.WriteStreamConnectionBackoff,\n TimerId.WriteStreamIdle,\n connection,\n credentials,\n listener\n );\n }\n\n /**\n * The last received stream token from the server, used to acknowledge which\n * responses the client has processed. Stream tokens are opaque checkpoint\n * markers whose only real value is their inclusion in the next request.\n *\n * PersistentWriteStream manages propagating this value from responses to the\n * next request.\n */\n lastStreamToken: ByteString = ByteString.EMPTY_BYTE_STRING;\n\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */\n get handshakeComplete(): boolean {\n return this.handshakeComplete_;\n }\n\n // Override of PersistentStream.start\n start(): void {\n this.handshakeComplete_ = false;\n super.start();\n }\n\n protected tearDown(): void {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n }\n\n protected startRpc(\n token: Token | null\n ): Stream<api.WriteRequest, api.WriteResponse> {\n return this.connection.openStream<api.WriteRequest, api.WriteResponse>(\n 'Write',\n token\n );\n }\n\n protected onMessage(responseProto: api.WriteResponse): Promise<void> {\n // Always capture the last stream token.\n assert(\n !!responseProto.streamToken,\n 'Got a write response without a stream token'\n );\n this.lastStreamToken = this.serializer.fromBytes(responseProto.streamToken);\n\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(\n !responseProto.writeResults || responseProto.writeResults.length === 0,\n 'Got mutation results for handshake'\n );\n this.handshakeComplete_ = true;\n return this.listener!.onHandshakeComplete();\n } else {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.backoff.reset();\n\n const results = this.serializer.fromWriteResults(\n responseProto.writeResults,\n responseProto.commitTime\n );\n const commitVersion = this.serializer.fromVersion(\n responseProto.commitTime!\n );\n return this.listener!.onMutationResult(commitVersion, results);\n }\n }\n\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */\n writeHandshake(): void {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed');\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const request: WriteRequest = {};\n request.database = this.serializer.encodedDatabaseId;\n this.sendRequest(request);\n }\n\n /** Sends a group of mutations to the Firestore backend to apply. */\n writeMutations(mutations: Mutation[]): void {\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(\n this.handshakeComplete_,\n 'Handshake must be complete before writing mutations'\n );\n assert(\n this.lastStreamToken.approximateByteSize() > 0,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n streamToken: this.serializer.toBytes(this.lastStreamToken),\n writes: mutations.map(mutation => this.serializer.toMutation(mutation))\n };\n\n this.sendRequest(request);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { CredentialsProvider } from '../api/credentials';\nimport { maybeDocumentMap } from '../model/collections';\nimport { MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation, MutationResult } from '../model/mutation';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { Connection } from './connection';\nimport {\n WatchStreamListener,\n WriteStreamListener,\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\n\nimport { JsonProtoSerializer } from './serializer';\n\n// The generated proto interfaces for these class are missing the database\n// field. So we add it here.\n// TODO(b/36015800): Remove this once the api generator is fixed.\ninterface BatchGetDocumentsRequest extends api.BatchGetDocumentsRequest {\n database?: string;\n}\ninterface CommitRequest extends api.CommitRequest {\n database?: string;\n}\n\n/**\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\n * which provides an interface that is more convenient for the rest of the\n * client SDK architecture to consume.\n */\nexport class Datastore {\n constructor(\n private queue: AsyncQueue,\n private connection: Connection,\n private credentials: CredentialsProvider,\n private serializer: JsonProtoSerializer\n ) {}\n\n newPersistentWriteStream(\n listener: WriteStreamListener\n ): PersistentWriteStream {\n return new PersistentWriteStream(\n this.queue,\n this.connection,\n this.credentials,\n this.serializer,\n listener\n );\n }\n\n newPersistentWatchStream(\n listener: WatchStreamListener\n ): PersistentListenStream {\n return new PersistentListenStream(\n this.queue,\n this.connection,\n this.credentials,\n this.serializer,\n listener\n );\n }\n\n commit(mutations: Mutation[]): Promise<MutationResult[]> {\n const params: CommitRequest = {\n database: this.serializer.encodedDatabaseId,\n writes: mutations.map(m => this.serializer.toMutation(m))\n };\n return this.invokeRPC<CommitRequest, api.CommitResponse>(\n 'Commit',\n params\n ).then(response => {\n return this.serializer.fromWriteResults(\n response.writeResults,\n response.commitTime\n );\n });\n }\n\n lookup(keys: DocumentKey[]): Promise<MaybeDocument[]> {\n const params: BatchGetDocumentsRequest = {\n database: this.serializer.encodedDatabaseId,\n documents: keys.map(k => this.serializer.toName(k))\n };\n return this.invokeStreamingRPC<\n BatchGetDocumentsRequest,\n api.BatchGetDocumentsResponse\n >('BatchGetDocuments', params).then(response => {\n let docs = maybeDocumentMap();\n response.forEach(proto => {\n const doc = this.serializer.fromMaybeDocument(proto);\n docs = docs.insert(doc.key, doc);\n });\n const result: MaybeDocument[] = [];\n keys.forEach(key => {\n const doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n }\n\n /** Gets an auth token and invokes the provided RPC. */\n private invokeRPC<Req, Resp>(rpcName: string, request: Req): Promise<Resp> {\n return this.credentials\n .getToken()\n .then(token => {\n return this.connection.invokeRPC<Req, Resp>(rpcName, request, token);\n })\n .catch((error: FirestoreError) => {\n if (error.code === Code.UNAUTHENTICATED) {\n this.credentials.invalidateToken();\n }\n throw error;\n });\n }\n\n /** Gets an auth token and invokes the provided RPC with streamed results. */\n private invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n request: Req\n ): Promise<Resp[]> {\n return this.credentials\n .getToken()\n .then(token => {\n return this.connection.invokeStreamingRPC<Req, Resp>(\n rpcName,\n request,\n token\n );\n })\n .catch((error: FirestoreError) => {\n if (error.code === Code.UNAUTHENTICATED) {\n this.credentials.invalidateToken();\n }\n throw error;\n });\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * as firestore from '@firebase/firestore-types';\n\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n invalidClassError,\n validateArgType,\n validateNamedArrayAtLeastNumberOfElements\n} from '../util/input_validation';\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n\n/**\n * A FieldPath refers to a field in a document. The path may consist of a single\n * field name (referring to a top-level field in the document), or a list of\n * field names (referring to a nested field in the document).\n */\nexport class FieldPath implements firestore.FieldPath {\n /** Internal representation of a Firestore field path. */\n _internalPath: InternalFieldPath;\n\n /**\n * Creates a FieldPath from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames A list of field names.\n */\n constructor(...fieldNames: string[]) {\n validateNamedArrayAtLeastNumberOfElements(\n 'FieldPath',\n fieldNames,\n 'fieldNames',\n 1\n );\n\n for (let i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field name at argument $(i + 1). ` +\n 'Field names must not be empty.'\n );\n }\n }\n\n this._internalPath = new InternalFieldPath(fieldNames);\n }\n\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n private static readonly _DOCUMENT_ID = new FieldPath(\n InternalFieldPath.keyField().canonicalString()\n );\n\n static documentId(): FieldPath {\n return FieldPath._DOCUMENT_ID;\n }\n\n isEqual(other: firestore.FieldPath): boolean {\n if (!(other instanceof FieldPath)) {\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\n }\n return this._internalPath.isEqual(other._internalPath);\n }\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */\nconst RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n\n/**\n * Parses a field path string into a FieldPath, treating dots as separators.\n */\nexport function fromDotSeparatedString(path: string): FieldPath {\n const found = path.search(RESERVED);\n if (found >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not contain ` +\n `'~', '*', '/', '[', or ']'`\n );\n }\n try {\n return new FieldPath(...path.split('.'));\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid field path (${path}). Paths must not be empty, ` +\n `begin with '.', end with '.', or contain '..'`\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * as firestore from '@firebase/firestore-types';\n\nimport { makeConstructorPrivate } from '../util/api';\nimport {\n validateArgType,\n validateAtLeastNumberOfArgs,\n validateExactNumberOfArgs,\n validateNoArgs\n} from '../util/input_validation';\n\n/**\n * An opaque base class for FieldValue sentinel objects in our public API,\n * with public static methods for creating said sentinel objects.\n */\nexport abstract class FieldValueImpl implements firestore.FieldValue {\n protected constructor(readonly _methodName: string) {}\n\n static delete(): FieldValueImpl {\n validateNoArgs('FieldValue.delete', arguments);\n return DeleteFieldValueImpl.instance;\n }\n\n static serverTimestamp(): FieldValueImpl {\n validateNoArgs('FieldValue.serverTimestamp', arguments);\n return ServerTimestampFieldValueImpl.instance;\n }\n\n static arrayUnion(...elements: unknown[]): FieldValueImpl {\n validateAtLeastNumberOfArgs('FieldValue.arrayUnion', arguments, 1);\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we need access to the Firestore instance.\n return new ArrayUnionFieldValueImpl(elements);\n }\n\n static arrayRemove(...elements: unknown[]): FieldValueImpl {\n validateAtLeastNumberOfArgs('FieldValue.arrayRemove', arguments, 1);\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we need access to the Firestore instance.\n return new ArrayRemoveFieldValueImpl(elements);\n }\n\n static increment(n: number): FieldValueImpl {\n validateArgType('FieldValue.increment', 'number', 1, n);\n validateExactNumberOfArgs('FieldValue.increment', arguments, 1);\n return new NumericIncrementFieldValueImpl(n);\n }\n\n isEqual(other: FieldValueImpl): boolean {\n return this === other;\n }\n}\n\nexport class DeleteFieldValueImpl extends FieldValueImpl {\n private constructor() {\n super('FieldValue.delete');\n }\n /** Singleton instance. */\n static instance = new DeleteFieldValueImpl();\n}\n\nexport class ServerTimestampFieldValueImpl extends FieldValueImpl {\n private constructor() {\n super('FieldValue.serverTimestamp');\n }\n /** Singleton instance. */\n static instance = new ServerTimestampFieldValueImpl();\n}\n\nexport class ArrayUnionFieldValueImpl extends FieldValueImpl {\n constructor(readonly _elements: unknown[]) {\n super('FieldValue.arrayUnion');\n }\n}\n\nexport class ArrayRemoveFieldValueImpl extends FieldValueImpl {\n constructor(readonly _elements: unknown[]) {\n super('FieldValue.arrayRemove');\n }\n}\n\nexport class NumericIncrementFieldValueImpl extends FieldValueImpl {\n constructor(readonly _operand: number) {\n super('FieldValue.increment');\n }\n}\n\n// Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\nexport const PublicFieldValue = makeConstructorPrivate(\n FieldValueImpl,\n 'Use FieldValue.<field>() instead.'\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * as firestore from '@firebase/firestore-types';\n\nimport { Timestamp } from '../api/timestamp';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport {\n FieldValue,\n NumberValue,\n ObjectValue,\n ArrayValue,\n BlobValue,\n BooleanValue,\n DoubleValue,\n GeoPointValue,\n IntegerValue,\n NullValue,\n RefValue,\n StringValue,\n TimestampValue\n} from '../model/field_value';\n\nimport {\n FieldMask,\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation,\n TransformMutation\n} from '../model/mutation';\nimport { FieldPath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { isPlainObject, valueDescription } from '../util/input_validation';\nimport { primitiveComparator } from '../util/misc';\nimport { Dict, forEach, isEmpty } from '../util/obj';\nimport { SortedMap } from '../util/sorted_map';\nimport * as typeUtils from '../util/types';\n\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport { SortedSet } from '../util/sorted_set';\nimport { Blob } from './blob';\nimport {\n FieldPath as ExternalFieldPath,\n fromDotSeparatedString\n} from './field_path';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n FieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './field_value';\nimport { GeoPoint } from './geo_point';\n\nconst RESERVED_FIELD_REGEX = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */\nexport class ParsedSetData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask | null,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutations(key: DocumentKey, precondition: Precondition): Mutation[] {\n const mutations = [] as Mutation[];\n if (this.fieldMask !== null) {\n mutations.push(\n new PatchMutation(key, this.data, this.fieldMask, precondition)\n );\n } else {\n mutations.push(new SetMutation(key, this.data, precondition));\n }\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\nexport class ParsedUpdateData {\n constructor(\n readonly data: ObjectValue,\n readonly fieldMask: FieldMask,\n readonly fieldTransforms: FieldTransform[]\n ) {}\n\n toMutations(key: DocumentKey, precondition: Precondition): Mutation[] {\n const mutations = [\n new PatchMutation(key, this.data, this.fieldMask, precondition)\n ] as Mutation[];\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n return mutations;\n }\n}\n\n/*\n * Represents what type of API method provided the data being parsed; useful\n * for determining which error conditions apply during parsing and providing\n * better error messages.\n */\nconst enum UserDataSource {\n Set,\n Update,\n MergeSet,\n /**\n * Indicates the source is a where clause, cursor bound, arrayUnion()\n * element, etc. Of note, isWrite(source) will return false.\n */\n Argument,\n /**\n * Indicates that the source is an Argument that may directly contain nested\n * arrays (e.g. the operand of an `in` query).\n */\n ArrayArgument\n}\n\nfunction isWrite(dataSource: UserDataSource): boolean {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n case UserDataSource.MergeSet: // fall through\n case UserDataSource.Update:\n return true;\n case UserDataSource.Argument:\n case UserDataSource.ArrayArgument:\n return false;\n default:\n throw fail(`Unexpected case for UserDataSource: ${dataSource}`);\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */\nclass ParseContext {\n readonly fieldTransforms: FieldTransform[];\n readonly fieldMask: FieldPath[];\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param dataSource Indicates what kind of API method this data came from.\n * @param methodName The name of the method the user called to create this\n * ParseContext.\n * @param path A path within the object being parsed. This could be an empty\n * path (in which case the context represents the root of the data being\n * parsed), or a nonempty path (indicating the context represents a nested\n * location within the data).\n * @param arrayElement Whether or not this context corresponds to an element\n * of an array.\n * @param fieldTransforms A mutable list of field transforms encountered while\n * parsing the data.\n * @param fieldMask A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(\n readonly dataSource: UserDataSource,\n readonly methodName: string,\n readonly path: FieldPath | null,\n readonly arrayElement?: boolean,\n fieldTransforms?: FieldTransform[],\n fieldMask?: FieldPath[]\n ) {\n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n childContextForField(field: string): ParseContext {\n const childPath = this.path == null ? null : this.path.child(field);\n const context = new ParseContext(\n this.dataSource,\n this.methodName,\n childPath,\n /*arrayElement=*/ false,\n this.fieldTransforms,\n this.fieldMask\n );\n context.validatePathSegment(field);\n return context;\n }\n\n childContextForFieldPath(field: FieldPath): ParseContext {\n const childPath = this.path == null ? null : this.path.child(field);\n const context = new ParseContext(\n this.dataSource,\n this.methodName,\n childPath,\n /*arrayElement=*/ false,\n this.fieldTransforms,\n this.fieldMask\n );\n context.validatePath();\n return context;\n }\n\n childContextForArray(index: number): ParseContext {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(\n this.dataSource,\n this.methodName,\n /*path=*/ null,\n /*arrayElement=*/ true,\n this.fieldTransforms,\n this.fieldMask\n );\n }\n\n createError(reason: string): Error {\n const fieldDescription =\n this.path === null || this.path.isEmpty()\n ? ''\n : ` (found in field ${this.path.toString()})`;\n return new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${this.methodName}() called with invalid data. ` +\n reason +\n fieldDescription\n );\n }\n\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n contains(fieldPath: FieldPath): boolean {\n return (\n this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined ||\n this.fieldTransforms.find(transform =>\n fieldPath.isPrefixOf(transform.field)\n ) !== undefined\n );\n }\n\n private validatePath(): void {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n for (let i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n }\n\n private validatePathSegment(segment: string): void {\n if (segment.length === 0) {\n throw this.createError('Document fields must not be empty');\n }\n if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) {\n throw this.createError('Document fields cannot begin and end with \"__\"');\n }\n }\n}\n/**\n * An interface that allows arbitrary pre-converting of user data. This\n * abstraction allows for, e.g.:\n * * The public API to convert DocumentReference objects to DocRef objects,\n * avoiding a circular dependency between user_data_converter.ts and\n * database.ts\n * * Tests to convert test-only sentinels (e.g. '<DELETE>') into types\n * compatible with UserDataConverter.\n *\n * Returns the converted value (can return back the input to act as a no-op).\n *\n * It can also throw an Error which will be wrapped into a friendly message.\n */\nexport type DataPreConverter = (input: unknown) => unknown;\n\n/**\n * A placeholder object for DocumentReferences in this file, in order to\n * avoid a circular dependency. See the comments for `DataPreConverter` for\n * the full context.\n */\nexport class DocumentKeyReference {\n constructor(public databaseId: DatabaseId, public key: DocumentKey) {}\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */\nexport class UserDataConverter {\n constructor(private preConverter: DataPreConverter) {}\n\n /** Parse document data from a non-merge set() call. */\n parseSetData(methodName: string, input: unknown): ParsedSetData {\n const context = new ParseContext(\n UserDataSource.Set,\n methodName,\n FieldPath.EMPTY_PATH\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const updateData = this.parseData(input, context);\n\n return new ParsedSetData(\n updateData as ObjectValue,\n /* fieldMask= */ null,\n context.fieldTransforms\n );\n }\n\n /** Parse document data from a set() call with '{merge:true}'. */\n parseMergeData(\n methodName: string,\n input: unknown,\n fieldPaths?: Array<string | firestore.FieldPath>\n ): ParsedSetData {\n const context = new ParseContext(\n UserDataSource.MergeSet,\n methodName,\n FieldPath.EMPTY_PATH\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n const updateData = this.parseData(input, context) as ObjectValue;\n let fieldMask: FieldMask;\n let fieldTransforms: FieldTransform[];\n\n if (!fieldPaths) {\n fieldMask = FieldMask.fromArray(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else {\n let validatedFieldPaths = new SortedSet<FieldPath>(FieldPath.comparator);\n\n for (const stringOrFieldPath of fieldPaths) {\n let fieldPath: FieldPath;\n\n if (stringOrFieldPath instanceof ExternalFieldPath) {\n fieldPath = stringOrFieldPath._internalPath;\n } else if (typeof stringOrFieldPath === 'string') {\n fieldPath = fieldPathFromDotSeparatedString(\n methodName,\n stringOrFieldPath\n );\n } else {\n throw fail(\n 'Expected stringOrFieldPath to be a string or a FieldPath'\n );\n }\n\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Field '${fieldPath}' is specified in your field mask but missing from your input data.`\n );\n }\n\n validatedFieldPaths = validatedFieldPaths.add(fieldPath);\n }\n\n fieldMask = FieldMask.fromSet(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(transform =>\n fieldMask.covers(transform.field)\n );\n }\n return new ParsedSetData(\n updateData as ObjectValue,\n fieldMask,\n fieldTransforms\n );\n }\n\n /** Parse update data from an update() call. */\n parseUpdateData(methodName: string, input: unknown): ParsedUpdateData {\n const context = new ParseContext(\n UserDataSource.Update,\n methodName,\n FieldPath.EMPTY_PATH\n );\n validatePlainObject('Data must be an object, but it was:', context, input);\n\n let fieldMaskPaths = new SortedSet<FieldPath>(FieldPath.comparator);\n const updateData = ObjectValue.newBuilder();\n forEach(input as Dict<unknown>, (key, value) => {\n const path = fieldPathFromDotSeparatedString(methodName, key);\n\n const childContext = context.childContextForFieldPath(path);\n value = this.runPreConverter(value, childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths = fieldMaskPaths.add(path);\n } else {\n const parsedValue = this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths = fieldMaskPaths.add(path);\n updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = FieldMask.fromSet(fieldMaskPaths);\n return new ParsedUpdateData(\n updateData.build(),\n mask,\n context.fieldTransforms\n );\n }\n\n /** Parse update data from a list of field/value arguments. */\n parseUpdateVarargs(\n methodName: string,\n field: string | ExternalFieldPath,\n value: unknown,\n moreFieldsAndValues: unknown[]\n ): ParsedUpdateData {\n const context = new ParseContext(\n UserDataSource.Update,\n methodName,\n FieldPath.EMPTY_PATH\n );\n const keys = [fieldPathFromArgument(methodName, field)];\n const values = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() needs to be called with an even number ` +\n 'of arguments that alternate between field names and values.'\n );\n }\n\n for (let i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(\n fieldPathFromArgument(\n methodName,\n moreFieldsAndValues[i] as string | ExternalFieldPath\n )\n );\n values.push(moreFieldsAndValues[i + 1]);\n }\n\n let fieldMaskPaths = new SortedSet<FieldPath>(FieldPath.comparator);\n const updateData = ObjectValue.newBuilder();\n\n for (let i = 0; i < keys.length; ++i) {\n const path = keys[i];\n const childContext = context.childContextForFieldPath(path);\n const value = this.runPreConverter(values[i], childContext);\n if (value instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths = fieldMaskPaths.add(path);\n } else {\n const parsedValue = this.parseData(value, childContext);\n if (parsedValue != null) {\n fieldMaskPaths = fieldMaskPaths.add(path);\n updateData.set(path, parsedValue);\n }\n }\n }\n\n const mask = FieldMask.fromSet(fieldMaskPaths);\n return new ParsedUpdateData(\n updateData.build(),\n mask,\n context.fieldTransforms\n );\n }\n\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\n parseQueryValue(\n methodName: string,\n input: unknown,\n allowArrays = false\n ): FieldValue {\n const context = new ParseContext(\n allowArrays ? UserDataSource.ArrayArgument : UserDataSource.Argument,\n methodName,\n FieldPath.EMPTY_PATH\n );\n const parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(\n context.fieldTransforms.length === 0,\n 'Field transforms should have been disallowed.'\n );\n return parsed;\n }\n\n /** Sends data through this.preConverter, handling any thrown errors. */\n private runPreConverter(input: unknown, context: ParseContext): unknown {\n try {\n return this.preConverter(input);\n } catch (e) {\n const message = errorMessage(e);\n throw context.createError(message);\n }\n }\n\n /**\n * Internal helper for parsing user data.\n *\n * @param input Data to be parsed.\n * @param context A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @return The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */\n private parseData(input: unknown, context: ParseContext): FieldValue | null {\n input = this.runPreConverter(input, context);\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input as Dict<unknown>, context);\n } else if (input instanceof FieldValueImpl) {\n // FieldValues usually parse into transforms (except FieldValue.delete())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n this.parseSentinelFieldValue(input, context);\n return null;\n } else {\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n if (context.path) {\n context.fieldMask.push(context.path);\n }\n\n if (input instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (\n context.arrayElement &&\n context.dataSource !== UserDataSource.ArrayArgument\n ) {\n throw context.createError('Nested arrays are not supported');\n }\n return this.parseArray(input as unknown[], context);\n } else {\n return this.parseScalarValue(input, context);\n }\n }\n }\n\n private parseObject(obj: Dict<unknown>, context: ParseContext): FieldValue {\n let result = new SortedMap<string, FieldValue>(primitiveComparator);\n\n if (isEmpty(obj)) {\n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n if (context.path && context.path.length > 0) {\n context.fieldMask.push(context.path);\n }\n } else {\n forEach(obj, (key: string, val: unknown) => {\n const parsedValue = this.parseData(\n val,\n context.childContextForField(key)\n );\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n }\n\n return new ObjectValue(result);\n }\n\n private parseArray(array: unknown[], context: ParseContext): FieldValue {\n const result = [] as FieldValue[];\n let entryIndex = 0;\n for (const entry of array) {\n let parsedEntry = this.parseData(\n entry,\n context.childContextForArray(entryIndex)\n );\n if (parsedEntry == null) {\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n parsedEntry = NullValue.INSTANCE;\n }\n result.push(parsedEntry);\n entryIndex++;\n }\n return new ArrayValue(result);\n }\n\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n private parseSentinelFieldValue(\n value: FieldValueImpl,\n context: ParseContext\n ): void {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(\n `${value._methodName}() can only be used with update() and set()`\n );\n }\n if (context.path === null) {\n throw context.createError(\n `${value._methodName}() is not currently supported inside arrays`\n );\n }\n\n if (value instanceof DeleteFieldValueImpl) {\n if (context.dataSource === UserDataSource.MergeSet) {\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n context.fieldMask.push(context.path);\n } else if (context.dataSource === UserDataSource.Update) {\n assert(\n context.path.length > 0,\n 'FieldValue.delete() at the top level should have already' +\n ' been handled.'\n );\n throw context.createError(\n 'FieldValue.delete() can only appear at the top level ' +\n 'of your update data'\n );\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError(\n 'FieldValue.delete() cannot be used with set() unless you pass ' +\n '{merge:true}'\n );\n }\n } else if (value instanceof ServerTimestampFieldValueImpl) {\n context.fieldTransforms.push(\n new FieldTransform(context.path, ServerTimestampTransform.instance)\n );\n } else if (value instanceof ArrayUnionFieldValueImpl) {\n const parsedElements = this.parseArrayTransformElements(\n value._methodName,\n value._elements\n );\n const arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n context.fieldTransforms.push(\n new FieldTransform(context.path, arrayUnion)\n );\n } else if (value instanceof ArrayRemoveFieldValueImpl) {\n const parsedElements = this.parseArrayTransformElements(\n value._methodName,\n value._elements\n );\n const arrayRemove = new ArrayRemoveTransformOperation(parsedElements);\n context.fieldTransforms.push(\n new FieldTransform(context.path, arrayRemove)\n );\n } else if (value instanceof NumericIncrementFieldValueImpl) {\n const operand = this.parseQueryValue(\n 'FieldValue.increment',\n value._operand\n ) as NumberValue;\n const numericIncrement = new NumericIncrementTransformOperation(operand);\n context.fieldTransforms.push(\n new FieldTransform(context.path, numericIncrement)\n );\n } else {\n fail('Unknown FieldValue type: ' + value);\n }\n }\n\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @return The parsed value\n */\n private parseScalarValue(value: unknown, context: ParseContext): FieldValue {\n if (value === null) {\n return NullValue.INSTANCE;\n } else if (typeof value === 'number') {\n if (typeUtils.isSafeInteger(value)) {\n return new IntegerValue(value);\n } else {\n return new DoubleValue(value);\n }\n } else if (typeof value === 'boolean') {\n return BooleanValue.of(value);\n } else if (typeof value === 'string') {\n return new StringValue(value);\n } else if (value instanceof Date) {\n return new TimestampValue(Timestamp.fromDate(value));\n } else if (value instanceof Timestamp) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n return new TimestampValue(\n new Timestamp(\n value.seconds,\n Math.floor(value.nanoseconds / 1000) * 1000\n )\n );\n } else if (value instanceof GeoPoint) {\n return new GeoPointValue(value);\n } else if (value instanceof Blob) {\n return new BlobValue(value);\n } else if (value instanceof DocumentKeyReference) {\n return new RefValue(value.databaseId, value.key);\n } else {\n throw context.createError(\n `Unsupported field value: ${valueDescription(value)}`\n );\n }\n }\n\n private parseArrayTransformElements(\n methodName: string,\n elements: unknown[]\n ): FieldValue[] {\n return elements.map((element, i) => {\n // Although array transforms are used with writes, the actual elements\n // being unioned or removed are not considered writes since they cannot\n // contain any FieldValue sentinels, etc.\n const context = new ParseContext(\n UserDataSource.Argument,\n methodName,\n FieldPath.EMPTY_PATH\n );\n return this.parseData(element, context.childContextForArray(i))!;\n });\n }\n}\n\n/**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */\nfunction looksLikeJsonObject(input: unknown): boolean {\n return (\n typeof input === 'object' &&\n input !== null &&\n !(input instanceof Array) &&\n !(input instanceof Date) &&\n !(input instanceof Timestamp) &&\n !(input instanceof GeoPoint) &&\n !(input instanceof Blob) &&\n !(input instanceof DocumentKeyReference) &&\n !(input instanceof FieldValueImpl)\n );\n}\n\nfunction validatePlainObject(\n message: string,\n context: ParseContext,\n input: unknown\n): void {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n const description = valueDescription(input);\n if (description === 'an object') {\n // Massage the error if it was an object.\n throw context.createError(message + ' a custom object');\n } else {\n throw context.createError(message + ' ' + description);\n }\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */\nexport function fieldPathFromArgument(\n methodName: string,\n path: string | ExternalFieldPath\n): FieldPath {\n if (path instanceof ExternalFieldPath) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n const message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() called with invalid data. ${message}`\n );\n }\n}\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName The publicly visible method name\n * @param path The dot-separated string form of a field path which will be split\n * on dots.\n */\nfunction fieldPathFromDotSeparatedString(\n methodName: string,\n path: string\n): FieldPath {\n try {\n return fromDotSeparatedString(path)._internalPath;\n } catch (e) {\n const message = errorMessage(e);\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function ${methodName}() called with invalid data. ${message}`\n );\n }\n}\n\n/**\n * Extracts the message from a caught exception, which should be an Error object\n * though JS doesn't guarantee that.\n */\nfunction errorMessage(error: Error | object): string {\n return error instanceof Error ? error.message : error.toString();\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { QueryResult } from '../local/local_store';\nimport {\n documentKeySet,\n DocumentKeySet,\n MaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { assert, fail } from '../util/assert';\n\nimport { Query } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges The doc changes to apply to this view.\n * @param previousChanges If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @return a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: MaybeDocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.hasLimitToFirst() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.hasLimitToLast() && oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal(\n (key: DocumentKey, newMaybeDoc: MaybeDocument) => {\n const oldDoc = oldDocumentSet.get(key);\n let newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\n if (newDoc) {\n assert(\n key.isEqual(newDoc.key),\n 'Mismatching keys found in document changes: ' +\n key +\n ' != ' +\n newDoc.key\n );\n newDoc = this.query.matches(newDoc) ? newDoc : null;\n }\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data().isEqual(newDoc.data());\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.query.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.query.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n }\n );\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.hasLimitToFirst() || this.query.hasLimitToLast()) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc = this.query.hasLimitToFirst()\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n assert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges The set of changes to make to the view's docs.\n * @param updateLimboDocuments Whether to update limbo documents based on this\n * change.\n * @param targetChange A target change to apply for computing limbo docs and\n * sync state.\n * @return A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n updateLimboDocuments: boolean,\n targetChange?: TargetChange\n ): ViewChange {\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.query.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n const limboChanges = updateLimboDocuments\n ? this.updateLimboDocuments()\n : [];\n const synced = this.limboDocuments.size === 0 && this.current;\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* updateLimboDocuments= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key =>\n assert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n )\n );\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @return The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /*updateLimboDocuments=*/ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n\n return order(c1) - order(c2);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ParsedSetData, ParsedUpdateData } from '../api/user_data_converter';\nimport { documentVersionMap } from '../model/collections';\nimport { Document, NoDocument, MaybeDocument } from '../model/document';\n\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport { Datastore } from '../remote/datastore';\nimport { fail, assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = documentVersionMap();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastWriteError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set<DocumentKey> = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise<MaybeDocument[]> {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n }\n const docs = await this.datastore.lookup(keys);\n docs.forEach(doc => {\n if (doc instanceof NoDocument || doc instanceof Document) {\n this.recordVersion(doc);\n } else {\n fail('Document in a transaction was a ' + doc.constructor.name);\n }\n });\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutations(key, this.precondition(key)));\n this.writtenDocs.add(key);\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastWriteError = e;\n }\n this.writtenDocs.add(key);\n }\n\n delete(key: DocumentKey): void {\n this.write([new DeleteMutation(key, this.precondition(key))]);\n this.writtenDocs.add(key);\n }\n\n async commit(): Promise<void> {\n this.ensureCommitNotCalled();\n\n if (this.lastWriteError) {\n throw this.lastWriteError;\n }\n let unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten = unwritten.remove(mutation.key);\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((key, _version) => {\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await this.datastore.commit(this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: MaybeDocument): void {\n let docVersion: SnapshotVersion;\n\n if (doc instanceof Document) {\n docVersion = doc.version;\n } else if (doc instanceof NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = SnapshotVersion.forDeletedDoc();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n const existingVersion = this.readVersions.get(doc.key);\n if (existingVersion !== null) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key);\n if (!this.writtenDocs.has(key) && version) {\n return Precondition.updateTime(version);\n } else {\n return Precondition.NONE;\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key);\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key) && version) {\n if (version.isEqual(SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutations: Mutation[]): void {\n this.ensureCommitNotCalled();\n this.mutations = this.mutations.concat(mutations);\n }\n\n private ensureCommitNotCalled(): void {\n assert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { OnlineState } from '../core/types';\nimport { assert } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { CancelablePromise } from '../util/promise';\n\nconst LOG_TAG = 'OnlineStateTracker';\n\n// To deal with transient failures, we allow multiple stream attempts before\n// giving up and transitioning from OnlineState.Unknown to Offline.\n// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394.\n// @jdimond thinks that bug is sufficiently fixed so that we can set this back\n// to 1. If that works okay, we could potentially remove this logic entirely.\nconst MAX_WATCH_STREAM_FAILURES = 1;\n\n// To deal with stream attempts that don't succeed or fail in a timely manner,\n// we have a timeout for OnlineState to reach Online or Offline.\n// If the timeout is reached, we transition to Offline rather than waiting\n// indefinitely.\nconst ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nexport class OnlineStateTracker {\n /** The current OnlineState. */\n private state = OnlineState.Unknown;\n\n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n private watchStreamFailures = 0;\n\n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n private onlineStateTimer: CancelablePromise<void> | null = null;\n\n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n private shouldWarnClientIsOffline = true;\n\n constructor(\n private asyncQueue: AsyncQueue,\n private onlineStateHandler: (onlineState: OnlineState) => void\n ) {}\n\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */\n handleWatchStreamStart(): void {\n if (this.watchStreamFailures === 0) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n assert(\n this.onlineStateTimer === null,\n `onlineStateTimer shouldn't be started yet`\n );\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(\n TimerId.OnlineStateTimeout,\n ONLINE_STATE_TIMEOUT_MS,\n () => {\n this.onlineStateTimer = null;\n assert(\n this.state === OnlineState.Unknown,\n 'Timer should be canceled if we transitioned to a different state.'\n );\n this.logClientOfflineWarningIfNecessary(\n `Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` +\n `seconds.`\n );\n this.setAndBroadcast(OnlineState.Offline);\n\n // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n\n return Promise.resolve();\n }\n );\n }\n }\n\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */\n handleWatchStreamFailure(error: FirestoreError): void {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown);\n\n // To get to OnlineState.Online, set() must have been called which would\n // have reset our heuristics.\n assert(this.watchStreamFailures === 0, 'watchStreamFailures must be 0');\n assert(this.onlineStateTimer === null, 'onlineStateTimer must be null');\n } else {\n this.watchStreamFailures++;\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n\n this.logClientOfflineWarningIfNecessary(\n `Connection failed ${MAX_WATCH_STREAM_FAILURES} ` +\n `times. Most recent error: ${error.toString()}`\n );\n\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\n }\n\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */\n set(newState: OnlineState): void {\n this.clearOnlineStateTimer();\n this.watchStreamFailures = 0;\n\n if (newState === OnlineState.Online) {\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.shouldWarnClientIsOffline = false;\n }\n\n this.setAndBroadcast(newState);\n }\n\n private setAndBroadcast(newState: OnlineState): void {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n }\n\n private logClientOfflineWarningIfNecessary(details: string): void {\n const message =\n `Could not reach Cloud Firestore backend. ${details}\\n` +\n `This typically indicates that your device does not have a healthy ` +\n `Internet connection at the moment. The client will operate in offline ` +\n `mode until it is able to successfully connect to the backend.`;\n if (this.shouldWarnClientIsOffline) {\n log.error(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n log.debug(LOG_TAG, message);\n }\n }\n\n private clearOnlineStateTimer(): void {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = null;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SnapshotVersion } from '../core/snapshot_version';\nimport { Transaction } from '../core/transaction';\nimport { OnlineState, TargetId } from '../core/types';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport { MutationResult } from '../model/mutation';\nimport {\n BATCHID_UNKNOWN,\n MutationBatch,\n MutationBatchResult\n} from '../model/mutation_batch';\nimport { assert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport * as objUtils from '../util/obj';\n\nimport { DocumentKeySet } from '../model/collections';\nimport { AsyncQueue } from '../util/async_queue';\nimport { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\nimport { Datastore } from './datastore';\nimport { OnlineStateTracker } from './online_state_tracker';\nimport {\n PersistentListenStream,\n PersistentWriteStream\n} from './persistent_stream';\nimport { RemoteSyncer } from './remote_syncer';\nimport { isPermanentError, isPermanentWriteError } from './rpc_error';\nimport {\n DocumentWatchChange,\n ExistenceFilterChange,\n TargetMetadataProvider,\n WatchChange,\n WatchChangeAggregator,\n WatchTargetChange,\n WatchTargetChangeState\n} from './watch_change';\nimport { ByteString } from '../util/byte_string';\n\nconst LOG_TAG = 'RemoteStore';\n\n// TODO(b/35853402): Negotiate this with the stream.\nconst MAX_PENDING_WRITES = 10;\n\n/**\n * RemoteStore - An interface to remotely stored data, basically providing a\n * wrapper around the Datastore that is more reliable for the rest of the\n * system.\n *\n * RemoteStore is responsible for maintaining the connection to the server.\n * - maintaining a list of active listens.\n * - reconnecting when the connection is dropped.\n * - resuming all the active listens on reconnect.\n *\n * RemoteStore handles all incoming events from the Datastore.\n * - listening to the watch stream and repackaging the events as RemoteEvents\n * - notifying SyncEngine of any changes to the active listens.\n *\n * RemoteStore takes writes from other components and handles them reliably.\n * - pulling pending mutations from LocalStore and sending them to Datastore.\n * - retrying mutations that failed because of network problems.\n * - acking mutations to the SyncEngine once they are accepted or rejected.\n */\nexport class RemoteStore implements TargetMetadataProvider {\n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n private writePipeline: MutationBatch[] = [];\n\n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n private listenTargets: { [targetId: number]: TargetData } = {};\n\n private connectivityMonitor: ConnectivityMonitor;\n private watchStream: PersistentListenStream;\n private writeStream: PersistentWriteStream;\n private watchChangeAggregator: WatchChangeAggregator | null = null;\n\n /**\n * Set to true by enableNetwork() and false by disableNetwork() and indicates\n * the user-preferred network state.\n */\n private networkEnabled = false;\n\n private isPrimary = false;\n\n private onlineStateTracker: OnlineStateTracker;\n\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n private localStore: LocalStore,\n /** The client-side proxy for interacting with the backend. */\n private datastore: Datastore,\n asyncQueue: AsyncQueue,\n onlineStateHandler: (onlineState: OnlineState) => void,\n connectivityMonitor: ConnectivityMonitor\n ) {\n this.connectivityMonitor = connectivityMonitor;\n this.connectivityMonitor.addCallback((status: NetworkStatus) => {\n asyncQueue.enqueueAndForget(async () => {\n if (this.canUseNetwork()) {\n log.debug(\n LOG_TAG,\n 'Restarting streams for network reachability change.'\n );\n await this.restartNetwork();\n }\n });\n });\n\n this.onlineStateTracker = new OnlineStateTracker(\n asyncQueue,\n onlineStateHandler\n );\n\n // Create streams (but note they're not started yet).\n this.watchStream = this.datastore.newPersistentWatchStream({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n\n this.writeStream = this.datastore.newPersistentWriteStream({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n }\n\n /**\n * SyncEngine to notify of watch and write events. This must be set\n * immediately after construction.\n */\n syncEngine!: RemoteSyncer;\n\n /**\n * Starts up the remote store, creating streams, restoring state from\n * LocalStore, etc.\n */\n start(): Promise<void> {\n return this.enableNetwork();\n }\n\n /** Re-enables the network. Idempotent. */\n async enableNetwork(): Promise<void> {\n this.networkEnabled = true;\n\n if (this.canUseNetwork()) {\n this.writeStream.lastStreamToken = await this.localStore.getLastStreamToken();\n\n if (this.shouldStartWatchStream()) {\n this.startWatchStream();\n } else {\n this.onlineStateTracker.set(OnlineState.Unknown);\n }\n\n // This will start the write stream if necessary.\n await this.fillWritePipeline();\n }\n }\n\n /**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */\n async disableNetwork(): Promise<void> {\n this.networkEnabled = false;\n await this.disableNetworkInternal();\n\n // Set the OnlineState to Offline so get()s return from cache, etc.\n this.onlineStateTracker.set(OnlineState.Offline);\n }\n\n private async disableNetworkInternal(): Promise<void> {\n await this.writeStream.stop();\n await this.watchStream.stop();\n\n if (this.writePipeline.length > 0) {\n log.debug(\n LOG_TAG,\n `Stopping write stream with ${this.writePipeline.length} pending writes`\n );\n this.writePipeline = [];\n }\n\n this.cleanUpWatchStreamState();\n }\n\n async shutdown(): Promise<void> {\n log.debug(LOG_TAG, 'RemoteStore shutting down.');\n this.networkEnabled = false;\n await this.disableNetworkInternal();\n this.connectivityMonitor.shutdown();\n\n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n this.onlineStateTracker.set(OnlineState.Unknown);\n }\n\n /**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\n listen(targetData: TargetData): void {\n if (objUtils.contains(this.listenTargets, targetData.targetId)) {\n return;\n }\n\n // Mark this as something the client is currently listening for.\n this.listenTargets[targetData.targetId] = targetData;\n\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n } else if (this.watchStream.isOpen()) {\n this.sendWatchRequest(targetData);\n }\n }\n\n /**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */\n unlisten(targetId: TargetId): void {\n assert(\n objUtils.contains(this.listenTargets, targetId),\n `unlisten called on target no currently watched: ${targetId}`\n );\n\n delete this.listenTargets[targetId];\n if (this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\n }\n\n if (objUtils.isEmpty(this.listenTargets)) {\n if (this.watchStream.isOpen()) {\n this.watchStream.markIdle();\n } else if (this.canUseNetwork()) {\n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n this.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n }\n\n /** {@link TargetMetadataProvider.getTargetDataForTarget} */\n getTargetDataForTarget(targetId: TargetId): TargetData | null {\n return this.listenTargets[targetId] || null;\n }\n\n /** {@link TargetMetadataProvider.getRemoteKeysForTarget} */\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet {\n return this.syncEngine.getRemoteKeysForTarget(targetId);\n }\n\n /**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */\n private sendWatchRequest(targetData: TargetData): void {\n this.watchChangeAggregator!.recordPendingTargetRequest(targetData.targetId);\n this.watchStream.watch(targetData);\n }\n\n /**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */\n private sendUnwatchRequest(targetId: TargetId): void {\n this.watchChangeAggregator!.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n }\n\n private startWatchStream(): void {\n assert(\n this.shouldStartWatchStream(),\n 'startWatchStream() called when shouldStartWatchStream() is false.'\n );\n\n this.watchChangeAggregator = new WatchChangeAggregator(this);\n this.watchStream.start();\n this.onlineStateTracker.handleWatchStreamStart();\n }\n\n /**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */\n private shouldStartWatchStream(): boolean {\n return (\n this.canUseNetwork() &&\n !this.watchStream.isStarted() &&\n !objUtils.isEmpty(this.listenTargets)\n );\n }\n\n canUseNetwork(): boolean {\n return this.isPrimary && this.networkEnabled;\n }\n\n private cleanUpWatchStreamState(): void {\n this.watchChangeAggregator = null;\n }\n\n private async onWatchStreamOpen(): Promise<void> {\n objUtils.forEachNumber(this.listenTargets, (targetId, targetData) => {\n this.sendWatchRequest(targetData);\n });\n }\n\n private async onWatchStreamClose(error?: FirestoreError): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n assert(\n !this.shouldStartWatchStream(),\n 'Watch stream was stopped gracefully while still needed.'\n );\n }\n\n this.cleanUpWatchStreamState();\n\n // If we still need the watch stream, retry the connection.\n if (this.shouldStartWatchStream()) {\n this.onlineStateTracker.handleWatchStreamFailure(error!);\n\n this.startWatchStream();\n } else {\n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n this.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n\n private async onWatchStreamChange(\n watchChange: WatchChange,\n snapshotVersion: SnapshotVersion\n ): Promise<void> {\n // Mark the client as online since we got a message from the server\n this.onlineStateTracker.set(OnlineState.Online);\n\n if (\n watchChange instanceof WatchTargetChange &&\n watchChange.state === WatchTargetChangeState.Removed &&\n watchChange.cause\n ) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return this.handleTargetError(watchChange);\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n this.watchChangeAggregator!.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n this.watchChangeAggregator!.handleExistenceFilter(watchChange);\n } else {\n assert(\n watchChange instanceof WatchTargetChange,\n 'Expected watchChange to be an instance of WatchTargetChange'\n );\n this.watchChangeAggregator!.handleTargetChange(watchChange);\n }\n\n if (!snapshotVersion.isEqual(SnapshotVersion.MIN)) {\n const lastRemoteSnapshotVersion = await this.localStore.getLastRemoteSnapshotVersion();\n if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) {\n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.MIN.\n await this.raiseWatchSnapshot(snapshotVersion);\n }\n }\n }\n\n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n private raiseWatchSnapshot(snapshotVersion: SnapshotVersion): Promise<void> {\n assert(\n !snapshotVersion.isEqual(SnapshotVersion.MIN),\n \"Can't raise event for unknown SnapshotVersion\"\n );\n const remoteEvent = this.watchChangeAggregator!.createRemoteEvent(\n snapshotVersion\n );\n\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n objUtils.forEachNumber(remoteEvent.targetChanges, (targetId, change) => {\n if (change.resumeToken.approximateByteSize() > 0) {\n const targetData = this.listenTargets[targetId];\n // A watched target might have been removed already.\n if (targetData) {\n this.listenTargets[targetId] = targetData.withResumeToken(\n change.resumeToken,\n snapshotVersion\n );\n }\n }\n });\n\n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n remoteEvent.targetMismatches.forEach(targetId => {\n const targetData = this.listenTargets[targetId];\n if (!targetData) {\n // A watched target might have been removed already.\n return;\n }\n\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n this.listenTargets[targetId] = targetData.withResumeToken(\n ByteString.EMPTY_BYTE_STRING,\n targetData.snapshotVersion\n );\n\n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n this.sendUnwatchRequest(targetId);\n\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const requestTargetData = new TargetData(\n targetData.target,\n targetId,\n TargetPurpose.ExistenceFilterMismatch,\n targetData.sequenceNumber\n );\n this.sendWatchRequest(requestTargetData);\n });\n\n // Finally raise remote event\n return this.syncEngine.applyRemoteEvent(remoteEvent);\n }\n\n /** Handles an error on a target */\n private handleTargetError(watchChange: WatchTargetChange): Promise<void> {\n assert(!!watchChange.cause, 'Handling target error without a cause');\n const error = watchChange.cause!;\n let promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(targetId => {\n promiseChain = promiseChain.then(async () => {\n // A watched target might have been removed already.\n if (objUtils.contains(this.listenTargets, targetId)) {\n delete this.listenTargets[targetId];\n this.watchChangeAggregator!.removeTarget(targetId);\n return this.syncEngine.rejectListen(targetId, error);\n }\n });\n });\n return promiseChain;\n }\n\n /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */\n async fillWritePipeline(): Promise<void> {\n if (this.canAddToWritePipeline()) {\n const lastBatchIdRetrieved =\n this.writePipeline.length > 0\n ? this.writePipeline[this.writePipeline.length - 1].batchId\n : BATCHID_UNKNOWN;\n const batch = await this.localStore.nextMutationBatch(\n lastBatchIdRetrieved\n );\n\n if (batch === null) {\n if (this.writePipeline.length === 0) {\n this.writeStream.markIdle();\n }\n } else {\n this.addToWritePipeline(batch);\n await this.fillWritePipeline();\n }\n }\n\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n }\n\n /**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */\n private canAddToWritePipeline(): boolean {\n return (\n this.canUseNetwork() && this.writePipeline.length < MAX_PENDING_WRITES\n );\n }\n\n // For testing\n outstandingWrites(): number {\n return this.writePipeline.length;\n }\n\n /**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */\n private addToWritePipeline(batch: MutationBatch): void {\n assert(\n this.canAddToWritePipeline(),\n 'addToWritePipeline called when pipeline is full'\n );\n this.writePipeline.push(batch);\n\n if (this.writeStream.isOpen() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n }\n\n private shouldStartWriteStream(): boolean {\n return (\n this.canUseNetwork() &&\n !this.writeStream.isStarted() &&\n this.writePipeline.length > 0\n );\n }\n\n private startWriteStream(): void {\n assert(\n this.shouldStartWriteStream(),\n 'startWriteStream() called when shouldStartWriteStream() is false.'\n );\n this.writeStream.start();\n }\n\n private async onWriteStreamOpen(): Promise<void> {\n this.writeStream.writeHandshake();\n }\n\n private onWriteHandshakeComplete(): Promise<void> {\n // Record the stream token.\n return this.localStore\n .setLastStreamToken(this.writeStream.lastStreamToken)\n .then(() => {\n // Send the write pipeline now that the stream is established.\n for (const batch of this.writePipeline) {\n this.writeStream.writeMutations(batch.mutations);\n }\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n\n private onMutationResult(\n commitVersion: SnapshotVersion,\n results: MutationResult[]\n ): Promise<void> {\n // This is a response to a write containing mutations and should be\n // correlated to the first write in our write pipeline.\n assert(\n this.writePipeline.length > 0,\n 'Got result for empty write pipeline'\n );\n const batch = this.writePipeline.shift()!;\n const success = MutationBatchResult.from(\n batch,\n commitVersion,\n results,\n this.writeStream.lastStreamToken\n );\n return this.syncEngine.applySuccessfulWrite(success).then(() => {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return this.fillWritePipeline();\n });\n }\n\n private async onWriteStreamClose(error?: FirestoreError): Promise<void> {\n if (error === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n assert(\n !this.shouldStartWriteStream(),\n 'Write stream was stopped gracefully while still needed.'\n );\n }\n\n // If the write stream closed due to an error, invoke the error callbacks if\n // there are pending writes.\n if (error && this.writePipeline.length > 0) {\n // A promise that is resolved after we processed the error\n let errorHandling: Promise<void>;\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error!);\n } else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error!);\n }\n\n return errorHandling.then(() => {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n });\n }\n // No pending writes, nothing to do\n }\n\n private async handleHandshakeError(error: FirestoreError): Promise<void> {\n // Reset the token if it's a permanent error, signaling the write stream is\n // no longer valid. Note that the handshake does not count as a write: see\n // comments on isPermanentWriteError for details.\n if (isPermanentError(error.code)) {\n log.debug(\n LOG_TAG,\n 'RemoteStore error before completed handshake; resetting stream token: ',\n this.writeStream.lastStreamToken\n );\n this.writeStream.lastStreamToken = ByteString.EMPTY_BYTE_STRING;\n\n return this.localStore\n .setLastStreamToken(ByteString.EMPTY_BYTE_STRING)\n .catch(ignoreIfPrimaryLeaseLoss);\n } else {\n // Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n }\n }\n\n private async handleWriteError(error: FirestoreError): Promise<void> {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (isPermanentWriteError(error.code)) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const batch = this.writePipeline.shift()!;\n\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n this.writeStream.inhibitBackoff();\n\n return this.syncEngine\n .rejectFailedWrite(batch.batchId, error)\n .then(() => {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return this.fillWritePipeline();\n });\n } else {\n // Transient error, just let the retry logic kick in.\n }\n }\n\n createTransaction(): Transaction {\n return new Transaction(this.datastore);\n }\n\n private async restartNetwork(): Promise<void> {\n this.networkEnabled = false;\n await this.disableNetworkInternal();\n this.onlineStateTracker.set(OnlineState.Unknown);\n await this.enableNetwork();\n }\n\n async handleCredentialChange(): Promise<void> {\n if (this.canUseNetwork()) {\n // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n log.debug(LOG_TAG, 'RemoteStore restarting streams for new credential');\n await this.restartNetwork();\n }\n }\n\n /**\n * Toggles the network state when the client gains or loses its primary lease.\n */\n async applyPrimaryState(isPrimary: boolean): Promise<void> {\n this.isPrimary = isPrimary;\n\n if (isPrimary && this.networkEnabled) {\n await this.enableNetwork();\n } else if (!isPrimary) {\n await this.disableNetworkInternal();\n this.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { User } from '../auth/user';\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from '../local/local_store';\nimport { LocalViewChanges } from '../local/local_view_changes';\nimport { ReferenceSet } from '../local/reference_set';\nimport { TargetData, TargetPurpose } from '../local/target_data';\nimport {\n documentKeySet,\n DocumentKeySet,\n MaybeDocumentMap\n} from '../model/collections';\nimport { MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatchResult, BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { RemoteEvent, TargetChange } from '../remote/remote_event';\nimport { RemoteStore } from '../remote/remote_store';\nimport { RemoteSyncer } from '../remote/remote_syncer';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Deferred } from '../util/promise';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { ClientId, SharedClientState } from '../local/shared_client_state';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from '../local/shared_client_state_syncer';\nimport * as objUtils from '../util/obj';\nimport { SortedSet } from '../util/sorted_set';\nimport { ListenSequence } from './listen_sequence';\nimport { Query, LimitType } from './query';\nimport { SnapshotVersion } from './snapshot_version';\nimport { Target } from './target';\nimport { TargetIdGenerator } from './target_id_generator';\nimport { Transaction } from './transaction';\nimport {\n BatchId,\n MutationBatchState,\n OnlineState,\n OnlineStateSource,\n TargetId\n} from './types';\nimport {\n AddedLimboDocument,\n LimboDocumentChange,\n RemovedLimboDocument,\n View,\n ViewChange,\n ViewDocumentChanges\n} from './view';\nimport { ViewSnapshot } from './view_snapshot';\nimport { AsyncQueue } from '../util/async_queue';\nimport { TransactionRunner } from './transaction_runner';\n\nconst LOG_TAG = 'SyncEngine';\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass QueryView {\n constructor(\n /**\n * The query itself.\n */\n public query: Query,\n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n public targetId: TargetId,\n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n public view: View\n ) {}\n}\n\n/** Tracks a limbo resolution. */\nclass LimboResolution {\n constructor(public key: DocumentKey) {}\n\n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n receivedDocument: boolean = false;\n}\n\n/**\n * Interface implemented by EventManager to handle notifications from\n * SyncEngine.\n */\nexport interface SyncEngineListener {\n /** Handles new view snapshots. */\n onWatchChange(snapshots: ViewSnapshot[]): void;\n\n /** Handles the failure of a query. */\n onWatchError(query: Query, error: Error): void;\n\n /** Handles a change in online state. */\n onOnlineStateChange(onlineState: OnlineState): void;\n}\n\n/**\n * SyncEngine is the central controller in the client SDK architecture. It is\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\n * SyncEngine's responsibilities include:\n * 1. Coordinating client requests and remote events between the EventManager\n * and the local and remote data stores.\n * 2. Managing a View object for each query, providing the unified view between\n * the local and remote data stores.\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\n * queue that need sending to the backend.\n *\n * The SyncEngine’s methods should only ever be called by methods running in the\n * global async queue.\n */\nexport class SyncEngine implements RemoteSyncer, SharedClientStateSyncer {\n private syncEngineListener: SyncEngineListener | null = null;\n\n private queryViewsByQuery = new ObjectMap<Query, QueryView>(q =>\n q.canonicalId()\n );\n private queriesByTarget: { [targetId: number]: Query[] } = {};\n private limboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n private limboResolutionsByTarget: {\n [targetId: number]: LimboResolution;\n } = {};\n private limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n private mutationUserCallbacks = {} as {\n [uidKey: string]: SortedMap<BatchId, Deferred<void>>;\n };\n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n private pendingWritesCallbacks = new Map<BatchId, Array<Deferred<void>>>();\n private limboTargetIdGenerator = TargetIdGenerator.forSyncEngine();\n\n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n private isPrimary: undefined | boolean = undefined;\n private onlineState = OnlineState.Unknown;\n\n constructor(\n private localStore: LocalStore,\n private remoteStore: RemoteStore,\n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n private sharedClientState: SharedClientState,\n private currentUser: User\n ) {}\n\n // Only used for testing.\n get isPrimaryClient(): boolean {\n return this.isPrimary === true;\n }\n\n /** Subscribes to SyncEngine notifications. Has to be called exactly once. */\n subscribe(syncEngineListener: SyncEngineListener): void {\n assert(syncEngineListener !== null, 'SyncEngine listener cannot be null');\n assert(\n this.syncEngineListener === null,\n 'SyncEngine already has a subscriber.'\n );\n\n this.syncEngineListener = syncEngineListener;\n }\n\n /**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the targetId of the query.\n */\n async listen(query: Query): Promise<TargetId> {\n this.assertSubscribed('listen()');\n\n let targetId;\n let viewSnapshot;\n\n const queryView = this.queryViewsByQuery.get(query);\n if (queryView) {\n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n targetId = queryView.targetId;\n this.sharedClientState.addLocalQueryTarget(targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n } else {\n const targetData = await this.localStore.allocateTarget(query.toTarget());\n\n const status = this.sharedClientState.addLocalQueryTarget(\n targetData.targetId\n );\n targetId = targetData.targetId;\n viewSnapshot = await this.initializeViewAndComputeSnapshot(\n query,\n targetId,\n status === 'current'\n );\n if (this.isPrimary) {\n this.remoteStore.listen(targetData);\n }\n }\n\n this.syncEngineListener!.onWatchChange([viewSnapshot]);\n return targetId;\n }\n\n /**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */\n private async initializeViewAndComputeSnapshot(\n query: Query,\n targetId: TargetId,\n current: boolean\n ): Promise<ViewSnapshot> {\n const queryResult = await this.localStore.executeQuery(\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n const synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(\n targetId,\n current && this.onlineState !== OnlineState.Offline\n );\n const viewChange = view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ this.isPrimary === true,\n synthesizedTargetChange\n );\n assert(\n viewChange.limboChanges.length === 0,\n 'View returned limbo docs before target ack from the server.'\n );\n assert(\n !!viewChange.snapshot,\n 'applyChanges for new view should always return a snapshot'\n );\n\n const data = new QueryView(query, targetId, view);\n this.queryViewsByQuery.set(query, data);\n if (!this.queriesByTarget[targetId]) {\n this.queriesByTarget[targetId] = [];\n }\n this.queriesByTarget[targetId].push(query);\n return viewChange.snapshot!;\n }\n\n /**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */\n // PORTING NOTE: Multi-tab only.\n private async synchronizeViewAndComputeSnapshot(\n queryView: QueryView\n ): Promise<ViewChange> {\n const queryResult = await this.localStore.executeQuery(\n queryView.query,\n /* usePreviousResults= */ true\n );\n const viewSnapshot = queryView.view.synchronizeWithPersistedState(\n queryResult\n );\n if (this.isPrimary) {\n this.updateTrackedLimbos(queryView.targetId, viewSnapshot.limboChanges);\n }\n return viewSnapshot;\n }\n\n /** Stops listening to the query. */\n async unlisten(query: Query): Promise<void> {\n this.assertSubscribed('unlisten()');\n\n const queryView = this.queryViewsByQuery.get(query)!;\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n\n // Only clean up the query view and target if this is the only query mapped\n // to the target.\n const queries = this.queriesByTarget[queryView.targetId];\n if (queries.length > 1) {\n this.queriesByTarget[queryView.targetId] = queries.filter(\n q => !q.isEqual(query)\n );\n this.queryViewsByQuery.delete(query);\n return;\n }\n\n // No other queries are mapped to the target, clean up the query and the target.\n if (this.isPrimary) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n this.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n const targetRemainsActive = this.sharedClientState.isActiveQueryTarget(\n queryView.targetId\n );\n\n if (!targetRemainsActive) {\n await this.localStore\n .releaseTarget(queryView.targetId, /*keepPersistedTargetData=*/ false)\n .then(() => {\n this.sharedClientState.clearQueryState(queryView.targetId);\n this.remoteStore.unlisten(queryView.targetId);\n this.removeAndCleanupTarget(queryView.targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n } else {\n this.removeAndCleanupTarget(queryView.targetId);\n await this.localStore.releaseTarget(\n queryView.targetId,\n /*keepPersistedTargetData=*/ true\n );\n }\n }\n\n /**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */\n async write(batch: Mutation[], userCallback: Deferred<void>): Promise<void> {\n this.assertSubscribed('write()');\n const result = await this.localStore.localWrite(batch);\n this.sharedClientState.addPendingMutation(result.batchId);\n this.addMutationCallback(result.batchId, userCallback);\n await this.emitNewSnapsAndNotifyLocalStore(result.changes);\n await this.remoteStore.fillWritePipeline();\n }\n\n /**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n *\n * The Deferred input is resolved when the transaction is fully committed.\n */\n runTransaction<T>(\n asyncQueue: AsyncQueue,\n updateFunction: (transaction: Transaction) => Promise<T>,\n deferred: Deferred<T>\n ): void {\n new TransactionRunner<T>(\n asyncQueue,\n this.remoteStore,\n updateFunction,\n deferred\n ).run();\n }\n\n async applyRemoteEvent(remoteEvent: RemoteEvent): Promise<void> {\n this.assertSubscribed('applyRemoteEvent()');\n try {\n const changes = await this.localStore.applyRemoteEvent(remoteEvent);\n // Update `receivedDocument` as appropriate for any limbo targets.\n objUtils.forEach(remoteEvent.targetChanges, (targetId, targetChange) => {\n const limboResolution = this.limboResolutionsByTarget[Number(targetId)];\n if (limboResolution) {\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n assert(\n targetChange.addedDocuments.size +\n targetChange.modifiedDocuments.size +\n targetChange.removedDocuments.size <=\n 1,\n 'Limbo resolution for single document contains multiple changes.'\n );\n if (targetChange.addedDocuments.size > 0) {\n limboResolution.receivedDocument = true;\n } else if (targetChange.modifiedDocuments.size > 0) {\n assert(\n limboResolution.receivedDocument,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n assert(\n limboResolution.receivedDocument,\n 'Received remove for limbo target document without add.'\n );\n limboResolution.receivedDocument = false;\n } else {\n // This was probably just a CURRENT targetChange or similar.\n }\n }\n });\n await this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error);\n }\n }\n\n /**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */\n applyOnlineStateChange(\n onlineState: OnlineState,\n source: OnlineStateSource\n ): void {\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (\n (this.isPrimary && source === OnlineStateSource.RemoteStore) ||\n (!this.isPrimary && source === OnlineStateSource.SharedClientState)\n ) {\n this.assertSubscribed('applyOnlineStateChange()');\n const newViewSnapshots = [] as ViewSnapshot[];\n this.queryViewsByQuery.forEach((query, queryView) => {\n const viewChange = queryView.view.applyOnlineStateChange(onlineState);\n assert(\n viewChange.limboChanges.length === 0,\n 'OnlineState should not affect limbo documents.'\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n });\n this.syncEngineListener!.onOnlineStateChange(onlineState);\n this.syncEngineListener!.onWatchChange(newViewSnapshots);\n\n this.onlineState = onlineState;\n if (this.isPrimary) {\n this.sharedClientState.setOnlineState(onlineState);\n }\n }\n }\n\n async rejectListen(targetId: TargetId, err: FirestoreError): Promise<void> {\n this.assertSubscribed('rejectListens()');\n\n // PORTING NOTE: Multi-tab only.\n this.sharedClientState.updateQueryState(targetId, 'rejected', err);\n\n const limboResolution = this.limboResolutionsByTarget[targetId];\n const limboKey = limboResolution && limboResolution.key;\n if (limboKey) {\n // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboResolutionsByTarget[targetId];\n\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let documentUpdates = new SortedMap<DocumentKey, MaybeDocument>(\n DocumentKey.comparator\n );\n documentUpdates = documentUpdates.insert(\n limboKey,\n new NoDocument(limboKey, SnapshotVersion.forDeletedDoc())\n );\n const resolvedLimboDocuments = documentKeySet().add(limboKey);\n const event = new RemoteEvent(\n SnapshotVersion.MIN,\n /* targetChanges= */ {},\n /* targetMismatches= */ new SortedSet<TargetId>(primitiveComparator),\n documentUpdates,\n resolvedLimboDocuments\n );\n return this.applyRemoteEvent(event);\n } else {\n await this.localStore\n .releaseTarget(targetId, /* keepPersistedTargetData */ false)\n .then(() => this.removeAndCleanupTarget(targetId, err))\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n }\n\n // PORTING NOTE: Multi-tab only\n async applyBatchState(\n batchId: BatchId,\n batchState: MutationBatchState,\n error?: FirestoreError\n ): Promise<void> {\n this.assertSubscribed('applyBatchState()');\n const documents = await this.localStore.lookupMutationDocuments(batchId);\n\n if (documents === null) {\n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n log.debug(LOG_TAG, 'Cannot apply mutation batch with id: ' + batchId);\n return;\n }\n\n if (batchState === 'pending') {\n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await this.remoteStore.fillWritePipeline();\n } else if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n this.processUserCallback(batchId, error ? error : null);\n this.localStore.removeCachedMutationBatchMetadata(batchId);\n } else {\n fail(`Unknown batchState: ${batchState}`);\n }\n\n await this.emitNewSnapsAndNotifyLocalStore(documents);\n }\n\n async applySuccessfulWrite(\n mutationBatchResult: MutationBatchResult\n ): Promise<void> {\n this.assertSubscribed('applySuccessfulWrite()');\n\n const batchId = mutationBatchResult.batch.batchId;\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n this.processUserCallback(batchId, /*error=*/ null);\n\n this.triggerPendingWritesCallbacks(batchId);\n\n try {\n const changes = await this.localStore.acknowledgeBatch(\n mutationBatchResult\n );\n this.sharedClientState.updateMutationState(batchId, 'acknowledged');\n await this.emitNewSnapsAndNotifyLocalStore(changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error);\n }\n }\n\n async rejectFailedWrite(\n batchId: BatchId,\n error: FirestoreError\n ): Promise<void> {\n this.assertSubscribed('rejectFailedWrite()');\n\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n this.processUserCallback(batchId, error);\n\n this.triggerPendingWritesCallbacks(batchId);\n\n try {\n const changes = await this.localStore.rejectBatch(batchId);\n this.sharedClientState.updateMutationState(batchId, 'rejected', error);\n await this.emitNewSnapsAndNotifyLocalStore(changes);\n } catch (error) {\n await ignoreIfPrimaryLeaseLoss(error);\n }\n }\n\n /**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */\n async registerPendingWritesCallback(callback: Deferred<void>): Promise<void> {\n if (!this.remoteStore.canUseNetwork()) {\n log.debug(\n LOG_TAG,\n 'The network is disabled. The task returned by ' +\n \"'awaitPendingWrites()' will not complete until the network is enabled.\"\n );\n }\n\n const highestBatchId = await this.localStore.getHighestUnacknowledgedBatchId();\n if (highestBatchId === BATCHID_UNKNOWN) {\n // Trigger the callback right away if there is no pending writes at the moment.\n callback.resolve();\n return;\n }\n\n const callbacks = this.pendingWritesCallbacks.get(highestBatchId) || [];\n callbacks.push(callback);\n this.pendingWritesCallbacks.set(highestBatchId, callbacks);\n }\n\n /**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */\n private triggerPendingWritesCallbacks(batchId: BatchId): void {\n (this.pendingWritesCallbacks.get(batchId) || []).forEach(callback => {\n callback.resolve();\n });\n\n this.pendingWritesCallbacks.delete(batchId);\n }\n\n /** Reject all outstanding callbacks waiting for pending writes to complete. */\n private rejectOutstandingPendingWritesCallbacks(errorMessage: string): void {\n this.pendingWritesCallbacks.forEach(callbacks => {\n callbacks.forEach(callback => {\n callback.reject(new FirestoreError(Code.CANCELLED, errorMessage));\n });\n });\n\n this.pendingWritesCallbacks.clear();\n }\n\n private addMutationCallback(\n batchId: BatchId,\n callback: Deferred<void>\n ): void {\n let newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n if (!newCallbacks) {\n newCallbacks = new SortedMap<BatchId, Deferred<void>>(\n primitiveComparator\n );\n }\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */\n private processUserCallback(batchId: BatchId, error: Error | null): void {\n let newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (newCallbacks) {\n const callback = newCallbacks.get(batchId);\n if (callback) {\n assert(\n batchId === newCallbacks.minKey(),\n 'Mutation callbacks processed out-of-order?'\n );\n if (error) {\n callback.reject(error);\n } else {\n callback.resolve();\n }\n newCallbacks = newCallbacks.remove(batchId);\n }\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n }\n\n private removeAndCleanupTarget(\n targetId: number,\n error: Error | null = null\n ): void {\n this.sharedClientState.removeLocalQueryTarget(targetId);\n\n assert(\n this.queriesByTarget[targetId] &&\n this.queriesByTarget[targetId].length !== 0,\n `There are no queries mapped to target id ${targetId}`\n );\n\n for (const query of this.queriesByTarget[targetId]) {\n this.queryViewsByQuery.delete(query);\n if (error) {\n this.syncEngineListener!.onWatchError(query, error);\n }\n }\n\n delete this.queriesByTarget[targetId];\n\n if (this.isPrimary) {\n const limboKeys = this.limboDocumentRefs.referencesForId(targetId);\n this.limboDocumentRefs.removeReferencesForId(targetId);\n limboKeys.forEach(limboKey => {\n const isReferenced = this.limboDocumentRefs.containsKey(limboKey);\n if (!isReferenced) {\n // We removed the last reference for this key\n this.removeLimboTarget(limboKey);\n }\n });\n }\n }\n\n private removeLimboTarget(key: DocumentKey): void {\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const limboTargetId = this.limboTargetsByKey.get(key);\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n this.remoteStore.unlisten(limboTargetId);\n this.limboTargetsByKey = this.limboTargetsByKey.remove(key);\n delete this.limboResolutionsByTarget[limboTargetId];\n }\n\n private updateTrackedLimbos(\n targetId: TargetId,\n limboChanges: LimboDocumentChange[]\n ): void {\n for (const limboChange of limboChanges) {\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n log.debug(LOG_TAG, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n const isReferenced = this.limboDocumentRefs.containsKey(\n limboChange.key\n );\n if (!isReferenced) {\n // We removed the last reference for this key\n this.removeLimboTarget(limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n }\n\n private trackLimboChange(limboChange: AddedLimboDocument): void {\n const key = limboChange.key;\n if (!this.limboTargetsByKey.get(key)) {\n log.debug(LOG_TAG, 'New document in limbo: ' + key);\n const limboTargetId = this.limboTargetIdGenerator.next();\n const query = Query.atPath(key.path);\n this.limboResolutionsByTarget[limboTargetId] = new LimboResolution(key);\n this.remoteStore.listen(\n new TargetData(\n query.toTarget(),\n limboTargetId,\n TargetPurpose.LimboResolution,\n ListenSequence.INVALID\n )\n );\n this.limboTargetsByKey = this.limboTargetsByKey.insert(\n key,\n limboTargetId\n );\n }\n }\n\n // Visible for testing\n currentLimboDocs(): SortedMap<DocumentKey, TargetId> {\n return this.limboTargetsByKey;\n }\n\n private async emitNewSnapsAndNotifyLocalStore(\n changes: MaybeDocumentMap,\n remoteEvent?: RemoteEvent\n ): Promise<void> {\n const newSnaps: ViewSnapshot[] = [];\n const docChangesInAllViews: LocalViewChanges[] = [];\n const queriesProcessed: Array<Promise<void>> = [];\n\n this.queryViewsByQuery.forEach((_, queryView) => {\n queriesProcessed.push(\n Promise.resolve()\n .then(() => {\n const viewDocChanges = queryView.view.computeDocChanges(changes);\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\n }\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n return this.localStore\n .executeQuery(queryView.query, /* usePreviousResults= */ false)\n .then(({ documents }) => {\n return queryView.view.computeDocChanges(\n documents,\n viewDocChanges\n );\n });\n })\n .then((viewDocChanges: ViewDocumentChanges) => {\n const targetChange =\n remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n const viewChange = queryView.view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ this.isPrimary === true,\n targetChange\n );\n this.updateTrackedLimbos(\n queryView.targetId,\n viewChange.limboChanges\n );\n if (viewChange.snapshot) {\n if (this.isPrimary) {\n this.sharedClientState.updateQueryState(\n queryView.targetId,\n viewChange.snapshot.fromCache ? 'not-current' : 'current'\n );\n }\n\n newSnaps.push(viewChange.snapshot);\n const docChanges = LocalViewChanges.fromSnapshot(\n queryView.targetId,\n viewChange.snapshot\n );\n docChangesInAllViews.push(docChanges);\n }\n })\n );\n });\n\n await Promise.all(queriesProcessed);\n this.syncEngineListener!.onWatchChange(newSnaps);\n await this.localStore.notifyLocalViewChanges(docChangesInAllViews);\n }\n\n private assertSubscribed(fnName: string): void {\n assert(\n this.syncEngineListener !== null,\n 'Trying to call ' + fnName + ' before calling subscribe().'\n );\n }\n\n async handleCredentialChange(user: User): Promise<void> {\n const userChanged = !this.currentUser.isEqual(user);\n this.currentUser = user;\n\n if (userChanged) {\n // Fails tasks waiting for pending writes requested by previous user.\n this.rejectOutstandingPendingWritesCallbacks(\n \"'waitForPendingWrites' promise is rejected due to a user change.\"\n );\n\n const result = await this.localStore.handleUserChange(user);\n // TODO(b/114226417): Consider calling this only in the primary tab.\n this.sharedClientState.handleUserChange(\n user,\n result.removedBatchIds,\n result.addedBatchIds\n );\n await this.emitNewSnapsAndNotifyLocalStore(result.affectedDocuments);\n }\n\n await this.remoteStore.handleCredentialChange();\n }\n\n // PORTING NOTE: Multi-tab only\n async applyPrimaryState(isPrimary: boolean): Promise<void> {\n if (isPrimary === true && this.isPrimary !== true) {\n this.isPrimary = true;\n await this.remoteStore.applyPrimaryState(true);\n\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const activeTargets = this.sharedClientState.getAllActiveQueryTargets();\n const activeQueries = await this.synchronizeQueryViewsAndRaiseSnapshots(\n activeTargets.toArray()\n );\n for (const targetData of activeQueries) {\n this.remoteStore.listen(targetData);\n }\n } else if (isPrimary === false && this.isPrimary !== false) {\n this.isPrimary = false;\n\n const activeTargets: TargetId[] = [];\n\n let p = Promise.resolve();\n objUtils.forEachNumber(this.queriesByTarget, (targetId, _) => {\n if (this.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets.push(targetId);\n } else {\n p = p.then(() => {\n this.removeAndCleanupTarget(targetId);\n return this.localStore.releaseTarget(\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n });\n }\n this.remoteStore.unlisten(targetId);\n });\n await p;\n\n await this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets);\n this.resetLimboDocuments();\n await this.remoteStore.applyPrimaryState(false);\n }\n }\n\n // PORTING NOTE: Multi-tab only.\n private resetLimboDocuments(): void {\n objUtils.forEachNumber(this.limboResolutionsByTarget, targetId => {\n this.remoteStore.unlisten(targetId);\n });\n this.limboDocumentRefs.removeAllReferences();\n this.limboResolutionsByTarget = [];\n this.limboTargetsByKey = new SortedMap<DocumentKey, TargetId>(\n DocumentKey.comparator\n );\n }\n\n /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n */\n // PORTING NOTE: Multi-tab only.\n private async synchronizeQueryViewsAndRaiseSnapshots(\n targets: TargetId[]\n ): Promise<TargetData[]> {\n const activeQueries: TargetData[] = [];\n const newViewSnapshots: ViewSnapshot[] = [];\n for (const targetId of targets) {\n let targetData: TargetData;\n const queries = this.queriesByTarget[targetId];\n\n if (queries && queries.length !== 0) {\n // For queries that have a local View, we need to update their state\n // in LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n await this.localStore.releaseTarget(\n targetId,\n /*keepPersistedTargetData=*/ true\n );\n targetData = await this.localStore.allocateTarget(\n queries[0].toTarget()\n );\n\n for (const query of queries) {\n const queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, `No query view found for ${query}`);\n\n const viewChange = await this.synchronizeViewAndComputeSnapshot(\n queryView\n );\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n }\n } else {\n assert(\n this.isPrimary === true,\n 'A secondary tab should never have an active target without an active query.'\n );\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const target = await this.localStore.getTarget(targetId);\n assert(!!target, `Target for id ${targetId} not found`);\n targetData = await this.localStore.allocateTarget(target);\n await this.initializeViewAndComputeSnapshot(\n this.synthesizeTargetToQuery(target!),\n targetId,\n /*current=*/ false\n );\n }\n\n activeQueries.push(targetData!);\n }\n\n this.syncEngineListener!.onWatchChange(newViewSnapshots);\n return activeQueries;\n }\n\n /**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n // PORTING NOTE: Multi-tab only\n private synthesizeTargetToQuery(target: Target): Query {\n return new Query(\n target.path,\n target.collectionGroup,\n target.orderBy,\n target.filters,\n target.limit,\n LimitType.First,\n target.startAt,\n target.endAt\n );\n }\n\n // PORTING NOTE: Multi-tab only\n getActiveClients(): Promise<ClientId[]> {\n return this.localStore.getActiveClients();\n }\n\n // PORTING NOTE: Multi-tab only\n async applyTargetState(\n targetId: TargetId,\n state: QueryTargetState,\n error?: FirestoreError\n ): Promise<void> {\n if (this.isPrimary) {\n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n log.debug(LOG_TAG, 'Ignoring unexpected query state notification.');\n return;\n }\n\n if (this.queriesByTarget[targetId]) {\n switch (state) {\n case 'current':\n case 'not-current': {\n const changes = await this.localStore.getNewDocumentChanges();\n const synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(\n targetId,\n state === 'current'\n );\n await this.emitNewSnapsAndNotifyLocalStore(\n changes,\n synthesizedRemoteEvent\n );\n break;\n }\n case 'rejected': {\n await this.localStore.releaseTarget(\n targetId,\n /* keepPersistedTargetData */ true\n );\n this.removeAndCleanupTarget(targetId, error);\n break;\n }\n default:\n fail('Unexpected target state: ' + state);\n }\n }\n }\n\n // PORTING NOTE: Multi-tab only\n async applyActiveTargetsChange(\n added: TargetId[],\n removed: TargetId[]\n ): Promise<void> {\n if (!this.isPrimary) {\n return;\n }\n\n for (const targetId of added) {\n assert(\n !this.queriesByTarget[targetId],\n 'Trying to add an already active target'\n );\n const target = await this.localStore.getTarget(targetId);\n assert(!!target, `Query data for active target ${targetId} not found`);\n const targetData = await this.localStore.allocateTarget(target);\n await this.initializeViewAndComputeSnapshot(\n this.synthesizeTargetToQuery(target),\n targetData.targetId,\n /*current=*/ false\n );\n this.remoteStore.listen(targetData);\n }\n\n for (const targetId of removed) {\n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n if (!this.queriesByTarget[targetId]) {\n continue;\n }\n\n // Release queries that are still active.\n await this.localStore\n .releaseTarget(targetId, /* keepPersistedTargetData */ false)\n .then(() => {\n this.remoteStore.unlisten(targetId);\n this.removeAndCleanupTarget(targetId);\n })\n .catch(ignoreIfPrimaryLeaseLoss);\n }\n }\n\n // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\n // the online state.\n enableNetwork(): Promise<void> {\n this.localStore.setNetworkEnabled(true);\n return this.remoteStore.enableNetwork();\n }\n\n // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\n // the online state.\n disableNetwork(): Promise<void> {\n this.localStore.setNetworkEnabled(false);\n return this.remoteStore.disableNetwork();\n }\n\n getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet {\n const limboResolution = this.limboResolutionsByTarget[targetId];\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n let keySet = documentKeySet();\n const queries = this.queriesByTarget[targetId];\n if (!queries) {\n return keySet;\n }\n for (const query of queries) {\n const queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, `No query view found for ${query}`);\n keySet = keySet.unionWith(queryView.view.syncedDocuments);\n }\n return keySet;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../util/assert';\nimport { EventHandler } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { Query } from './query';\nimport { SyncEngine, SyncEngineListener } from './sync_engine';\nimport { OnlineState, TargetId } from './types';\nimport { DocumentViewChange, ChangeType, ViewSnapshot } from './view_snapshot';\n\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */\nclass QueryListenersInfo {\n viewSnap: ViewSnapshot | null = null;\n targetId: TargetId = 0;\n listeners: QueryListener[] = [];\n}\n\n/**\n * Interface for handling events from the EventManager.\n */\nexport interface Observer<T> {\n next: EventHandler<T>;\n error: EventHandler<Error>;\n}\n\n/**\n * EventManager is responsible for mapping queries to query event emitters.\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\n * backend.\n */\nexport class EventManager implements SyncEngineListener {\n private queries = new ObjectMap<Query, QueryListenersInfo>(q =>\n q.canonicalId()\n );\n\n private onlineState = OnlineState.Unknown;\n\n private snapshotsInSyncListeners: Set<Observer<void>> = new Set();\n\n constructor(private syncEngine: SyncEngine) {\n this.syncEngine.subscribe(this);\n }\n\n listen(listener: QueryListener): Promise<TargetId> {\n const query = listener.query;\n let firstListen = false;\n\n let queryInfo = this.queries.get(query);\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n queryInfo.listeners.push(listener);\n\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n const raisedEvent = listener.applyOnlineStateChange(this.onlineState);\n assert(\n !raisedEvent,\n \"applyOnlineStateChange() shouldn't raise an event for brand-new listeners.\"\n );\n\n if (queryInfo.viewSnap) {\n const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap);\n if (raisedEvent) {\n this.raiseSnapshotsInSyncEvent();\n }\n }\n\n if (firstListen) {\n return this.syncEngine.listen(query).then(targetId => {\n queryInfo!.targetId = targetId;\n return targetId;\n });\n } else {\n return Promise.resolve(queryInfo.targetId);\n }\n }\n\n async unlisten(listener: QueryListener): Promise<void> {\n const query = listener.query;\n let lastListen = false;\n\n const queryInfo = this.queries.get(query);\n if (queryInfo) {\n const i = queryInfo.listeners.indexOf(listener);\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n\n if (lastListen) {\n this.queries.delete(query);\n return this.syncEngine.unlisten(query);\n }\n }\n\n onWatchChange(viewSnaps: ViewSnapshot[]): void {\n let raisedEvent = false;\n for (const viewSnap of viewSnaps) {\n const query = viewSnap.query;\n const queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n if (listener.onViewSnapshot(viewSnap)) {\n raisedEvent = true;\n }\n }\n queryInfo.viewSnap = viewSnap;\n }\n }\n if (raisedEvent) {\n this.raiseSnapshotsInSyncEvent();\n }\n }\n\n onWatchError(query: Query, error: Error): void {\n const queryInfo = this.queries.get(query);\n if (queryInfo) {\n for (const listener of queryInfo.listeners) {\n listener.onError(error);\n }\n }\n\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n this.queries.delete(query);\n }\n\n onOnlineStateChange(onlineState: OnlineState): void {\n this.onlineState = onlineState;\n let raisedEvent = false;\n this.queries.forEach((_, queryInfo) => {\n for (const listener of queryInfo.listeners) {\n // Run global snapshot listeners if a consistent snapshot has been emitted.\n if (listener.applyOnlineStateChange(onlineState)) {\n raisedEvent = true;\n }\n }\n });\n if (raisedEvent) {\n this.raiseSnapshotsInSyncEvent();\n }\n }\n\n addSnapshotsInSyncListener(observer: Observer<void>): void {\n this.snapshotsInSyncListeners.add(observer);\n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n observer.next();\n }\n\n removeSnapshotsInSyncListener(observer: Observer<void>): void {\n this.snapshotsInSyncListeners.delete(observer);\n }\n\n // Call all global snapshot listeners that have been set.\n private raiseSnapshotsInSyncEvent(): void {\n this.snapshotsInSyncListeners.forEach(observer => {\n observer.next();\n });\n }\n}\n\nexport interface ListenOptions {\n /** Raise events even when only the metadata changes */\n readonly includeMetadataChanges?: boolean;\n\n /**\n * Wait for a sync with the server when online, but still raise events while\n * offline.\n */\n readonly waitForSyncWhenOnline?: boolean;\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */\nexport class QueryListener {\n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n private raisedInitialEvent = false;\n\n private options: ListenOptions;\n\n private snap: ViewSnapshot | null = null;\n\n private onlineState = OnlineState.Unknown;\n\n constructor(\n readonly query: Query,\n private queryObserver: Observer<ViewSnapshot>,\n options?: ListenOptions\n ) {\n this.options = options || {};\n }\n\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */\n onViewSnapshot(snap: ViewSnapshot): boolean {\n assert(\n snap.docChanges.length > 0 || snap.syncStateChanged,\n 'We got a new snapshot with no changes?'\n );\n\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const docChanges: DocumentViewChange[] = [];\n for (const docChange of snap.docChanges) {\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n snap = new ViewSnapshot(\n snap.query,\n snap.docs,\n snap.oldDocs,\n docChanges,\n snap.mutatedKeys,\n snap.fromCache,\n snap.syncStateChanged,\n /* excludesMetadataChanges= */ true\n );\n }\n let raisedEvent = false;\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n raisedEvent = true;\n }\n } else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n raisedEvent = true;\n }\n\n this.snap = snap;\n return raisedEvent;\n }\n\n onError(error: Error): void {\n this.queryObserver.error(error);\n }\n\n /** Returns whether a snapshot was raised. */\n applyOnlineStateChange(onlineState: OnlineState): boolean {\n this.onlineState = onlineState;\n let raisedEvent = false;\n if (\n this.snap &&\n !this.raisedInitialEvent &&\n this.shouldRaiseInitialEvent(this.snap, onlineState)\n ) {\n this.raiseInitialEvent(this.snap);\n raisedEvent = true;\n }\n return raisedEvent;\n }\n\n private shouldRaiseInitialEvent(\n snap: ViewSnapshot,\n onlineState: OnlineState\n ): boolean {\n assert(\n !this.raisedInitialEvent,\n 'Determining whether to raise first event but already had first event'\n );\n\n // Always raise the first event when we're synced\n if (!snap.fromCache) {\n return true;\n }\n\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const maybeOnline = onlineState !== OnlineState.Offline;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(\n snap.fromCache,\n 'Waiting for sync, but snapshot is not from cache'\n );\n return false;\n }\n\n // Raise data from cache if we have any documents or we are offline\n return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;\n }\n\n private shouldRaiseEvent(snap: ViewSnapshot): boolean {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (snap.docChanges.length > 0) {\n return true;\n }\n\n const hasPendingWritesChanged =\n this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeMetadataChanges === true;\n }\n\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n return false;\n }\n\n private raiseInitialEvent(snap: ViewSnapshot): void {\n assert(\n !this.raisedInitialEvent,\n 'Trying to raise initial events for second time'\n );\n snap = ViewSnapshot.fromInitialDocuments(\n snap.query,\n snap.docs,\n snap.mutatedKeys,\n snap.fromCache\n );\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Deferred } from '../util/promise';\nimport { TimerId, AsyncQueue } from '../util/async_queue';\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Transaction } from './transaction';\nimport { RemoteStore } from '../remote/remote_store';\nimport { isNullOrUndefined } from '../util/types';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { FirestoreError } from '../util/error';\n\nconst RETRY_COUNT = 5;\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner<T> {\n private retries = RETRY_COUNT;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly remoteStore: RemoteStore,\n private readonly updateFunction: (transaction: Transaction) => Promise<T>,\n private readonly deferred: Deferred<T>\n ) {\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.RetryTransaction\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = this.remoteStore.createTransaction();\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise<T> | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.retries > 0 && this.isRetryableTransactionError(error)) {\n this.retries -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error): boolean {\n if (error.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { IndexFreeQueryEngine } from '../local/index_free_query_engine';\nimport { LocalStore } from '../local/local_store';\nimport { MemoryPersistenceProvider } from '../local/memory_persistence';\nimport {\n GarbageCollectionScheduler,\n Persistence,\n PersistenceProvider\n} from '../local/persistence';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { Platform } from '../platform/platform';\nimport { Datastore } from '../remote/datastore';\nimport { RemoteStore } from '../remote/remote_store';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { debug } from '../util/log';\nimport { Deferred } from '../util/promise';\nimport {\n EventManager,\n ListenOptions,\n Observer,\n QueryListener\n} from './event_manager';\nimport { SyncEngine } from './sync_engine';\nimport { View } from './view';\n\nimport { SharedClientState } from '../local/shared_client_state';\nimport { AutoId } from '../util/misc';\nimport { DatabaseId, DatabaseInfo } from './database_info';\nimport { Query } from './query';\nimport { Transaction } from './transaction';\nimport { OnlineState, OnlineStateSource } from './types';\nimport { ViewSnapshot } from './view_snapshot';\n\nconst LOG_TAG = 'FirestoreClient';\n\n/** DOMException error code constants. */\nconst DOM_EXCEPTION_INVALID_STATE = 11;\nconst DOM_EXCEPTION_ABORTED = 20;\nconst DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\n\nexport type PersistenceSettings =\n | {\n readonly durable: false;\n }\n | {\n readonly durable: true;\n readonly cacheSizeBytes: number;\n readonly synchronizeTabs: boolean;\n };\n\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the\n * pieces of the client SDK architecture. It is responsible for creating the\n * async queue that is shared by all of the other components in the system.\n */\nexport class FirestoreClient {\n // NOTE: These should technically have '|undefined' in the types, since\n // they're initialized asynchronously rather than in the constructor, but\n // given that all work is done on the async queue and we assert that\n // initialization completes before any other work is queued, we're cheating\n // with the types rather than littering the code with '!' or unnecessary\n // undefined checks.\n private eventMgr!: EventManager;\n private persistence!: Persistence;\n private localStore!: LocalStore;\n private remoteStore!: RemoteStore;\n private syncEngine!: SyncEngine;\n private gcScheduler!: GarbageCollectionScheduler;\n\n // PORTING NOTE: SharedClientState is only used for multi-tab web.\n private sharedClientState!: SharedClientState;\n\n private readonly clientId = AutoId.newId();\n\n constructor(\n private platform: Platform,\n private databaseInfo: DatabaseInfo,\n private credentials: CredentialsProvider,\n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n private asyncQueue: AsyncQueue\n ) {}\n\n /**\n * Starts up the FirestoreClient, returning only whether or not enabling\n * persistence succeeded.\n *\n * The intent here is to \"do the right thing\" as far as users are concerned.\n * Namely, in cases where offline persistence is requested and possible,\n * enable it, but otherwise fall back to persistence disabled. For the most\n * part we expect this to succeed one way or the other so we don't expect our\n * users to actually wait on the firestore.enablePersistence Promise since\n * they generally won't care.\n *\n * Of course some users actually do care about whether or not persistence\n * was successfully enabled, so the Promise returned from this method\n * indicates this outcome.\n *\n * This presents a problem though: even before enablePersistence resolves or\n * rejects, users may have made calls to e.g. firestore.collection() which\n * means that the FirestoreClient in there will be available and will be\n * enqueuing actions on the async queue.\n *\n * Meanwhile any failure of an operation on the async queue causes it to\n * panic and reject any further work, on the premise that unhandled errors\n * are fatal.\n *\n * Consequently the fallback is handled internally here in start, and if the\n * fallback succeeds we signal success to the async queue even though the\n * start() itself signals failure.\n *\n * @param persistenceProvider Provider that returns the persistence\n * implementation.\n * @param persistenceSettings Settings object to configure offline\n * persistence.\n * @returns A deferred result indicating the user-visible result of enabling\n * offline persistence. This method will reject this if IndexedDB fails to\n * start for any reason. If usePersistence is false this is\n * unconditionally resolved.\n */\n start(\n persistenceProvider: PersistenceProvider,\n persistenceSettings: PersistenceSettings\n ): Promise<void> {\n this.verifyNotTerminated();\n // We defer our initialization until we get the current user from\n // setChangeListener(). We block the async queue until we got the initial\n // user and the initialization is completed. This will prevent any scheduled\n // work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n const initializationDone = new Deferred<void>();\n\n // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n const persistenceResult = new Deferred<void>();\n\n let initialized = false;\n this.credentials.setChangeListener(user => {\n if (!initialized) {\n initialized = true;\n\n this.initializePersistence(\n persistenceProvider,\n persistenceSettings,\n user,\n persistenceResult\n )\n .then(() => this.initializeRest(user))\n .then(initializationDone.resolve, initializationDone.reject);\n } else {\n this.asyncQueue.enqueueAndForget(() => {\n return this.handleCredentialChange(user);\n });\n }\n });\n\n // Block the async queue until initialization is done\n this.asyncQueue.enqueueAndForget(() => {\n return initializationDone.promise;\n });\n\n // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n return persistenceResult.promise;\n }\n\n /** Enables the network connection and requeues all pending operations. */\n enableNetwork(): Promise<void> {\n this.verifyNotTerminated();\n return this.asyncQueue.enqueue(() => {\n return this.syncEngine.enableNetwork();\n });\n }\n\n /**\n * Initializes persistent storage, attempting to use IndexedDB if\n * usePersistence is true or memory-only if false.\n *\n * If IndexedDB fails because it's already open in another tab or because the\n * platform can't possibly support our implementation then this method rejects\n * the persistenceResult and falls back on memory-only persistence.\n *\n * @param persistenceProvider The provider that provides either IndexedDb or\n * memory-backed persistence\n * @param persistenceSettings Settings object to configure offline persistence\n * @param user The initial user\n * @param persistenceResult A deferred result indicating the user-visible\n * result of enabling offline persistence. This method will reject this if\n * IndexedDB fails to start for any reason. If usePersistence is false\n * this is unconditionally resolved.\n * @returns a Promise indicating whether or not initialization should\n * continue, i.e. that one of the persistence implementations actually\n * succeeded.\n */\n private async initializePersistence(\n persistenceProvider: PersistenceProvider,\n persistenceSettings: PersistenceSettings,\n user: User,\n persistenceResult: Deferred<void>\n ): Promise<void> {\n try {\n await persistenceProvider.initialize(\n this.asyncQueue,\n this.databaseInfo,\n this.platform,\n this.clientId,\n user,\n persistenceSettings\n );\n\n this.persistence = persistenceProvider.getPersistence();\n this.gcScheduler = persistenceProvider.getGarbageCollectionScheduler();\n this.sharedClientState = persistenceProvider.getSharedClientState();\n persistenceResult.resolve();\n } catch (error) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error);\n\n // An unknown failure on the first stage shuts everything down.\n if (!this.canFallback(error)) {\n throw error;\n }\n console.warn(\n 'Error enabling offline persistence. Falling back to' +\n ' persistence disabled: ' +\n error\n );\n return this.initializePersistence(\n new MemoryPersistenceProvider(),\n { durable: false },\n user,\n persistenceResult\n );\n }\n }\n\n /**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\n private canFallback(error: FirestoreError | DOMException): boolean {\n if (error.name === 'FirebaseError') {\n return (\n error.code === Code.FAILED_PRECONDITION ||\n error.code === Code.UNIMPLEMENTED\n );\n } else if (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException\n ) {\n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n return (\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n error.code === DOM_EXCEPTION_QUOTA_EXCEEDED ||\n error.code === DOM_EXCEPTION_ABORTED ||\n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n error.code === DOM_EXCEPTION_INVALID_STATE\n );\n }\n\n return true;\n }\n\n /**\n * Checks that the client has not been terminated. Ensures that other methods on\n * this class cannot be called after the client is terminated.\n */\n private verifyNotTerminated(): void {\n if (this.asyncQueue.isShuttingDown) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'The client has already been terminated.'\n );\n }\n }\n\n /**\n * Initializes the rest of the FirestoreClient, assuming the initial user\n * has been obtained from the credential provider and some persistence\n * implementation is available in this.persistence.\n */\n private initializeRest(user: User): Promise<void> {\n debug(LOG_TAG, 'Initializing. user=', user.uid);\n return this.platform\n .loadConnection(this.databaseInfo)\n .then(async connection => {\n const queryEngine = new IndexFreeQueryEngine();\n this.localStore = new LocalStore(this.persistence, queryEngine, user);\n await this.localStore.start();\n const connectivityMonitor = this.platform.newConnectivityMonitor();\n const serializer = this.platform.newSerializer(\n this.databaseInfo.databaseId\n );\n const datastore = new Datastore(\n this.asyncQueue,\n connection,\n this.credentials,\n serializer\n );\n\n const remoteStoreOnlineStateChangedHandler = (\n onlineState: OnlineState\n ): void =>\n this.syncEngine.applyOnlineStateChange(\n onlineState,\n OnlineStateSource.RemoteStore\n );\n const sharedClientStateOnlineStateChangedHandler = (\n onlineState: OnlineState\n ): void =>\n this.syncEngine.applyOnlineStateChange(\n onlineState,\n OnlineStateSource.SharedClientState\n );\n\n this.remoteStore = new RemoteStore(\n this.localStore,\n datastore,\n this.asyncQueue,\n remoteStoreOnlineStateChangedHandler,\n connectivityMonitor\n );\n\n this.syncEngine = new SyncEngine(\n this.localStore,\n this.remoteStore,\n this.sharedClientState,\n user\n );\n\n this.sharedClientState.onlineStateHandler = sharedClientStateOnlineStateChangedHandler;\n\n // Set up wiring between sync engine and other components\n this.remoteStore.syncEngine = this.syncEngine;\n this.sharedClientState.syncEngine = this.syncEngine;\n\n this.eventMgr = new EventManager(this.syncEngine);\n\n // PORTING NOTE: LocalStore doesn't need an explicit start() on the Web.\n await this.sharedClientState.start();\n await this.remoteStore.start();\n\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.setPrimaryStateListener(async isPrimary => {\n await this.syncEngine.applyPrimaryState(isPrimary);\n if (isPrimary && !this.gcScheduler.started) {\n this.gcScheduler.start(this.localStore);\n } else if (!isPrimary) {\n this.gcScheduler.stop();\n }\n });\n\n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n await this.persistence.setDatabaseDeletedListener(async () => {\n await this.terminate();\n });\n });\n }\n\n private handleCredentialChange(user: User): Promise<void> {\n this.asyncQueue.verifyOperationInProgress();\n\n debug(LOG_TAG, 'Credential Changed. Current user: ' + user.uid);\n return this.syncEngine.handleCredentialChange(user);\n }\n\n /** Disables the network connection. Pending operations will not complete. */\n disableNetwork(): Promise<void> {\n this.verifyNotTerminated();\n return this.asyncQueue.enqueue(() => {\n return this.syncEngine.disableNetwork();\n });\n }\n\n terminate(): Promise<void> {\n return this.asyncQueue.enqueueAndInitiateShutdown(async () => {\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n this.gcScheduler.stop();\n await this.remoteStore.shutdown();\n await this.sharedClientState.shutdown();\n await this.persistence.shutdown();\n\n // `removeChangeListener` must be called after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving\n // auth tokens.\n this.credentials.removeChangeListener();\n });\n }\n\n /**\n * Returns a Promise that resolves when all writes that were pending at the time this\n * method was called received server acknowledgement. An acknowledgement can be either acceptance\n * or rejection.\n */\n waitForPendingWrites(): Promise<void> {\n this.verifyNotTerminated();\n\n const deferred = new Deferred<void>();\n this.asyncQueue.enqueueAndForget(() => {\n return this.syncEngine.registerPendingWritesCallback(deferred);\n });\n return deferred.promise;\n }\n\n listen(\n query: Query,\n observer: Observer<ViewSnapshot>,\n options: ListenOptions\n ): QueryListener {\n this.verifyNotTerminated();\n const listener = new QueryListener(query, observer, options);\n this.asyncQueue.enqueueAndForget(() => {\n return this.eventMgr.listen(listener);\n });\n return listener;\n }\n\n unlisten(listener: QueryListener): void {\n // Checks for termination but does not raise error, allowing unlisten after\n // termination to be a no-op.\n if (this.clientTerminated) {\n return;\n }\n this.asyncQueue.enqueueAndForget(() => {\n return this.eventMgr.unlisten(listener);\n });\n }\n\n getDocumentFromLocalCache(docKey: DocumentKey): Promise<Document | null> {\n this.verifyNotTerminated();\n return this.asyncQueue\n .enqueue(() => {\n return this.localStore.readDocument(docKey);\n })\n .then((maybeDoc: MaybeDocument | null) => {\n if (maybeDoc instanceof Document) {\n return maybeDoc;\n } else if (maybeDoc instanceof NoDocument) {\n return null;\n } else {\n throw new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from cache. (However, this document may ' +\n \"exist on the server. Run again without setting 'source' in \" +\n 'the GetOptions to attempt to retrieve the document from the ' +\n 'server.)'\n );\n }\n });\n }\n\n getDocumentsFromLocalCache(query: Query): Promise<ViewSnapshot> {\n this.verifyNotTerminated();\n return this.asyncQueue.enqueue(async () => {\n const queryResult = await this.localStore.executeQuery(\n query,\n /* usePreviousResults= */ true\n );\n const view = new View(query, queryResult.remoteKeys);\n const viewDocChanges = view.computeDocChanges(queryResult.documents);\n return view.applyChanges(\n viewDocChanges,\n /* updateLimboDocuments= */ false\n ).snapshot!;\n });\n }\n\n write(mutations: Mutation[]): Promise<void> {\n this.verifyNotTerminated();\n const deferred = new Deferred<void>();\n this.asyncQueue.enqueueAndForget(() =>\n this.syncEngine.write(mutations, deferred)\n );\n return deferred.promise;\n }\n\n databaseId(): DatabaseId {\n return this.databaseInfo.databaseId;\n }\n\n addSnapshotsInSyncListener(observer: Observer<void>): void {\n this.verifyNotTerminated();\n this.asyncQueue.enqueueAndForget(() => {\n this.eventMgr.addSnapshotsInSyncListener(observer);\n return Promise.resolve();\n });\n }\n\n removeSnapshotsInSyncListener(observer: Observer<void>): void {\n // Checks for shutdown but does not raise error, allowing remove after\n // shutdown to be a no-op.\n if (this.clientTerminated) {\n return;\n }\n this.eventMgr.removeSnapshotsInSyncListener(observer);\n }\n\n get clientTerminated(): boolean {\n // Technically, the asyncQueue is still running, but only accepting operations\n // related to termination or supposed to be run after termination. It is effectively\n // terminated to the eyes of users.\n return this.asyncQueue.isShuttingDown;\n }\n\n transaction<T>(\n updateFunction: (transaction: Transaction) => Promise<T>\n ): Promise<T> {\n this.verifyNotTerminated();\n const deferred = new Deferred<T>();\n this.asyncQueue.enqueueAndForget(() => {\n this.syncEngine.runTransaction(this.asyncQueue, updateFunction, deferred);\n return Promise.resolve();\n });\n return deferred.promise;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Observer } from '../core/event_manager';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer<T> that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nexport class AsyncObserver<T> implements Observer<T> {\n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n private muted = false;\n\n constructor(private observer: Observer<T>) {}\n\n next(value: T): void {\n this.scheduleEvent(this.observer.next, value);\n }\n\n error(error: Error): void {\n this.scheduleEvent(this.observer.error, error);\n }\n\n mute(): void {\n this.muted = true;\n }\n\n private scheduleEvent<E>(eventHandler: EventHandler<E>, event: E): void {\n if (!this.muted) {\n setTimeout(() => {\n if (!this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { JsonObject } from '../model/field_value';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver<T> {\n next?: NextFn<T>;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport interface Unsubscribe {\n (): void;\n}\n\nexport function isPartialObserver(obj: unknown): boolean {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject<unknown>;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * as firestore from '@firebase/firestore-types';\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseService, _FirebaseApp } from '@firebase/app-types/private';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { ListenOptions } from '../core/event_manager';\nimport { FirestoreClient, PersistenceSettings } from '../core/firestore_client';\nimport {\n Bound,\n Direction,\n FieldFilter,\n Filter,\n Operator,\n OrderBy,\n Query as InternalQuery\n} from '../core/query';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport { ChangeType, ViewSnapshot } from '../core/view_snapshot';\nimport { LruParams } from '../local/lru_garbage_collector';\nimport { MemoryPersistenceProvider } from '../local/memory_persistence';\nimport { PersistenceProvider } from '../local/persistence';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n ArrayValue,\n FieldValue,\n FieldValueOptions,\n ObjectValue,\n RefValue,\n ServerTimestampValue\n} from '../model/field_value';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { FieldPath, ResourcePath } from '../model/path';\nimport { PlatformSupport } from '../platform/platform';\nimport { makeConstructorPrivate } from '../util/api';\nimport { assert, fail } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport {\n invalidClassError,\n validateArgType,\n validateAtLeastNumberOfArgs,\n validateBetweenNumberOfArgs,\n validateDefined,\n validateExactNumberOfArgs,\n validateNamedOptionalPropertyEquals,\n validateNamedOptionalType,\n validateNamedType,\n validateOptionalArgType,\n validateOptionalArrayElements,\n validateOptionNames,\n validatePositiveNumber,\n validateStringEnum,\n valueDescription\n} from '../util/input_validation';\n// eslint-disable-next-line import/no-duplicates\nimport * as log from '../util/log';\n// eslint-disable-next-line import/no-duplicates\nimport { LogLevel } from '../util/log';\nimport { AutoId } from '../util/misc';\nimport * as objUtils from '../util/obj';\nimport { Deferred, Rejecter, Resolver } from '../util/promise';\nimport { FieldPath as ExternalFieldPath } from './field_path';\n\nimport {\n CredentialsProvider,\n CredentialsSettings,\n EmptyCredentialsProvider,\n FirebaseCredentialsProvider,\n makeCredentialsProvider\n} from './credentials';\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver,\n Unsubscribe\n} from './observer';\nimport {\n DocumentKeyReference,\n fieldPathFromArgument,\n UserDataConverter\n} from './user_data_converter';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\n// settings() defaults:\nconst DEFAULT_HOST = 'firestore.googleapis.com';\nconst DEFAULT_SSL = true;\nconst DEFAULT_TIMESTAMPS_IN_SNAPSHOTS = true;\nconst DEFAULT_FORCE_LONG_POLLING = false;\n\n/**\n * Constant used to indicate the LRU garbage collection should be disabled.\n * Set this value as the `cacheSizeBytes` on the settings passed to the\n * `Firestore` instance.\n */\nexport const CACHE_SIZE_UNLIMITED = LruParams.COLLECTION_DISABLED;\n\n// enablePersistence() defaults:\nconst DEFAULT_SYNCHRONIZE_TABS = false;\n\n/** Undocumented, private additional settings not exposed in our public API. */\ninterface PrivateSettings extends firestore.Settings {\n // Can be a google-auth-library or gapi client.\n credentials?: CredentialsSettings;\n}\n\n/**\n * Options that can be provided in the Firestore constructor when not using\n * Firebase (aka standalone mode).\n */\nexport interface FirestoreDatabase {\n projectId: string;\n database?: string;\n}\n\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied firestore.Settings object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass FirestoreSettings {\n /** The hostname to connect to. */\n readonly host: string;\n\n /** Whether to use SSL when connecting. */\n readonly ssl: boolean;\n\n readonly timestampsInSnapshots: boolean;\n\n readonly cacheSizeBytes: number;\n\n readonly forceLongPolling: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n validateNamedType('settings', 'non-empty string', 'host', settings.host);\n this.host = settings.host;\n\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = objUtils.defaulted(settings.ssl, DEFAULT_SSL);\n }\n validateOptionNames('settings', settings, [\n 'host',\n 'ssl',\n 'credentials',\n 'timestampsInSnapshots',\n 'cacheSizeBytes',\n 'experimentalForceLongPolling'\n ]);\n\n validateNamedOptionalType(\n 'settings',\n 'object',\n 'credentials',\n settings.credentials\n );\n this.credentials = settings.credentials;\n\n validateNamedOptionalType(\n 'settings',\n 'boolean',\n 'timestampsInSnapshots',\n settings.timestampsInSnapshots\n );\n\n // Nobody should set timestampsInSnapshots anymore, but the error depends on\n // whether they set it to true or false...\n if (settings.timestampsInSnapshots === true) {\n log.error(`\n The timestampsInSnapshots setting now defaults to true and you no\n longer need to explicitly set it. In a future release, the setting\n will be removed entirely and so it is recommended that you remove it\n from your firestore.settings() call now.`);\n } else if (settings.timestampsInSnapshots === false) {\n log.error(`\n The timestampsInSnapshots setting will soon be removed. YOU MUST UPDATE\n YOUR CODE.\n\n To hide this warning, stop using the timestampsInSnapshots setting in your\n firestore.settings({ ... }) call.\n\n Once you remove the setting, Timestamps stored in Cloud Firestore will be\n read back as Firebase Timestamp objects instead of as system Date objects.\n So you will also need to update code expecting a Date to instead expect a\n Timestamp. For example:\n\n // Old:\n const date = snapshot.get('created_at');\n // New:\n const timestamp = snapshot.get('created_at'); const date =\n timestamp.toDate();\n\n Please audit all existing usages of Date when you enable the new\n behavior.`);\n }\n this.timestampsInSnapshots = objUtils.defaulted(\n settings.timestampsInSnapshots,\n DEFAULT_TIMESTAMPS_IN_SNAPSHOTS\n );\n\n validateNamedOptionalType(\n 'settings',\n 'number',\n 'cacheSizeBytes',\n settings.cacheSizeBytes\n );\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LruParams.DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED &&\n settings.cacheSizeBytes < LruParams.MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LruParams.MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateNamedOptionalType(\n 'settings',\n 'boolean',\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling\n );\n this.forceLongPolling =\n settings.experimentalForceLongPolling === undefined\n ? DEFAULT_FORCE_LONG_POLLING\n : settings.experimentalForceLongPolling;\n }\n\n isEqual(other: FirestoreSettings): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.timestampsInSnapshots === other.timestampsInSnapshots &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.forceLongPolling === other.forceLongPolling\n );\n }\n}\n\n/**\n * The root reference to the database.\n */\nexport class Firestore implements firestore.FirebaseFirestore, FirebaseService {\n // The objects that are a part of this API are exposed to third-parties as\n // compiled javascript so we want to flag our private members with a leading\n // underscore to discourage their use.\n readonly _databaseId: DatabaseId;\n private readonly _persistenceKey: string;\n private readonly _persistenceProvider: PersistenceProvider;\n private _credentials: CredentialsProvider;\n private readonly _firebaseApp: FirebaseApp | null = null;\n private _settings: FirestoreSettings;\n\n // The firestore client instance. This will be available as soon as\n // configureClient is called, but any calls against it will block until\n // setup has completed.\n //\n // Operations on the _firestoreClient don't block on _firestoreReady. Those\n // are already set to synchronize on the async queue.\n private _firestoreClient: FirestoreClient | undefined;\n\n // Public for use in tests.\n // TODO(mikelehen): Use modularized initialization instead.\n readonly _queue = new AsyncQueue();\n\n readonly _dataConverter: UserDataConverter;\n\n // Note: We are using `MemoryPersistenceProvider` as a default\n // PersistenceProvider to ensure backwards compatibility with the format\n // expected by the console build.\n constructor(\n databaseIdOrApp: FirestoreDatabase | FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n persistenceProvider: PersistenceProvider = new MemoryPersistenceProvider()\n ) {\n if (typeof (databaseIdOrApp as FirebaseApp).options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n const app = databaseIdOrApp as FirebaseApp;\n this._firebaseApp = app;\n this._databaseId = Firestore.databaseIdFromApp(app);\n this._persistenceKey = app.name;\n this._credentials = new FirebaseCredentialsProvider(authProvider);\n } else {\n const external = databaseIdOrApp as FirestoreDatabase;\n if (!external.projectId) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Must provide projectId'\n );\n }\n\n this._databaseId = new DatabaseId(external.projectId, external.database);\n // Use a default persistenceKey that lines up with FirebaseApp.\n this._persistenceKey = '[DEFAULT]';\n this._credentials = new EmptyCredentialsProvider();\n }\n\n this._persistenceProvider = persistenceProvider;\n this._settings = new FirestoreSettings({});\n this._dataConverter = this.createDataConverter(this._databaseId);\n }\n\n settings(settingsLiteral: firestore.Settings): void {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n\n if (\n objUtils.contains(settingsLiteral as objUtils.Dict<{}>, 'persistence')\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"persistence\" is now specified with a separate call to ' +\n 'firestore.enablePersistence().'\n );\n }\n\n const newSettings = new FirestoreSettings(settingsLiteral);\n if (this._firestoreClient && !this._settings.isEqual(newSettings)) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and its settings can no longer ' +\n 'be changed. You can only call settings() before calling any other ' +\n 'methods on a Firestore object.'\n );\n }\n\n this._settings = newSettings;\n if (newSettings.credentials !== undefined) {\n this._credentials = makeCredentialsProvider(newSettings.credentials);\n }\n }\n\n enableNetwork(): Promise<void> {\n this.ensureClientConfigured();\n return this._firestoreClient!.enableNetwork();\n }\n\n disableNetwork(): Promise<void> {\n this.ensureClientConfigured();\n return this._firestoreClient!.disableNetwork();\n }\n\n enablePersistence(settings?: firestore.PersistenceSettings): Promise<void> {\n if (this._firestoreClient) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Firestore has already been started and persistence can no longer ' +\n 'be enabled. You can only call enablePersistence() before calling ' +\n 'any other methods on a Firestore object.'\n );\n }\n\n let synchronizeTabs = false;\n\n if (settings) {\n if (settings.experimentalTabSynchronization !== undefined) {\n log.error(\n \"The 'experimentalTabSynchronization' setting has been renamed to \" +\n \"'synchronizeTabs'. In a future release, the setting will be removed \" +\n 'and it is recommended that you update your ' +\n \"firestore.enablePersistence() call to use 'synchronizeTabs'.\"\n );\n }\n synchronizeTabs = objUtils.defaulted(\n settings.synchronizeTabs !== undefined\n ? settings.synchronizeTabs\n : settings.experimentalTabSynchronization,\n DEFAULT_SYNCHRONIZE_TABS\n );\n }\n\n return this.configureClient(this._persistenceProvider, {\n durable: true,\n cacheSizeBytes: this._settings.cacheSizeBytes,\n synchronizeTabs\n });\n }\n\n async clearPersistence(): Promise<void> {\n if (\n this._firestoreClient !== undefined &&\n !this._firestoreClient.clientTerminated\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Persistence cannot be cleared after this Firestore instance is initialized.'\n );\n }\n\n const deferred = new Deferred<void>();\n this._queue.enqueueAndForgetEvenAfterShutdown(async () => {\n try {\n const databaseInfo = this.makeDatabaseInfo();\n await this._persistenceProvider.clearPersistence(databaseInfo);\n deferred.resolve();\n } catch (e) {\n deferred.reject(e);\n }\n });\n return deferred.promise;\n }\n\n terminate(): Promise<void> {\n (this.app as _FirebaseApp)._removeServiceInstance('firestore');\n return this.INTERNAL.delete();\n }\n\n get _isTerminated(): boolean {\n this.ensureClientConfigured();\n return this._firestoreClient!.clientTerminated;\n }\n\n waitForPendingWrites(): Promise<void> {\n this.ensureClientConfigured();\n return this._firestoreClient!.waitForPendingWrites();\n }\n\n onSnapshotsInSync(observer: PartialObserver<void>): Unsubscribe;\n onSnapshotsInSync(onSync: () => void): Unsubscribe;\n onSnapshotsInSync(arg: unknown): Unsubscribe {\n this.ensureClientConfigured();\n\n if (isPartialObserver(arg)) {\n return this.onSnapshotsInSyncInternal(arg as PartialObserver<void>);\n } else {\n validateArgType('Firestore.onSnapshotsInSync', 'function', 1, arg);\n const observer: PartialObserver<void> = {\n next: arg as () => void\n };\n return this.onSnapshotsInSyncInternal(observer);\n }\n }\n\n private onSnapshotsInSyncInternal(\n observer: PartialObserver<void>\n ): Unsubscribe {\n const errHandler = (err: Error): void => {\n throw fail('Uncaught Error in onSnapshotsInSync');\n };\n const asyncObserver = new AsyncObserver<void>({\n next: () => {\n if (observer.next) {\n observer.next();\n }\n },\n error: errHandler\n });\n this._firestoreClient!.addSnapshotsInSyncListener(asyncObserver);\n return () => {\n asyncObserver.mute();\n this._firestoreClient!.removeSnapshotsInSyncListener(asyncObserver);\n };\n }\n\n ensureClientConfigured(): FirestoreClient {\n if (!this._firestoreClient) {\n // Kick off starting the client but don't actually wait for it.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.configureClient(new MemoryPersistenceProvider(), {\n durable: false\n });\n }\n return this._firestoreClient as FirestoreClient;\n }\n\n private makeDatabaseInfo(): DatabaseInfo {\n return new DatabaseInfo(\n this._databaseId,\n this._persistenceKey,\n this._settings.host,\n this._settings.ssl,\n this._settings.forceLongPolling\n );\n }\n\n private configureClient(\n persistenceProvider: PersistenceProvider,\n persistenceSettings: PersistenceSettings\n ): Promise<void> {\n assert(!!this._settings.host, 'FirestoreSettings.host is not set');\n\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n\n const databaseInfo = this.makeDatabaseInfo();\n\n this._firestoreClient = new FirestoreClient(\n PlatformSupport.getPlatform(),\n databaseInfo,\n this._credentials,\n this._queue\n );\n\n return this._firestoreClient.start(\n persistenceProvider,\n persistenceSettings\n );\n }\n\n private createDataConverter(databaseId: DatabaseId): UserDataConverter {\n const preConverter = (value: unknown): unknown => {\n if (value instanceof DocumentReference) {\n const thisDb = databaseId;\n const otherDb = value.firestore._databaseId;\n if (!otherDb.isEqual(thisDb)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Document reference is for database ' +\n `${otherDb.projectId}/${otherDb.database} but should be ` +\n `for database ${thisDb.projectId}/${thisDb.database}`\n );\n }\n return new DocumentKeyReference(databaseId, value._key);\n } else {\n return value;\n }\n };\n return new UserDataConverter(preConverter);\n }\n\n private static databaseIdFromApp(app: FirebaseApp): DatabaseId {\n const options = app.options as objUtils.Dict<{}>;\n if (!objUtils.contains(options, 'projectId')) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n '\"projectId\" not provided in firebase.initializeApp.'\n );\n }\n\n const projectId = options['projectId'];\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'projectId must be a string in FirebaseApp.options'\n );\n }\n return new DatabaseId(projectId);\n }\n\n get app(): FirebaseApp {\n if (!this._firebaseApp) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._firebaseApp;\n }\n\n INTERNAL = {\n delete: async (): Promise<void> => {\n // The client must be initalized to ensure that all subsequent API usage\n // throws an exception.\n this.ensureClientConfigured();\n await this._firestoreClient!.terminate();\n }\n };\n\n collection(pathString: string): firestore.CollectionReference {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'non-empty string', 1, pathString);\n this.ensureClientConfigured();\n return new CollectionReference(ResourcePath.fromString(pathString), this);\n }\n\n doc(pathString: string): firestore.DocumentReference {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'non-empty string', 1, pathString);\n this.ensureClientConfigured();\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\n }\n\n collectionGroup(collectionId: string): firestore.Query {\n validateExactNumberOfArgs('Firestore.collectionGroup', arguments, 1);\n validateArgType(\n 'Firestore.collectionGroup',\n 'non-empty string',\n 1,\n collectionId\n );\n if (collectionId.indexOf('/') >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid collection ID '${collectionId}' passed to function ` +\n `Firestore.collectionGroup(). Collection IDs must not contain '/'.`\n );\n }\n this.ensureClientConfigured();\n return new Query(\n new InternalQuery(ResourcePath.EMPTY_PATH, collectionId),\n this\n );\n }\n\n runTransaction<T>(\n updateFunction: (transaction: firestore.Transaction) => Promise<T>\n ): Promise<T> {\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(\n (transaction: InternalTransaction) => {\n return updateFunction(new Transaction(this, transaction));\n }\n );\n }\n\n batch(): firestore.WriteBatch {\n this.ensureClientConfigured();\n\n return new WriteBatch(this);\n }\n\n static get logLevel(): firestore.LogLevel {\n switch (log.getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n case LogLevel.ERROR:\n return 'error';\n case LogLevel.SILENT:\n return 'silent';\n default:\n return fail('Unknown log level: ' + log.getLogLevel());\n }\n }\n\n static setLogLevel(level: firestore.LogLevel): void {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'non-empty string', 1, level);\n switch (level) {\n case 'debug':\n log.setLogLevel(log.LogLevel.DEBUG);\n break;\n case 'error':\n log.setLogLevel(log.LogLevel.ERROR);\n break;\n case 'silent':\n log.setLogLevel(log.LogLevel.SILENT);\n break;\n default:\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid log level: ' + level\n );\n }\n }\n\n // Note: this is not a property because the minifier can't work correctly with\n // the way TypeScript compiler outputs properties.\n _areTimestampsInSnapshotsEnabled(): boolean {\n return this._settings.timestampsInSnapshots;\n }\n}\n\n/**\n * A reference to a transaction.\n */\nexport class Transaction implements firestore.Transaction {\n constructor(\n private _firestore: Firestore,\n private _transaction: InternalTransaction\n ) {}\n\n get<T>(\n documentRef: firestore.DocumentReference<T>\n ): Promise<firestore.DocumentSnapshot<T>> {\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n const ref = validateReference(\n 'Transaction.get',\n documentRef,\n this._firestore\n );\n return this._transaction\n .lookup([ref._key])\n .then((docs: MaybeDocument[]) => {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc instanceof NoDocument) {\n return new DocumentSnapshot<T>(\n this._firestore,\n ref._key,\n null,\n /* fromCache= */ false,\n /* hasPendingWrites= */ false,\n ref._converter\n );\n } else if (doc instanceof Document) {\n return new DocumentSnapshot<T>(\n this._firestore,\n ref._key,\n doc,\n /* fromCache= */ false,\n /* hasPendingWrites= */ false,\n ref._converter\n );\n } else {\n throw fail(\n `BatchGetDocumentsRequest returned unexpected document type: ${doc.constructor.name}`\n );\n }\n });\n }\n\n set<T>(\n documentRef: firestore.DocumentReference<T>,\n value: T,\n options?: firestore.SetOptions\n ): Transaction {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n const ref = validateReference(\n 'Transaction.set',\n documentRef,\n this._firestore\n );\n options = validateSetOptions('Transaction.set', options);\n const [convertedValue, functionName] = applyFirestoreDataConverter(\n ref._converter,\n value,\n 'Transaction.set'\n );\n const parsed =\n options.merge || options.mergeFields\n ? this._firestore._dataConverter.parseMergeData(\n functionName,\n convertedValue,\n options.mergeFields\n )\n : this._firestore._dataConverter.parseSetData(\n functionName,\n convertedValue\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n update(\n documentRef: firestore.DocumentReference<unknown>,\n value: firestore.UpdateData\n ): Transaction;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n field: string | ExternalFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction {\n let ref;\n let parsed;\n\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath\n ) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference(\n 'Transaction.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateVarargs(\n 'Transaction.update',\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference(\n 'Transaction.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateData(\n 'Transaction.update',\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n delete(documentRef: firestore.DocumentReference<unknown>): Transaction {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n const ref = validateReference(\n 'Transaction.delete',\n documentRef,\n this._firestore\n );\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\nexport class WriteBatch implements firestore.WriteBatch {\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n constructor(private _firestore: Firestore) {}\n\n set<T>(\n documentRef: firestore.DocumentReference<T>,\n value: T,\n options?: firestore.SetOptions\n ): WriteBatch {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n const ref = validateReference(\n 'WriteBatch.set',\n documentRef,\n this._firestore\n );\n options = validateSetOptions('WriteBatch.set', options);\n const [convertedValue, functionName] = applyFirestoreDataConverter(\n ref._converter,\n value,\n 'WriteBatch.set'\n );\n const parsed =\n options.merge || options.mergeFields\n ? this._firestore._dataConverter.parseMergeData(\n functionName,\n convertedValue,\n options.mergeFields\n )\n : this._firestore._dataConverter.parseSetData(\n functionName,\n convertedValue\n );\n this._mutations = this._mutations.concat(\n parsed.toMutations(ref._key, Precondition.NONE)\n );\n return this;\n }\n\n update(\n documentRef: firestore.DocumentReference<unknown>,\n value: firestore.UpdateData\n ): WriteBatch;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n field: string | ExternalFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: firestore.DocumentReference<unknown>,\n fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this.verifyNotCommitted();\n\n let ref;\n let parsed;\n\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath\n ) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference(\n 'WriteBatch.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateVarargs(\n 'WriteBatch.update',\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference(\n 'WriteBatch.update',\n documentRef,\n this._firestore\n );\n parsed = this._firestore._dataConverter.parseUpdateData(\n 'WriteBatch.update',\n fieldOrUpdateData\n );\n }\n\n this._mutations = this._mutations.concat(\n parsed.toMutations(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n delete(documentRef: firestore.DocumentReference<unknown>): WriteBatch {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n const ref = validateReference(\n 'WriteBatch.delete',\n documentRef,\n this._firestore\n );\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.NONE)\n );\n return this;\n }\n\n async commit(): Promise<void> {\n this.verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._firestore.ensureClientConfigured().write(this._mutations);\n }\n }\n\n private verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nexport class DocumentReference<T = firestore.DocumentData>\n implements firestore.DocumentReference<T> {\n private _firestoreClient: FirestoreClient;\n\n constructor(\n public _key: DocumentKey,\n readonly firestore: Firestore,\n readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n\n static forPath<U>(\n path: ResourcePath,\n firestore: Firestore,\n converter?: firestore.FirestoreDataConverter<U>\n ): DocumentReference<U> {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n `${path.canonicalString()} has ${path.length}`\n );\n }\n return new DocumentReference(new DocumentKey(path), firestore, converter);\n }\n\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n get parent(): firestore.CollectionReference<T> {\n return new CollectionReference(\n this._key.path.popLast(),\n this.firestore,\n this._converter\n );\n }\n\n get path(): string {\n return this._key.path.canonicalString();\n }\n\n collection(\n pathString: string\n ): firestore.CollectionReference<firestore.DocumentData> {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType(\n 'DocumentReference.collection',\n 'non-empty string',\n 1,\n pathString\n );\n if (!pathString) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Must provide a non-empty collection name to collection()'\n );\n }\n const path = ResourcePath.fromString(pathString);\n return new CollectionReference(this._key.path.child(path), this.firestore);\n }\n\n isEqual(other: firestore.DocumentReference<T>): boolean {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n return (\n this.firestore === other.firestore &&\n this._key.isEqual(other._key) &&\n this._converter === other._converter\n );\n }\n\n set(\n value: firestore.DocumentData,\n options?: firestore.SetOptions\n ): Promise<void>;\n set(value: T, options?: firestore.SetOptions): Promise<void> {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n const [convertedValue, functionName] = applyFirestoreDataConverter(\n this._converter,\n value,\n 'DocumentReference.set'\n );\n const parsed =\n options.merge || options.mergeFields\n ? this.firestore._dataConverter.parseMergeData(\n functionName,\n convertedValue,\n options.mergeFields\n )\n : this.firestore._dataConverter.parseSetData(\n functionName,\n convertedValue\n );\n return this._firestoreClient.write(\n parsed.toMutations(this._key, Precondition.NONE)\n );\n }\n\n update(value: firestore.UpdateData): Promise<void>;\n update(\n field: string | ExternalFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void>;\n update(\n fieldOrUpdateData: string | ExternalFieldPath | firestore.UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void> {\n let parsed;\n\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof ExternalFieldPath\n ) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs(\n 'DocumentReference.update',\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData(\n 'DocumentReference.update',\n fieldOrUpdateData\n );\n }\n\n return this._firestoreClient.write(\n parsed.toMutations(this._key, Precondition.exists(true))\n );\n }\n\n delete(): Promise<void> {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([\n new DeleteMutation(this._key, Precondition.NONE)\n ]);\n }\n\n onSnapshot(\n observer: PartialObserver<firestore.DocumentSnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n observer: PartialObserver<firestore.DocumentSnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<firestore.DocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n onNext: NextFn<firestore.DocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n validateBetweenNumberOfArgs(\n 'DocumentReference.onSnapshot',\n arguments,\n 1,\n 4\n );\n let options: firestore.SnapshotListenOptions = {\n includeMetadataChanges: false\n };\n let observer: PartialObserver<firestore.DocumentSnapshot<T>>;\n let currArg = 0;\n if (\n typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])\n ) {\n options = args[currArg] as firestore.SnapshotListenOptions;\n validateOptionNames('DocumentReference.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType(\n 'DocumentReference.onSnapshot',\n 'boolean',\n 'includeMetadataChanges',\n options.includeMetadataChanges\n );\n currArg++;\n }\n\n const internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges\n };\n\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg] as PartialObserver<\n firestore.DocumentSnapshot<T>\n >;\n } else {\n validateArgType(\n 'DocumentReference.onSnapshot',\n 'function',\n currArg,\n args[currArg]\n );\n validateOptionalArgType(\n 'DocumentReference.onSnapshot',\n 'function',\n currArg + 1,\n args[currArg + 1]\n );\n validateOptionalArgType(\n 'DocumentReference.onSnapshot',\n 'function',\n currArg + 2,\n args[currArg + 2]\n );\n observer = {\n next: args[currArg] as NextFn<firestore.DocumentSnapshot<T>>,\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n }\n return this.onSnapshotInternal(internalOptions, observer);\n }\n\n private onSnapshotInternal(\n options: ListenOptions,\n observer: PartialObserver<firestore.DocumentSnapshot<T>>\n ): Unsubscribe {\n let errHandler = (err: Error): void => {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n\n const asyncObserver = new AsyncObserver<ViewSnapshot>({\n next: snapshot => {\n if (observer.next) {\n assert(\n snapshot.docs.size <= 1,\n 'Too many documents returned on a document query'\n );\n const doc = snapshot.docs.get(this._key);\n\n observer.next(\n new DocumentSnapshot(\n this.firestore,\n this._key,\n doc,\n snapshot.fromCache,\n snapshot.hasPendingWrites,\n this._converter\n )\n );\n }\n },\n error: errHandler\n });\n const internalListener = this._firestoreClient.listen(\n InternalQuery.atPath(this._key.path),\n asyncObserver,\n options\n );\n\n return () => {\n asyncObserver.mute();\n this._firestoreClient.unlisten(internalListener);\n };\n }\n\n get(options?: firestore.GetOptions): Promise<firestore.DocumentSnapshot<T>> {\n validateBetweenNumberOfArgs('DocumentReference.get', arguments, 0, 1);\n validateGetOptions('DocumentReference.get', options);\n return new Promise(\n (resolve: Resolver<firestore.DocumentSnapshot<T>>, reject: Rejecter) => {\n if (options && options.source === 'cache') {\n this.firestore\n .ensureClientConfigured()\n .getDocumentFromLocalCache(this._key)\n .then(doc => {\n resolve(\n new DocumentSnapshot(\n this.firestore,\n this._key,\n doc,\n /*fromCache=*/ true,\n doc instanceof Document ? doc.hasLocalMutations : false,\n this._converter\n )\n );\n }, reject);\n } else {\n this.getViaSnapshotListener(resolve, reject, options);\n }\n }\n );\n }\n\n private getViaSnapshotListener(\n resolve: Resolver<firestore.DocumentSnapshot<T>>,\n reject: Rejecter,\n options?: firestore.GetOptions\n ): void {\n const unlisten = this.onSnapshotInternal(\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n },\n {\n next: (snap: firestore.DocumentSnapshot<T>) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n\n if (!snap.exists && snap.metadata.fromCache) {\n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document because the client is ' + 'offline.'\n )\n );\n } else if (\n snap.exists &&\n snap.metadata.fromCache &&\n options &&\n options.source === 'server'\n ) {\n reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get document from server. (However, this ' +\n 'document does exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached document.)'\n )\n );\n } else {\n resolve(snap);\n }\n },\n error: reject\n }\n );\n }\n\n withConverter<U>(\n converter: firestore.FirestoreDataConverter<U>\n ): firestore.DocumentReference<U> {\n return new DocumentReference<U>(this._key, this.firestore, converter);\n }\n}\n\nclass SnapshotMetadata implements firestore.SnapshotMetadata {\n constructor(\n readonly hasPendingWrites: boolean,\n readonly fromCache: boolean\n ) {}\n\n isEqual(other: firestore.SnapshotMetadata): boolean {\n return (\n this.hasPendingWrites === other.hasPendingWrites &&\n this.fromCache === other.fromCache\n );\n }\n}\n\n/**\n * Options interface that can be provided to configure the deserialization of\n * DocumentSnapshots.\n */\nexport interface SnapshotOptions extends firestore.SnapshotOptions {}\n\nexport class DocumentSnapshot<T = firestore.DocumentData>\n implements firestore.DocumentSnapshot<T> {\n constructor(\n private _firestore: Firestore,\n private _key: DocumentKey,\n public _document: Document | null,\n private _fromCache: boolean,\n private _hasPendingWrites: boolean,\n private readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {}\n\n data(options?: firestore.SnapshotOptions): T | undefined {\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\n if (!this._document) {\n return undefined;\n } else {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n if (this._converter) {\n const snapshot = new QueryDocumentSnapshot(\n this._firestore,\n this._key,\n this._document,\n this._fromCache,\n this._hasPendingWrites\n );\n return this._converter.fromFirestore(snapshot, options);\n } else {\n return this.toJSObject(\n this._document.data(),\n FieldValueOptions.fromSnapshotOptions(\n options,\n this._firestore._areTimestampsInSnapshotsEnabled()\n )\n ) as T;\n }\n }\n }\n\n get(\n fieldPath: string | ExternalFieldPath,\n options?: firestore.SnapshotOptions\n ): unknown {\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\n if (this._document) {\n const value = this._document\n .data()\n .field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n if (value !== null) {\n return this.toJSValue(\n value,\n FieldValueOptions.fromSnapshotOptions(\n options,\n this._firestore._areTimestampsInSnapshotsEnabled()\n )\n );\n }\n }\n return undefined;\n }\n\n get id(): string {\n return this._key.path.lastSegment();\n }\n\n get ref(): firestore.DocumentReference<T> {\n return new DocumentReference<T>(\n this._key,\n this._firestore,\n this._converter\n );\n }\n\n get exists(): boolean {\n return this._document !== null;\n }\n\n get metadata(): firestore.SnapshotMetadata {\n return new SnapshotMetadata(this._hasPendingWrites, this._fromCache);\n }\n\n isEqual(other: firestore.DocumentSnapshot<T>): boolean {\n if (!(other instanceof DocumentSnapshot)) {\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\n }\n return (\n this._firestore === other._firestore &&\n this._fromCache === other._fromCache &&\n this._key.isEqual(other._key) &&\n (this._document === null\n ? other._document === null\n : this._document.isEqual(other._document)) &&\n this._converter === other._converter\n );\n }\n\n private toJSObject(\n data: ObjectValue,\n options: FieldValueOptions\n ): firestore.DocumentData {\n const result: firestore.DocumentData = {};\n data.forEach((key, value) => {\n result[key] = this.toJSValue(value, options);\n });\n return result;\n }\n\n private toJSValue(value: FieldValue, options: FieldValueOptions): unknown {\n if (value instanceof ObjectValue) {\n return this.toJSObject(value, options);\n } else if (value instanceof ArrayValue) {\n return this.toJSArray(value, options);\n } else if (value instanceof RefValue) {\n const key = value.value(options);\n const database = this._firestore.ensureClientConfigured().databaseId();\n if (!value.databaseId.isEqual(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n log.error(\n `Document ${this._key.path} contains a document ` +\n `reference within a different database (` +\n `${value.databaseId.projectId}/${value.databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${database.projectId}/${database.database}) ` +\n `instead.`\n );\n }\n return new DocumentReference(key, this._firestore, this._converter);\n } else {\n return value.value(options);\n }\n }\n\n private toJSArray(data: ArrayValue, options: FieldValueOptions): unknown[] {\n return data.internalValue.map(value => {\n return this.toJSValue(value, options);\n });\n }\n}\n\nexport class QueryDocumentSnapshot<T = firestore.DocumentData>\n extends DocumentSnapshot<T>\n implements firestore.QueryDocumentSnapshot<T> {\n data(options?: SnapshotOptions): T {\n const data = super.data(options);\n assert(\n data !== undefined,\n 'Document in a QueryDocumentSnapshot should exist'\n );\n return data;\n }\n}\n\nexport class Query<T = firestore.DocumentData> implements firestore.Query<T> {\n constructor(\n public _query: InternalQuery,\n readonly firestore: Firestore,\n protected readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {}\n\n where(\n field: string | ExternalFieldPath,\n opStr: firestore.WhereFilterOp,\n value: unknown\n ): firestore.Query<T> {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateDefined('Query.where', 3, value);\n\n // Enumerated from the WhereFilterOp type in index.d.ts.\n const whereFilterOpEnums = [\n '<',\n '<=',\n '==',\n '>=',\n '>',\n 'array-contains',\n 'in',\n 'array-contains-any'\n ];\n validateStringEnum('Query.where', whereFilterOpEnums, 2, opStr);\n\n let fieldValue: FieldValue;\n const fieldPath = fieldPathFromArgument('Query.where', field);\n const operator = Operator.fromString(opStr);\n if (fieldPath.isKeyField()) {\n if (\n operator === Operator.ARRAY_CONTAINS ||\n operator === Operator.ARRAY_CONTAINS_ANY\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. You can't perform '${operator.toString()}' ` +\n 'queries on FieldPath.documentId().'\n );\n } else if (operator === Operator.IN) {\n this.validateDisjunctiveFilterElements(value, operator);\n const referenceList: FieldValue[] = [];\n for (const arrayValue of value as FieldValue[]) {\n referenceList.push(this.parseDocumentIdValue(arrayValue));\n }\n fieldValue = new ArrayValue(referenceList);\n } else {\n fieldValue = this.parseDocumentIdValue(value);\n }\n } else {\n if (\n operator === Operator.IN ||\n operator === Operator.ARRAY_CONTAINS_ANY\n ) {\n this.validateDisjunctiveFilterElements(value, operator);\n }\n fieldValue = this.firestore._dataConverter.parseQueryValue(\n 'Query.where',\n value,\n // We only allow nested arrays for IN queries.\n /** allowArrays = */ operator === Operator.IN ? true : false\n );\n }\n const filter = FieldFilter.create(fieldPath, operator, fieldValue);\n this.validateNewFilter(filter);\n return new Query(\n this._query.addFilter(filter),\n this.firestore,\n this._converter\n );\n }\n\n orderBy(\n field: string | ExternalFieldPath,\n directionStr?: firestore.OrderByDirection\n ): firestore.Query<T> {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType(\n 'Query.orderBy',\n 'non-empty string',\n 2,\n directionStr\n );\n let direction: Direction;\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n } else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Function Query.orderBy() has unknown direction '${directionStr}', ` +\n `expected 'asc' or 'desc'.`\n );\n }\n if (this._query.startAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call Query.startAt() or ' +\n 'Query.startAfter() before calling Query.orderBy().'\n );\n }\n if (this._query.endAt !== null) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You must not call Query.endAt() or ' +\n 'Query.endBefore() before calling Query.orderBy().'\n );\n }\n const fieldPath = fieldPathFromArgument('Query.orderBy', field);\n const orderBy = new OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query(\n this._query.addOrderBy(orderBy),\n this.firestore,\n this._converter\n );\n }\n\n limit(n: number): firestore.Query<T> {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n validatePositiveNumber('Query.limit', 1, n);\n return new Query(\n this._query.withLimitToFirst(n),\n this.firestore,\n this._converter\n );\n }\n\n limitToLast(n: number): firestore.Query<T> {\n validateExactNumberOfArgs('Query.limitToLast', arguments, 1);\n validateArgType('Query.limitToLast', 'number', 1, n);\n validatePositiveNumber('Query.limitToLast', 1, n);\n return new Query(\n this._query.withLimitToLast(n),\n this.firestore,\n this._converter\n );\n }\n\n startAt(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.startAt',\n docOrField,\n fields,\n /*before=*/ true\n );\n return new Query(\n this._query.withStartAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n startAfter(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.startAfter',\n docOrField,\n fields,\n /*before=*/ false\n );\n return new Query(\n this._query.withStartAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n endBefore(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.endBefore',\n docOrField,\n fields,\n /*before=*/ true\n );\n return new Query(\n this._query.withEndAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n endAt(\n docOrField: unknown | firestore.DocumentSnapshot<unknown>,\n ...fields: unknown[]\n ): firestore.Query<T> {\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n const bound = this.boundFromDocOrFields(\n 'Query.endAt',\n docOrField,\n fields,\n /*before=*/ false\n );\n return new Query(\n this._query.withEndAt(bound),\n this.firestore,\n this._converter\n );\n }\n\n isEqual(other: firestore.Query<T>): boolean {\n if (!(other instanceof Query)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n return (\n this.firestore === other.firestore && this._query.isEqual(other._query)\n );\n }\n\n withConverter<U>(\n converter: firestore.FirestoreDataConverter<U>\n ): firestore.Query<U> {\n return new Query<U>(this._query, this.firestore, converter);\n }\n\n /** Helper function to create a bound from a document or fields */\n private boundFromDocOrFields(\n methodName: string,\n docOrField: unknown | firestore.DocumentSnapshot<T>,\n fields: unknown[],\n before: boolean\n ): Bound {\n validateDefined(methodName, 1, docOrField);\n if (docOrField instanceof DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}().`\n );\n }\n const snap = docOrField;\n if (!snap.exists) {\n throw new FirestoreError(\n Code.NOT_FOUND,\n `Can't use a DocumentSnapshot that doesn't exist for ` +\n `${methodName}().`\n );\n }\n return this.boundFromDocument(methodName, snap._document!, before);\n } else {\n const allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\n }\n\n /**\n * Create a Bound from a query and a document.\n *\n * Note that the Bound will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */\n private boundFromDocument(\n methodName: string,\n doc: Document,\n before: boolean\n ): Bound {\n const components: FieldValue[] = [];\n\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const orderBy of this._query.orderBy) {\n if (orderBy.field.isKeyField()) {\n components.push(new RefValue(this.firestore._databaseId, doc.key));\n } else {\n const value = doc.field(orderBy.field);\n if (value instanceof ServerTimestampValue) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You are trying to start or end a query using a ' +\n 'document for which the field \"' +\n orderBy.field +\n '\" is an uncommitted server timestamp. (Since the value of ' +\n 'this field is unknown, you cannot start/end a query with it.)'\n );\n } else if (value !== null) {\n components.push(value);\n } else {\n const field = orderBy.field.canonicalString();\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You are trying to start or end a query using a ` +\n `document for which the field '${field}' (used as the ` +\n `orderBy) does not exist.`\n );\n }\n }\n }\n return new Bound(components, before);\n }\n\n /**\n * Converts a list of field values to a Bound for the given query.\n */\n private boundFromFields(\n methodName: string,\n values: unknown[],\n before: boolean\n ): Bound {\n // Use explicit order by's because it has to match the query the user made\n const orderBy = this._query.explicitOrderBy;\n if (values.length > orderBy.length) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Too many arguments provided to ${methodName}(). ` +\n `The number of arguments must be less than or equal to the ` +\n `number of Query.orderBy() clauses`\n );\n }\n\n const components: FieldValue[] = [];\n for (let i = 0; i < values.length; i++) {\n const rawValue = values[i];\n const orderByComponent = orderBy[i];\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. Expected a string for document ID in ` +\n `${methodName}(), but got a ${typeof rawValue}`\n );\n }\n if (\n !this._query.isCollectionGroupQuery() &&\n rawValue.indexOf('/') !== -1\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection and ordering by FieldPath.documentId(), ` +\n `the value passed to ${methodName}() must be a plain document ID, but ` +\n `'${rawValue}' contains a slash.`\n );\n }\n const path = this._query.path.child(ResourcePath.fromString(rawValue));\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group and ordering by ` +\n `FieldPath.documentId(), the value passed to ${methodName}() must result in a ` +\n `valid document path, but '${path}' is not because it contains an odd number ` +\n `of segments.`\n );\n }\n const key = new DocumentKey(path);\n components.push(new RefValue(this.firestore._databaseId, key));\n } else {\n const wrapped = this.firestore._dataConverter.parseQueryValue(\n methodName,\n rawValue\n );\n components.push(wrapped);\n }\n }\n\n return new Bound(components, before);\n }\n\n onSnapshot(\n observer: PartialObserver<firestore.QuerySnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n observer: PartialObserver<firestore.QuerySnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<firestore.QuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: firestore.SnapshotListenOptions,\n onNext: NextFn<firestore.QuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n let options: firestore.SnapshotListenOptions = {};\n let observer: PartialObserver<firestore.QuerySnapshot<T>>;\n let currArg = 0;\n if (\n typeof args[currArg] === 'object' &&\n !isPartialObserver(args[currArg])\n ) {\n options = args[currArg] as firestore.SnapshotListenOptions;\n validateOptionNames('Query.onSnapshot', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType(\n 'Query.onSnapshot',\n 'boolean',\n 'includeMetadataChanges',\n options.includeMetadataChanges\n );\n currArg++;\n }\n\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg] as PartialObserver<firestore.QuerySnapshot<T>>;\n } else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType(\n 'Query.onSnapshot',\n 'function',\n currArg + 1,\n args[currArg + 1]\n );\n validateOptionalArgType(\n 'Query.onSnapshot',\n 'function',\n currArg + 2,\n args[currArg + 2]\n );\n observer = {\n next: args[currArg] as NextFn<firestore.QuerySnapshot<T>>,\n error: args[currArg + 1] as ErrorFn,\n complete: args[currArg + 2] as CompleteFn\n };\n }\n this.validateHasExplicitOrderByForLimitToLast(this._query);\n return this.onSnapshotInternal(options, observer);\n }\n\n private onSnapshotInternal(\n options: ListenOptions,\n observer: PartialObserver<firestore.QuerySnapshot<T>>\n ): Unsubscribe {\n let errHandler = (err: Error): void => {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n\n const asyncObserver = new AsyncObserver<ViewSnapshot>({\n next: (result: ViewSnapshot): void => {\n if (observer.next) {\n observer.next(\n new QuerySnapshot(\n this.firestore,\n this._query,\n result,\n this._converter\n )\n );\n }\n },\n error: errHandler\n });\n\n const firestoreClient = this.firestore.ensureClientConfigured();\n const internalListener = firestoreClient.listen(\n this._query,\n asyncObserver,\n options\n );\n return (): void => {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n }\n\n private validateHasExplicitOrderByForLimitToLast(query: InternalQuery): void {\n if (query.hasLimitToLast() && query.explicitOrderBy.length === 0) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'limitToLast() queries require specifying at least one orderBy() clause'\n );\n }\n }\n\n get(options?: firestore.GetOptions): Promise<firestore.QuerySnapshot<T>> {\n validateBetweenNumberOfArgs('Query.get', arguments, 0, 1);\n validateGetOptions('Query.get', options);\n this.validateHasExplicitOrderByForLimitToLast(this._query);\n return new Promise(\n (resolve: Resolver<firestore.QuerySnapshot<T>>, reject: Rejecter) => {\n if (options && options.source === 'cache') {\n this.firestore\n .ensureClientConfigured()\n .getDocumentsFromLocalCache(this._query)\n .then((viewSnap: ViewSnapshot) => {\n resolve(\n new QuerySnapshot(\n this.firestore,\n this._query,\n viewSnap,\n this._converter\n )\n );\n }, reject);\n } else {\n this.getViaSnapshotListener(resolve, reject, options);\n }\n }\n );\n }\n\n private getViaSnapshotListener(\n resolve: Resolver<firestore.QuerySnapshot<T>>,\n reject: Rejecter,\n options?: firestore.GetOptions\n ): void {\n const unlisten = this.onSnapshotInternal(\n {\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n },\n {\n next: (result: firestore.QuerySnapshot<T>) => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n\n if (\n result.metadata.fromCache &&\n options &&\n options.source === 'server'\n ) {\n reject(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'Failed to get documents from server. (However, these ' +\n 'documents may exist in the local cache. Run again ' +\n 'without setting source to \"server\" to ' +\n 'retrieve the cached documents.)'\n )\n );\n } else {\n resolve(result);\n }\n },\n error: reject\n }\n );\n }\n\n /**\n * Parses the given documentIdValue into a ReferenceValue, throwing\n * appropriate errors if the value is anything other than a DocumentReference\n * or String, or if the string is malformed.\n */\n private parseDocumentIdValue(documentIdValue: unknown): RefValue {\n if (typeof documentIdValue === 'string') {\n if (documentIdValue === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. When querying with FieldPath.documentId(), you ' +\n 'must provide a valid document ID, but it was an empty string.'\n );\n }\n if (\n !this._query.isCollectionGroupQuery() &&\n documentIdValue.indexOf('/') !== -1\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection by ` +\n `FieldPath.documentId(), you must provide a plain document ID, but ` +\n `'${documentIdValue}' contains a '/' character.`\n );\n }\n const path = this._query.path.child(\n ResourcePath.fromString(documentIdValue)\n );\n if (!DocumentKey.isDocumentKey(path)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying a collection group by ` +\n `FieldPath.documentId(), the value provided must result in a valid document path, ` +\n `but '${path}' is not because it has an odd number of segments (${path.length}).`\n );\n }\n return new RefValue(this.firestore._databaseId, new DocumentKey(path));\n } else if (documentIdValue instanceof DocumentReference) {\n const ref = documentIdValue as DocumentReference<T>;\n return new RefValue(this.firestore._databaseId, ref._key);\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. When querying with FieldPath.documentId(), you must provide a valid ` +\n `string or a DocumentReference, but it was: ` +\n `${valueDescription(documentIdValue)}.`\n );\n }\n }\n\n /**\n * Validates that the value passed into a disjunctrive filter satisfies all\n * array requirements.\n */\n private validateDisjunctiveFilterElements(\n value: unknown,\n operator: Operator\n ): void {\n if (!Array.isArray(value) || value.length === 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid Query. A non-empty array is required for ' +\n `'${operator.toString()}' filters.`\n );\n }\n if (value.length > 10) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. '${operator.toString()}' filters support a ` +\n 'maximum of 10 elements in the value array.'\n );\n }\n if (value.indexOf(null) >= 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. '${operator.toString()}' filters cannot contain 'null' ` +\n 'in the value array.'\n );\n }\n if (value.filter(element => Number.isNaN(element)).length > 0) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid Query. '${operator.toString()}' filters cannot contain 'NaN' ` +\n 'in the value array.'\n );\n }\n }\n\n private validateNewFilter(filter: Filter): void {\n if (filter instanceof FieldFilter) {\n const arrayOps = [Operator.ARRAY_CONTAINS, Operator.ARRAY_CONTAINS_ANY];\n const disjunctiveOps = [Operator.IN, Operator.ARRAY_CONTAINS_ANY];\n const isArrayOp = arrayOps.indexOf(filter.op) >= 0;\n const isDisjunctiveOp = disjunctiveOps.indexOf(filter.op) >= 0;\n\n if (filter.isInequality()) {\n const existingField = this._query.getInequalityFilterField();\n if (existingField !== null && !existingField.isEqual(filter.field)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. All where filters with an inequality' +\n ' (<, <=, >, or >=) must be on the same field. But you have' +\n ` inequality filters on '${existingField.toString()}'` +\n ` and '${filter.field.toString()}'`\n );\n }\n\n const firstOrderByField = this._query.getFirstOrderByField();\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(\n filter.field,\n firstOrderByField\n );\n }\n } else if (isDisjunctiveOp || isArrayOp) {\n // You can have at most 1 disjunctive filter and 1 array filter. Check if\n // the new filter conflicts with an existing one.\n let conflictingOp: Operator | null = null;\n if (isDisjunctiveOp) {\n conflictingOp = this._query.findFilterOperator(disjunctiveOps);\n }\n if (conflictingOp === null && isArrayOp) {\n conflictingOp = this._query.findFilterOperator(arrayOps);\n }\n if (conflictingOp != null) {\n // We special case when it's a duplicate op to give a slightly clearer error message.\n if (conflictingOp === filter.op) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid query. You cannot use more than one ' +\n `'${filter.op.toString()}' filter.`\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You cannot use '${filter.op.toString()}' filters ` +\n `with '${conflictingOp.toString()}' filters.`\n );\n }\n }\n }\n }\n }\n\n private validateNewOrderBy(orderBy: OrderBy): void {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n const inequalityField = this._query.getInequalityFilterField();\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n }\n\n private validateOrderByAndInequalityMatch(\n inequality: FieldPath,\n orderBy: FieldPath\n ): void {\n if (!orderBy.isEqual(inequality)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid query. You have a where filter with an inequality ` +\n `(<, <=, >, or >=) on field '${inequality.toString()}' ` +\n `and so you must also use '${inequality.toString()}' ` +\n `as your first Query.orderBy(), but your first Query.orderBy() ` +\n `is on field '${orderBy.toString()}' instead.`\n );\n }\n }\n}\n\nexport class QuerySnapshot<T = firestore.DocumentData>\n implements firestore.QuerySnapshot<T> {\n private _cachedChanges: Array<firestore.DocumentChange<T>> | null = null;\n private _cachedChangesIncludeMetadataChanges: boolean | null = null;\n\n readonly metadata: firestore.SnapshotMetadata;\n\n constructor(\n private readonly _firestore: Firestore,\n private readonly _originalQuery: InternalQuery,\n private readonly _snapshot: ViewSnapshot,\n private readonly _converter?: firestore.FirestoreDataConverter<T>\n ) {\n this.metadata = new SnapshotMetadata(\n _snapshot.hasPendingWrites,\n _snapshot.fromCache\n );\n }\n\n get docs(): Array<firestore.QueryDocumentSnapshot<T>> {\n const result: Array<firestore.QueryDocumentSnapshot<T>> = [];\n this.forEach(doc => result.push(doc));\n return result;\n }\n\n get empty(): boolean {\n return this._snapshot.docs.isEmpty();\n }\n\n get size(): number {\n return this._snapshot.docs.size;\n }\n\n forEach(\n callback: (result: firestore.QueryDocumentSnapshot<T>) => void,\n thisArg?: unknown\n ): void {\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n this._snapshot.docs.forEach(doc => {\n callback.call(thisArg, this.convertToDocumentImpl(doc));\n });\n }\n\n get query(): firestore.Query<T> {\n return new Query(this._originalQuery, this._firestore, this._converter);\n }\n\n docChanges(\n options?: firestore.SnapshotListenOptions\n ): Array<firestore.DocumentChange<T>> {\n if (options) {\n validateOptionNames('QuerySnapshot.docChanges', options, [\n 'includeMetadataChanges'\n ]);\n validateNamedOptionalType(\n 'QuerySnapshot.docChanges',\n 'boolean',\n 'includeMetadataChanges',\n options.includeMetadataChanges\n );\n }\n\n const includeMetadataChanges = !!(\n options && options.includeMetadataChanges\n );\n\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'To include metadata changes with your document changes, you must ' +\n 'also pass { includeMetadataChanges:true } to onSnapshot().'\n );\n }\n\n if (\n !this._cachedChanges ||\n this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges\n ) {\n this._cachedChanges = changesFromSnapshot<T>(\n this._firestore,\n includeMetadataChanges,\n this._snapshot,\n this._converter\n );\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n }\n\n /** Check the equality. The call can be very expensive. */\n isEqual(other: firestore.QuerySnapshot<T>): boolean {\n if (!(other instanceof QuerySnapshot)) {\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\n }\n\n return (\n this._firestore === other._firestore &&\n this._originalQuery.isEqual(other._originalQuery) &&\n this._snapshot.isEqual(other._snapshot) &&\n this._converter === other._converter\n );\n }\n\n private convertToDocumentImpl(doc: Document): QueryDocumentSnapshot<T> {\n return new QueryDocumentSnapshot(\n this._firestore,\n doc.key,\n doc,\n this.metadata.fromCache,\n this._snapshot.mutatedKeys.has(doc.key),\n this._converter\n );\n }\n}\n\n// TODO(2018/11/01): As of 2018/04/17 we're changing docChanges from an array\n// into a method. Because this is a runtime breaking change and somewhat subtle\n// (both Array and Function have a .length, etc.), we'll replace commonly-used\n// properties (including Symbol.iterator) to throw a custom error message. In\n// ~6 months we can delete the custom error as most folks will have hopefully\n// migrated.\nfunction throwDocChangesMethodError(): never {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'QuerySnapshot.docChanges has been changed from a property into a ' +\n 'method, so usages like \"querySnapshot.docChanges\" should become ' +\n '\"querySnapshot.docChanges()\"'\n );\n}\n\nconst docChangesPropertiesToOverride = [\n 'length',\n 'forEach',\n 'map',\n ...(typeof Symbol !== 'undefined' ? [Symbol.iterator] : [])\n];\ndocChangesPropertiesToOverride.forEach(property => {\n /**\n * We are (re-)defining properties on QuerySnapshot.prototype.docChanges which\n * is a Function. This could fail, in particular in the case of 'length' which\n * already exists on Function.prototype and on IE11 is improperly defined with\n * `{ configurable: false }`. So we wrap this in a try/catch to ensure that we\n * still have a functional SDK.\n */\n try {\n Object.defineProperty(QuerySnapshot.prototype.docChanges, property, {\n get: () => throwDocChangesMethodError()\n });\n } catch (err) {} // Ignore this failure intentionally\n});\n\nexport class CollectionReference<T = firestore.DocumentData> extends Query<T>\n implements firestore.CollectionReference<T> {\n constructor(\n readonly _path: ResourcePath,\n firestore: Firestore,\n _converter?: firestore.FirestoreDataConverter<T>\n ) {\n super(InternalQuery.atPath(_path), firestore, _converter);\n if (_path.length % 2 !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Invalid collection reference. Collection ' +\n 'references must have an odd number of segments, but ' +\n `${_path.canonicalString()} has ${_path.length}`\n );\n }\n }\n\n get id(): string {\n return this._query.path.lastSegment();\n }\n\n get parent(): firestore.DocumentReference<firestore.DocumentData> | null {\n const parentPath = this._query.path.popLast();\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference<firestore.DocumentData>(\n new DocumentKey(parentPath),\n this.firestore\n );\n }\n }\n\n get path(): string {\n return this._query.path.canonicalString();\n }\n\n doc(pathString?: string): firestore.DocumentReference<T> {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1);\n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n if (arguments.length === 0) {\n pathString = AutoId.newId();\n }\n validateArgType(\n 'CollectionReference.doc',\n 'non-empty string',\n 1,\n pathString\n );\n if (pathString === '') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Document path must be a non-empty string'\n );\n }\n const path = ResourcePath.fromString(pathString!);\n return DocumentReference.forPath<T>(\n this._query.path.child(path),\n this.firestore,\n this._converter\n );\n }\n\n add(value: T): Promise<firestore.DocumentReference<T>> {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n const convertedValue = this._converter\n ? this._converter.toFirestore(value)\n : value;\n validateArgType('CollectionReference.add', 'object', 1, convertedValue);\n const docRef = this.doc();\n return docRef.set(value).then(() => docRef);\n }\n\n withConverter<U>(\n converter: firestore.FirestoreDataConverter<U>\n ): firestore.CollectionReference<U> {\n return new CollectionReference<U>(this._path, this.firestore, converter);\n }\n}\n\nfunction validateSetOptions(\n methodName: string,\n options: firestore.SetOptions | undefined\n): firestore.SetOptions {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n\n validateOptionNames(methodName, options, ['merge', 'mergeFields']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n validateOptionalArrayElements(\n methodName,\n 'mergeFields',\n 'a string or a FieldPath',\n options.mergeFields,\n element =>\n typeof element === 'string' || element instanceof ExternalFieldPath\n );\n\n if (options.mergeFields !== undefined && options.merge !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Invalid options passed to function ${methodName}(): You cannot specify both \"merge\" ` +\n `and \"mergeFields\".`\n );\n }\n\n return options;\n}\n\nfunction validateSnapshotOptions(\n methodName: string,\n options: firestore.SnapshotOptions | undefined\n): firestore.SnapshotOptions {\n if (options === undefined) {\n return {};\n }\n\n validateOptionNames(methodName, options, ['serverTimestamps']);\n validateNamedOptionalPropertyEquals(\n methodName,\n 'options',\n 'serverTimestamps',\n options.serverTimestamps,\n ['estimate', 'previous', 'none']\n );\n return options;\n}\n\nfunction validateGetOptions(\n methodName: string,\n options: firestore.GetOptions | undefined\n): void {\n validateOptionalArgType(methodName, 'object', 1, options);\n if (options) {\n validateOptionNames(methodName, options, ['source']);\n validateNamedOptionalPropertyEquals(\n methodName,\n 'options',\n 'source',\n options.source,\n ['default', 'server', 'cache']\n );\n }\n}\n\nfunction validateReference<T>(\n methodName: string,\n documentRef: firestore.DocumentReference<T>,\n firestore: Firestore\n): DocumentReference<T> {\n if (!(documentRef instanceof DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n } else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef;\n }\n}\n\n/**\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\n *\n * Exported for testing.\n */\nexport function changesFromSnapshot<T>(\n firestore: Firestore,\n includeMetadataChanges: boolean,\n snapshot: ViewSnapshot,\n converter?: firestore.FirestoreDataConverter<T>\n): Array<firestore.DocumentChange<T>> {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n let lastDoc: Document;\n let index = 0;\n return snapshot.docChanges.map(change => {\n const doc = new QueryDocumentSnapshot<T>(\n firestore,\n change.doc.key,\n change.doc,\n snapshot.fromCache,\n snapshot.mutatedKeys.has(change.doc.key),\n converter\n );\n assert(\n change.type === ChangeType.Added,\n 'Invalid event type for first snapshot'\n );\n assert(\n !lastDoc || snapshot.query.docComparator(lastDoc, change.doc) < 0,\n 'Got added events in wrong order'\n );\n lastDoc = change.doc;\n return {\n type: 'added' as firestore.DocumentChangeType,\n doc,\n oldIndex: -1,\n newIndex: index++\n };\n });\n } else {\n // A DocumentSet that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let indexTracker = snapshot.oldDocs;\n return snapshot.docChanges\n .filter(\n change => includeMetadataChanges || change.type !== ChangeType.Metadata\n )\n .map(change => {\n const doc = new QueryDocumentSnapshot<T>(\n firestore,\n change.doc.key,\n change.doc,\n snapshot.fromCache,\n snapshot.mutatedKeys.has(change.doc.key),\n converter\n );\n let oldIndex = -1;\n let newIndex = -1;\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker = indexTracker.delete(change.doc.key);\n }\n if (change.type !== ChangeType.Removed) {\n indexTracker = indexTracker.add(change.doc);\n newIndex = indexTracker.indexOf(change.doc.key);\n }\n return { type: resultChangeType(change.type), doc, oldIndex, newIndex };\n });\n }\n}\n\nfunction resultChangeType(type: ChangeType): firestore.DocumentChangeType {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n case ChangeType.Removed:\n return 'removed';\n default:\n return fail('Unknown change type: ' + type);\n }\n}\n\n/**\n * Converts custom model object of type T into DocumentData by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to DocumentData\n * because we want to provide the user with a more specific error message if\n * their set() or fails due to invalid data originating from a toFirestore()\n * call.\n */\nfunction applyFirestoreDataConverter<T>(\n converter: firestore.FirestoreDataConverter<T> | undefined,\n value: T,\n functionName: string\n): [firestore.DocumentData, string] {\n let convertedValue;\n if (converter) {\n convertedValue = converter.toFirestore(value);\n functionName = 'toFirestore() in ' + functionName;\n } else {\n convertedValue = value as firestore.DocumentData;\n }\n return [convertedValue, functionName];\n}\n\n// Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\nexport const PublicFirestore = makeConstructorPrivate(\n Firestore,\n 'Use firebase.firestore() instead.'\n);\nexport const PublicTransaction = makeConstructorPrivate(\n Transaction,\n 'Use firebase.firestore().runTransaction() instead.'\n);\nexport const PublicWriteBatch = makeConstructorPrivate(\n WriteBatch,\n 'Use firebase.firestore().batch() instead.'\n);\nexport const PublicDocumentReference = makeConstructorPrivate(\n DocumentReference,\n 'Use firebase.firestore().doc() instead.'\n);\nexport const PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\nexport const PublicQueryDocumentSnapshot = makeConstructorPrivate(\n QueryDocumentSnapshot\n);\nexport const PublicQuery = makeConstructorPrivate(Query);\nexport const PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\nexport const PublicCollectionReference = makeConstructorPrivate(\n CollectionReference,\n 'Use firebase.firestore().collection() instead.'\n);\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { getUA } from '@firebase/util';\nimport { assert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { debug, error } from '../util/log';\nimport { Deferred } from '../util/promise';\nimport { SCHEMA_VERSION } from './indexeddb_schema';\nimport { PersistencePromise } from './persistence_promise';\n\nconst LOG_TAG = 'SimpleDb';\n\n/**\n * The maximum number of retry attempts for an IndexedDb transaction that fails\n * with a DOMException.\n */\nconst TRANSACTION_RETRY_COUNT = 3;\n\n// The different modes supported by `SimpleDb.runTransaction()`\ntype SimpleDbTransactionMode = 'readonly' | 'readwrite';\n\nexport interface SimpleDbSchemaConverter {\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void>;\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */\nexport class SimpleDb {\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support downgrading the schema\n * version. We currently do not support any way to do versioning outside of IndexedDB's versioning\n * mechanism, as only version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n static openOrCreate(\n name: string,\n version: number,\n schemaConverter: SimpleDbSchemaConverter\n ): Promise<SimpleDb> {\n assert(\n SimpleDb.isAvailable(),\n 'IndexedDB not supported in current environment.'\n );\n debug(LOG_TAG, 'Opening database:', name);\n return new PersistencePromise<SimpleDb>((resolve, reject) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const request = window.indexedDB.open(name, version);\n\n request.onsuccess = (event: Event) => {\n const db = (event.target as IDBOpenDBRequest).result;\n resolve(new SimpleDb(db));\n };\n\n request.onblocked = () => {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'Cannot upgrade IndexedDB schema while another tab is open. ' +\n 'Close all tabs that access Firestore and reload this page to proceed.'\n )\n );\n };\n\n request.onerror = (event: Event) => {\n const error: DOMException = (event.target as IDBOpenDBRequest).error!;\n if (error.name === 'VersionError') {\n reject(\n new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A newer version of the Firestore SDK was previously used and so the persisted ' +\n 'data is not compatible with the version of the SDK you are now using. The SDK ' +\n 'will operate with persistence disabled. If you need persistence, please ' +\n 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' +\n 'data for your app to start fresh.'\n )\n );\n } else {\n reject(error);\n }\n };\n\n request.onupgradeneeded = (event: IDBVersionChangeEvent) => {\n debug(\n LOG_TAG,\n 'Database \"' + name + '\" requires upgrade from version:',\n event.oldVersion\n );\n const db = (event.target as IDBOpenDBRequest).result;\n schemaConverter\n .createOrUpgrade(\n db,\n request.transaction!,\n event.oldVersion,\n SCHEMA_VERSION\n )\n .next(() => {\n debug(\n LOG_TAG,\n 'Database upgrade to version ' + SCHEMA_VERSION + ' complete'\n );\n });\n };\n }).toPromise();\n }\n\n /** Deletes the specified database. */\n static delete(name: string): Promise<void> {\n debug(LOG_TAG, 'Removing database:', name);\n return wrapRequest<void>(window.indexedDB.deleteDatabase(name)).toPromise();\n }\n\n /** Returns true if IndexedDB is available in the current environment. */\n static isAvailable(): boolean {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\n }\n\n if (SimpleDb.isMockPersistence()) {\n return true;\n }\n\n // In some Node environments, `window` is defined, but `window.navigator` is\n // not. We don't support IndexedDB persistence in Node if the\n // isMockPersistence() check above returns false.\n if (window.navigator === undefined) {\n return false;\n }\n\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n\n // Check the UA string to find out the browser.\n const ua = getUA();\n\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n\n // iOS Safari: Disable for users running iOS version < 10.\n const iOSVersion = SimpleDb.getIOSVersion(ua);\n const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10;\n\n // Android browser: Disable for userse running version < 4.5.\n const androidVersion = SimpleDb.getAndroidVersion(ua);\n const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5;\n\n if (\n ua.indexOf('MSIE ') > 0 ||\n ua.indexOf('Trident/') > 0 ||\n ua.indexOf('Edge/') > 0 ||\n isUnsupportedIOS ||\n isUnsupportedAndroid\n ) {\n return false;\n } else {\n return true;\n }\n }\n\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */\n static isMockPersistence(): boolean {\n return (\n typeof process !== 'undefined' &&\n process.env?.USE_MOCK_PERSISTENCE === 'YES'\n );\n }\n\n /** Helper to get a typed SimpleDbStore from a transaction. */\n static getStore<KeyType extends IDBValidKey, ValueType extends unknown>(\n txn: SimpleDbTransaction,\n store: string\n ): SimpleDbStore<KeyType, ValueType> {\n return txn.store<KeyType, ValueType>(store);\n }\n\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static getIOSVersion(ua: string): number {\n const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\\d_]+)/i);\n const version = iOSVersionRegex\n ? iOSVersionRegex[1]\n .split('_')\n .slice(0, 2)\n .join('.')\n : '-1';\n return Number(version);\n }\n\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static getAndroidVersion(ua: string): number {\n const androidVersionRegex = ua.match(/Android ([\\d.]+)/i);\n const version = androidVersionRegex\n ? androidVersionRegex[1]\n .split('.')\n .slice(0, 2)\n .join('.')\n : '-1';\n return Number(version);\n }\n\n constructor(private db: IDBDatabase) {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n if (iOSVersion === 12.2) {\n error(\n 'Firestore persistence suffers from a bug in iOS 12.2 ' +\n 'Safari that may cause your app to stop working. See ' +\n 'https://stackoverflow.com/q/56496296/110915 for details ' +\n 'and a potential workaround.'\n );\n }\n }\n\n setVersionChangeListener(\n versionChangeListener: (event: IDBVersionChangeEvent) => void\n ): void {\n this.db.onversionchange = (event: IDBVersionChangeEvent) => {\n return versionChangeListener(event);\n };\n }\n\n async runTransaction<T>(\n mode: SimpleDbTransactionMode,\n objectStores: string[],\n transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise<T>\n ): Promise<T> {\n const readonly = mode === 'readonly';\n let attemptNumber = 0;\n\n while (true) {\n ++attemptNumber;\n\n const transaction = SimpleDbTransaction.open(\n this.db,\n readonly ? 'readonly' : 'readwrite',\n objectStores\n );\n try {\n const transactionFnResult = transactionFn(transaction)\n .catch(error => {\n // Abort the transaction if there was an error.\n transaction.abort(error);\n // We cannot actually recover, and calling `abort()` will cause the transaction's\n // completion promise to be rejected. This in turn means that we won't use\n // `transactionFnResult` below. We return a rejection here so that we don't add the\n // possibility of returning `void` to the type of `transactionFnResult`.\n return PersistencePromise.reject<T>(error);\n })\n .toPromise();\n\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n transactionFnResult.catch(() => {});\n\n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await transaction.completionPromise;\n return transactionFnResult;\n } catch (error) {\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n const retryable =\n error.name !== 'FirebaseError' &&\n attemptNumber < TRANSACTION_RETRY_COUNT;\n debug(\n LOG_TAG,\n 'Transaction failed with error: %s. Retrying: %s.',\n error.message,\n retryable\n );\n\n if (!retryable) {\n return Promise.reject(error);\n }\n }\n }\n }\n\n close(): void {\n this.db.close();\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */\nexport class IterationController {\n private shouldStop = false;\n private nextKey: IDBValidKey | null = null;\n\n constructor(private dbCursor: IDBCursorWithValue) {}\n\n get isDone(): boolean {\n return this.shouldStop;\n }\n\n get skipToKey(): IDBValidKey | null {\n return this.nextKey;\n }\n\n set cursor(value: IDBCursorWithValue) {\n this.dbCursor = value;\n }\n\n /**\n * This function can be called to stop iteration at any point.\n */\n done(): void {\n this.shouldStop = true;\n }\n\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */\n skip(key: IDBValidKey): void {\n this.nextKey = key;\n }\n\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */\n delete(): PersistencePromise<void> {\n return wrapRequest<void>(this.dbCursor.delete());\n }\n}\n\n/**\n * Callback used with iterate() method.\n */\nexport type IterateCallback<KeyType, ValueType> = (\n key: KeyType,\n value: ValueType,\n control: IterationController\n) => void | PersistencePromise<void>;\n\n/** Options available to the iterate() method. */\nexport interface IterateOptions {\n /** Index to iterate over (else primary keys will be iterated) */\n index?: string;\n\n /** IndxedDB Range to iterate over (else entire store will be iterated) */\n range?: IDBKeyRange;\n\n /** If true, values aren't read while iterating. */\n keysOnly?: boolean;\n\n /** If true, iterate over the store in reverse. */\n reverse?: boolean;\n}\n\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nexport class SimpleDbTransaction {\n private aborted = false;\n\n /**\n * A promise that resolves with the result of the IndexedDb transaction.\n */\n private readonly completionDeferred = new Deferred<void>();\n\n static open(\n db: IDBDatabase,\n mode: IDBTransactionMode,\n objectStoreNames: string[]\n ): SimpleDbTransaction {\n return new SimpleDbTransaction(db.transaction(objectStoreNames, mode));\n }\n\n constructor(private readonly transaction: IDBTransaction) {\n this.transaction.oncomplete = () => {\n this.completionDeferred.resolve();\n };\n this.transaction.onabort = () => {\n if (transaction.error) {\n this.completionDeferred.reject(transaction.error);\n } else {\n this.completionDeferred.resolve();\n }\n };\n this.transaction.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n this.completionDeferred.reject(error);\n };\n }\n\n get completionPromise(): Promise<void> {\n return this.completionDeferred.promise;\n }\n\n abort(error?: Error): void {\n if (error) {\n this.completionDeferred.reject(error);\n }\n\n if (!this.aborted) {\n debug(\n LOG_TAG,\n 'Aborting transaction:',\n error ? error.message : 'Client-initiated abort'\n );\n this.aborted = true;\n this.transaction.abort();\n }\n }\n\n /**\n * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */\n store<KeyType extends IDBValidKey, ValueType extends unknown>(\n storeName: string\n ): SimpleDbStore<KeyType, ValueType> {\n const store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore<KeyType, ValueType>(store);\n }\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */\nexport class SimpleDbStore<\n KeyType extends IDBValidKey,\n ValueType extends unknown\n> {\n constructor(private store: IDBObjectStore) {}\n\n /**\n * Writes a value into the Object Store.\n *\n * @param key Optional explicit key to use when writing the object, else the\n * key will be auto-assigned (e.g. via the defined keyPath for the store).\n * @param value The object to write.\n */\n put(value: ValueType): PersistencePromise<void>;\n put(key: KeyType, value: ValueType): PersistencePromise<void>;\n put(\n keyOrValue: KeyType | ValueType,\n value?: ValueType\n ): PersistencePromise<void> {\n let request;\n if (value !== undefined) {\n debug(LOG_TAG, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue as KeyType);\n } else {\n debug(LOG_TAG, 'PUT', this.store.name, '<auto-key>', keyOrValue);\n request = this.store.put(keyOrValue as ValueType);\n }\n return wrapRequest<void>(request);\n }\n\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value The object to write.\n * @return The key of the value to add.\n */\n add(value: ValueType): PersistencePromise<KeyType> {\n debug(LOG_TAG, 'ADD', this.store.name, value, value);\n const request = this.store.add(value as ValueType);\n return wrapRequest<KeyType>(request);\n }\n\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @return The object with the specified key or null if no object exists.\n */\n get(key: KeyType): PersistencePromise<ValueType | null> {\n const request = this.store.get(key);\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return wrapRequest<any>(request).next(result => {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n debug(LOG_TAG, 'GET', this.store.name, key, result);\n return result;\n });\n }\n\n delete(key: KeyType | IDBKeyRange): PersistencePromise<void> {\n debug(LOG_TAG, 'DELETE', this.store.name, key);\n const request = this.store.delete(key);\n return wrapRequest<void>(request);\n }\n\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */\n count(): PersistencePromise<number> {\n debug(LOG_TAG, 'COUNT', this.store.name);\n const request = this.store.count();\n return wrapRequest<number>(request);\n }\n\n loadAll(): PersistencePromise<ValueType[]>;\n loadAll(range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(index: string, range: IDBKeyRange): PersistencePromise<ValueType[]>;\n loadAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<ValueType[]> {\n const cursor = this.cursor(this.options(indexOrRange, range));\n const results: ValueType[] = [];\n return this.iterateCursor(cursor, (key, value) => {\n results.push(value);\n }).next(() => {\n return results;\n });\n }\n\n deleteAll(): PersistencePromise<void>;\n deleteAll(range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(index: string, range: IDBKeyRange): PersistencePromise<void>;\n deleteAll(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): PersistencePromise<void> {\n debug(LOG_TAG, 'DELETE ALL', this.store.name);\n const options = this.options(indexOrRange, range);\n options.keysOnly = false;\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, (key, value, control) => {\n // NOTE: Calling delete() on a cursor is documented as more efficient than\n // calling delete() on an object store with a single key\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete),\n // however, this requires us *not* to use a keysOnly cursor\n // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We\n // may want to compare the performance of each method.\n return control.delete();\n });\n }\n\n /**\n * Iterates over keys and values in an object store.\n *\n * @param options Options specifying how to iterate the objects in the store.\n * @param callback will be called for each iterated object. Iteration can be\n * canceled at any point by calling the doneFn passed to the callback.\n * The callback can return a PersistencePromise if it performs async\n * operations but note that iteration will continue without waiting for them\n * to complete.\n * @returns A PersistencePromise that resolves once all PersistencePromises\n * returned by callbacks resolve.\n */\n iterate(\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n options: IterateOptions,\n callback: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void>;\n iterate(\n optionsOrCallback: IterateOptions | IterateCallback<KeyType, ValueType>,\n callback?: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n let options;\n if (!callback) {\n options = {};\n callback = optionsOrCallback as IterateCallback<KeyType, ValueType>;\n } else {\n options = optionsOrCallback as IterateOptions;\n }\n const cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n }\n\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */\n iterateSerial(\n callback: (k: KeyType, v: ValueType) => PersistencePromise<boolean>\n ): PersistencePromise<void> {\n const cursorRequest = this.cursor({});\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey as KeyType, cursor.value).next(\n shouldContinue => {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n }\n );\n };\n });\n }\n\n private iterateCursor(\n cursorRequest: IDBRequest,\n fn: IterateCallback<KeyType, ValueType>\n ): PersistencePromise<void> {\n const results: Array<PersistencePromise<void>> = [];\n return new PersistencePromise((resolve, reject) => {\n cursorRequest.onerror = (event: Event) => {\n reject((event.target as IDBRequest).error!);\n };\n cursorRequest.onsuccess = (event: Event) => {\n const cursor: IDBCursorWithValue = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve();\n return;\n }\n const controller = new IterationController(cursor);\n const userResult = fn(\n cursor.primaryKey as KeyType,\n cursor.value,\n controller\n );\n if (userResult instanceof PersistencePromise) {\n const userPromise: PersistencePromise<void> = userResult.catch(\n err => {\n controller.done();\n return PersistencePromise.reject(err);\n }\n );\n results.push(userPromise);\n }\n if (controller.isDone) {\n resolve();\n } else if (controller.skipToKey === null) {\n cursor.continue();\n } else {\n cursor.continue(controller.skipToKey);\n }\n };\n }).next(() => {\n return PersistencePromise.waitFor(results);\n });\n }\n\n private options(\n indexOrRange?: string | IDBKeyRange,\n range?: IDBKeyRange\n ): IterateOptions {\n let indexName: string | undefined = undefined;\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n assert(\n range === undefined,\n '3rd argument must not be defined if 2nd is a range.'\n );\n range = indexOrRange;\n }\n }\n return { index: indexName, range };\n }\n\n private cursor(options: IterateOptions): IDBRequest {\n let direction: IDBCursorDirection = 'next';\n if (options.reverse) {\n direction = 'prev';\n }\n if (options.index) {\n const index = this.store.index(options.index);\n if (options.keysOnly) {\n return index.openKeyCursor(options.range, direction);\n } else {\n return index.openCursor(options.range, direction);\n }\n } else {\n return this.store.openCursor(options.range, direction);\n }\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */\nfunction wrapRequest<R>(request: IDBRequest): PersistencePromise<R> {\n return new PersistencePromise<R>((resolve, reject) => {\n request.onsuccess = (event: Event) => {\n const result = (event.target as IDBRequest).result;\n resolve(result);\n };\n\n request.onerror = (event: Event) => {\n const error = checkForAndReportiOSError(\n (event.target as IDBRequest).error!\n );\n reject(error);\n };\n });\n}\n\n// Guard so we only report the error once.\nlet reportedIOSError = false;\nfunction checkForAndReportiOSError(error: DOMException): Error {\n const iOSVersion = SimpleDb.getIOSVersion(getUA());\n if (iOSVersion >= 12.2 && iOSVersion < 13) {\n const IOS_ERROR =\n 'An internal error was encountered in the Indexed Database server';\n if (error.message.indexOf(IOS_ERROR) >= 0) {\n // Wrap error in a more descriptive one.\n const newError = new FirestoreError(\n 'internal',\n `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` +\n `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` +\n `for details and a potential workaround.`\n );\n if (!reportedIOSError) {\n reportedIOSError = true;\n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout(() => {\n throw newError;\n }, 0);\n }\n return newError;\n }\n }\n return error;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { User } from '../auth/user';\nimport { Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { BATCHID_UNKNOWN, MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { assert, fail } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ByteString } from '../util/byte_string';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport {\n IndexedDbPersistence,\n IndexedDbTransaction\n} from './indexeddb_persistence';\nimport {\n DbDocumentMutation,\n DbDocumentMutationKey,\n DbMutationBatch,\n DbMutationBatchKey,\n DbMutationQueue,\n DbMutationQueueKey\n} from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { PersistenceTransaction, ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user The user for which to create a mutation queue.\n * @param serializer The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n assert(user.uid !== '', 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise<boolean> {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatch.userMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n acknowledgeBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch,\n streamToken: ByteString\n ): PersistencePromise<void> {\n return this.getMutationQueueMetadata(transaction).next(metadata => {\n // We can't store the resumeToken as a ByteString in IndexedDB, so we\n // convert it to a Base64 string for storage.\n metadata.lastStreamToken = streamToken.toBase64();\n\n return mutationQueuesStore(transaction).put(metadata);\n });\n }\n\n getLastStreamToken(\n transaction: PersistenceTransaction\n ): PersistencePromise<ByteString> {\n return this.getMutationQueueMetadata(transaction).next<ByteString>(\n metadata => ByteString.fromBase64String(metadata.lastStreamToken)\n );\n }\n\n setLastStreamToken(\n transaction: PersistenceTransaction,\n streamToken: ByteString\n ): PersistencePromise<void> {\n return this.getMutationQueueMetadata(transaction).next(metadata => {\n // We can't store the resumeToken as a ByteString in IndexedDB, so we\n // convert it to a Base64 string for storage.\n metadata.lastStreamToken = streamToken.toBase64();\n return mutationQueuesStore(transaction).put(metadata);\n });\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise<MutationBatch> {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n assert(typeof batchId === 'number', 'Auto-generated key is not a number');\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = this.serializer.toDbMutationBatch(this.userId, batch);\n\n const promises: Array<PersistencePromise<void>> = [];\n let collectionParents = new SortedSet<ResourcePath>((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = DbDocumentMutation.key(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutation.PLACEHOLDER)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n assert(\n dbBatch.userId === this.userId,\n `Unexpected user '${dbBatch.userId}' for mutation batch ${batchId}`\n );\n return this.serializer.fromDbMutationBatch(dbBatch);\n }\n return null;\n });\n }\n\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<DocumentKeySet | null> {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve<DocumentKeySet | null>(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise<MutationBatch | null> {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatch.userMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n assert(\n dbBatch.batchId >= nextBatchId,\n 'Should have found mutation after ' + nextBatchId\n );\n foundBatch = this.serializer.fromDbMutationBatch(dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise<BatchId> {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatch.userMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise<MutationBatch[]> {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatch.userMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => this.serializer.fromDbMutationBatch(dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MutationBatch[]> {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = DbDocumentMutation.prefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = EncodedResourcePath.decode(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 'Dangling document-mutation reference found: ' +\n indexKey +\n ' which points to ' +\n batchId\n );\n }\n assert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(this.serializer.fromDbMutationBatch(mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap<DocumentKey, unknown>\n ): PersistencePromise<MutationBatch[]> {\n let uniqueBatchIDs = new SortedSet<BatchId>(primitiveComparator);\n\n const promises: Array<PersistencePromise<void>> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = DbDocumentMutation.prefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = EncodedResourcePath.decode(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise<MutationBatch[]> {\n assert(\n !query.isDocumentQuery(),\n \"Document queries shouldn't go down this path\"\n );\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = DbDocumentMutation.prefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet<BatchId>(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = EncodedResourcePath.decode(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet<BatchId>\n ): PersistencePromise<MutationBatch[]> {\n const results: MutationBatch[] = [];\n const promises: Array<PersistencePromise<void>> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 'Dangling document-mutation reference found, ' +\n 'which points to ' +\n batchId\n );\n }\n assert(\n mutation.userId === this.userId,\n `Unexpected user '${mutation.userId}' for mutation batch ${batchId}`\n );\n results.push(this.serializer.fromDbMutationBatch(mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise<void> {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.removeMutationReference(\n transaction,\n key\n );\n }\n );\n });\n }\n\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise<void> {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n DbDocumentMutation.prefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = EncodedResourcePath.decode(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n assert(\n danglingMutationReferences.length === 0,\n 'Document leak -- detected dangling mutation references when queue is empty. ' +\n 'Dangling keys: ' +\n danglingMutationReferences.map(p => p.canonicalString())\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise<DbMutationQueue> {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata ||\n new DbMutationQueue(\n this.userId,\n BATCHID_UNKNOWN,\n /*lastStreamToken=*/ ''\n )\n );\n });\n }\n}\n\n/**\n * @return true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise<boolean> {\n const indexKey = DbDocumentMutation.prefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise<boolean> {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @return A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: MutationBatch\n): PersistencePromise<DocumentKey[]> {\n const mutationStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatch.store\n );\n const indexTxn = txn.store<DbDocumentMutationKey, DbDocumentMutation>(\n DbDocumentMutation.store\n );\n const promises: Array<PersistencePromise<void>> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n assert(\n numDeleted === 1,\n 'Dangling document-mutation reference found: Missing batch ' +\n batch.batchId\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = DbDocumentMutation.key(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbMutationBatchKey, DbMutationBatch> {\n return IndexedDbPersistence.getStore<DbMutationBatchKey, DbMutationBatch>(\n txn,\n DbMutationBatch.store\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbDocumentMutationKey, DbDocumentMutation> {\n return IndexedDbPersistence.getStore<\n DbDocumentMutationKey,\n DbDocumentMutation\n >(txn, DbDocumentMutation.store);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbMutationQueueKey, DbMutationQueue> {\n return IndexedDbPersistence.getStore<DbMutationQueueKey, DbMutationQueue>(\n txn,\n DbMutationQueue.store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { assert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport * as EncodedResourcePath from './encoded_resource_path';\nimport {\n IndexedDbLruDelegate,\n IndexedDbPersistence,\n IndexedDbTransaction\n} from './indexeddb_persistence';\nimport {\n DbTarget,\n DbTargetDocument,\n DbTargetDocumentKey,\n DbTargetGlobal,\n DbTargetGlobalKey,\n DbTargetKey\n} from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\nimport { Target } from '../core/target';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n private targetIdGenerator = TargetIdGenerator.forTargetCache();\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise<TargetId> {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestTargetId = this.targetIdGenerator.after(\n metadata.highestTargetId\n );\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise<ListenSequenceNumber> {\n return getHighestListenSequenceNumber(\n (transaction as IndexedDbTransaction).simpleDbTransaction\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise<void> {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n assert(metadata.targetCount > 0, 'Removing from an empty target cache');\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n let count = 0;\n const promises: Array<PersistencePromise<void>> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = this.serializer.fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = this.serializer.fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise<DbTargetGlobal> {\n return retrieveMetadata(\n (transaction as IndexedDbTransaction).simpleDbTransaction\n );\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise<void> {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n return targetsStore(transaction).put(\n this.serializer.toDbTarget(targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise<number> {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise<TargetData | null> {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = target.canonicalId();\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTarget.queryTargetsIndexName },\n (key, value, control) => {\n const found = this.serializer.fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (target.isEqual(found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array<PersistencePromise<void>> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = EncodedResourcePath.encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n promises.push(this.referenceDelegate.addReference(txn, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise<void> {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = EncodedResourcePath.encode(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<void> {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<DocumentKeySet> {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = EncodedResourcePath.decode(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<boolean> {\n const path = EncodedResourcePath.encode(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise<TargetData | null> {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return this.serializer.fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbTargetKey, DbTarget> {\n return IndexedDbPersistence.getStore<DbTargetKey, DbTarget>(\n txn,\n DbTarget.store\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbTargetGlobalKey, DbTargetGlobal> {\n return IndexedDbPersistence.getStore<DbTargetGlobalKey, DbTargetGlobal>(\n txn,\n DbTargetGlobal.store\n );\n}\n\nfunction retrieveMetadata(\n txn: SimpleDbTransaction\n): PersistencePromise<DbTargetGlobal> {\n const globalStore = SimpleDb.getStore<DbTargetGlobalKey, DbTargetGlobal>(\n txn,\n DbTargetGlobal.store\n );\n return globalStore.get(DbTargetGlobal.key).next(metadata => {\n assert(metadata !== null, 'Missing metadata row.');\n return metadata;\n });\n}\n\nexport function getHighestListenSequenceNumber(\n txn: SimpleDbTransaction\n): PersistencePromise<ListenSequenceNumber> {\n return retrieveMetadata(txn).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbTargetDocumentKey, DbTargetDocument> {\n return IndexedDbPersistence.getStore<DbTargetDocumentKey, DbTargetDocument>(\n txn,\n DbTargetDocument.store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../core/query';\nimport {\n DocumentKeySet,\n DocumentMap,\n documentMap,\n DocumentSizeEntries,\n DocumentSizeEntry,\n MaybeDocumentMap,\n maybeDocumentMap,\n nullableMaybeDocumentMap,\n NullableMaybeDocumentMap\n} from '../model/collections';\nimport { Document, MaybeDocument, NoDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { assert, fail } from '../util/assert';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport {\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentKey\n} from './indexeddb_schema';\nimport { LocalSerializer } from './local_serializer';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { IterateOptions, SimpleDbStore } from './simple_db';\nimport { ObjectMap } from '../util/obj_map';\n\nexport class IndexedDbRemoteDocumentCache implements RemoteDocumentCache {\n /**\n * @param {LocalSerializer} serializer The document serializer.\n * @param {IndexManager} indexManager The query indexes that need to be maintained.\n */\n constructor(\n readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager\n ) {}\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n private addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise<void> {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(dbKey(key), doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n private removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<void> {\n const store = remoteDocumentsStore(transaction);\n const key = dbKey(documentKey);\n return store.delete(key);\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n private updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise<void> {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(dbRemoteDoc => {\n return this.maybeDecodeDocument(dbRemoteDoc);\n });\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey The key of the entry to look up.\n * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<DocumentSizeEntry | null> {\n return remoteDocumentsStore(transaction)\n .get(dbKey(documentKey))\n .next(dbRemoteDoc => {\n const doc = this.maybeDecodeDocument(dbRemoteDoc);\n return doc\n ? {\n maybeDocument: doc,\n size: dbDocumentSize(dbRemoteDoc!)\n }\n : null;\n });\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n let results = nullableMaybeDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys The set of keys entries to look up.\n * @return A map of MaybeDocuments indexed by key (if a document cannot be\n * found, the key will be mapped to null) and a map of sizes indexed by\n * key (zero if the key cannot be found).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<DocumentSizeEntries> {\n let results = nullableMaybeDocumentMap();\n let sizeMap = new SortedMap<DocumentKey, number>(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(dbRemoteDoc);\n if (doc) {\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc!));\n } else {\n results = results.insert(key, null);\n sizeMap = sizeMap.insert(key, 0);\n }\n }\n ).next(() => {\n return { maybeDocuments: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise<void> {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n const range = IDBKeyRange.bound(\n documentKeys.first()!.path.toArray(),\n documentKeys.last()!.path.toArray()\n );\n const keyIter = documentKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate({ range }, (potentialKeyRaw, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments(potentialKeyRaw);\n\n // Go through keys not found in cache.\n while (nextKey && DocumentKey.comparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(nextKey!.path.toArray());\n } else {\n control.done();\n }\n })\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<DocumentMap> {\n assert(\n !query.isCollectionGroupQuery(),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n let results = documentMap();\n\n const immediateChildrenPathLength = query.path.length + 1;\n\n const iterationOptions: IterateOptions = {};\n if (sinceReadTime.isEqual(SnapshotVersion.MIN)) {\n // Documents are ordered by key, so we can use a prefix scan to narrow\n // down the documents we need to match the query against.\n const startKey = query.path.toArray();\n iterationOptions.range = IDBKeyRange.lowerBound(startKey);\n } else {\n // Execute an index-free query and filter by read time. This is safe\n // since all document changes to queries that have a\n // lastLimboFreeSnapshotVersion (`sinceReadTime`) have a read time set.\n const collectionKey = query.path.toArray();\n const readTimeKey = this.serializer.toDbTimestampKey(sinceReadTime);\n iterationOptions.range = IDBKeyRange.lowerBound(\n [collectionKey, readTimeKey],\n /* open= */ true\n );\n iterationOptions.index = DbRemoteDocument.collectionReadTimeIndex;\n }\n\n return remoteDocumentsStore(transaction)\n .iterate(iterationOptions, (key, dbRemoteDoc, control) => {\n // The query is actually returning any path that starts with the query\n // path prefix which may include documents in subcollections. For\n // example, a query on 'rooms' will return rooms/abc/messages/xyx but we\n // shouldn't match it. Fix this by discarding rows with document keys\n // more than one segment longer than the query path.\n if (key.length !== immediateChildrenPathLength) {\n return;\n }\n\n const maybeDoc = this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n } else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n })\n .next(() => results);\n }\n\n getNewDocumentChanges(\n transaction: PersistenceTransaction,\n sinceReadTime: SnapshotVersion\n ): PersistencePromise<{\n changedDocs: MaybeDocumentMap;\n readTime: SnapshotVersion;\n }> {\n let changedDocs = maybeDocumentMap();\n\n let lastReadTime = this.serializer.toDbTimestampKey(sinceReadTime);\n\n const documentsStore = remoteDocumentsStore(transaction);\n const range = IDBKeyRange.lowerBound(lastReadTime, true);\n return documentsStore\n .iterate(\n { index: DbRemoteDocument.readTimeIndex, range },\n (_, dbRemoteDoc) => {\n // Unlike `getEntry()` and others, `getNewDocumentChanges()` parses\n // the documents directly since we want to keep sentinel deletes.\n const doc = this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n changedDocs = changedDocs.insert(doc.key, doc);\n lastReadTime = dbRemoteDoc.readTime!;\n }\n )\n .next(() => {\n return {\n changedDocs,\n readTime: this.serializer.fromDbTimestampKey(lastReadTime)\n };\n });\n }\n\n getLastReadTime(\n transaction: PersistenceTransaction\n ): PersistencePromise<SnapshotVersion> {\n const documentsStore = remoteDocumentsStore(transaction);\n\n // If there are no existing entries, we return SnapshotVersion.MIN.\n let readTime = SnapshotVersion.MIN;\n\n return documentsStore\n .iterate(\n { index: DbRemoteDocument.readTimeIndex, reverse: true },\n (key, dbRemoteDoc, control) => {\n if (dbRemoteDoc.readTime) {\n readTime = this.serializer.fromDbTimestampKey(dbRemoteDoc.readTime);\n }\n control.done();\n }\n )\n .next(() => readTime);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentCache.RemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise<DbRemoteDocumentGlobal> {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobal.key)\n .next(metadata => {\n assert(!!metadata, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise<void> {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobal.key, metadata);\n }\n\n /**\n * Decodes `remoteDoc` and returns the document (or null, if the document\n * corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n dbRemoteDoc: DbRemoteDocument | null\n ): MaybeDocument | null {\n if (dbRemoteDoc) {\n const doc = this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n if (\n doc instanceof NoDocument &&\n doc.version.isEqual(SnapshotVersion.forDeletedDoc())\n ) {\n // The document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`.\n return null;\n }\n\n return doc;\n }\n return null;\n }\n\n /**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\n private static RemoteDocumentChangeBuffer = class extends RemoteDocumentChangeBuffer {\n // A map of document sizes prior to applying the changes in this buffer.\n protected documentSizes: ObjectMap<\n DocumentKey,\n number\n > = new ObjectMap(key => key.toString());\n\n /**\n * @param documentCache The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCache,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise<void> {\n const promises: Array<PersistencePromise<void>> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet<ResourcePath>((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, maybeDocument) => {\n const previousSize = this.documentSizes.get(key);\n assert(\n previousSize !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n if (maybeDocument) {\n assert(\n !this.readTime.isEqual(SnapshotVersion.MIN),\n 'Cannot add a document with a read time of zero'\n );\n const doc = this.documentCache.serializer.toDbRemoteDocument(\n maybeDocument,\n this.readTime\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousSize!;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousSize!;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = this.documentCache.serializer.toDbRemoteDocument(\n new NoDocument(key, SnapshotVersion.forDeletedDoc()),\n this.readTime\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n } else {\n promises.push(this.documentCache.removeEntry(transaction, key));\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise<MaybeDocument | null> {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n if (getResult === null) {\n this.documentSizes.set(documentKey, 0);\n return null;\n } else {\n this.documentSizes.set(documentKey, getResult.size);\n return getResult.maybeDocument;\n }\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise<NullableMaybeDocumentMap> {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ maybeDocuments, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `NullableMaybeDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentSizes.set(documentKey, size);\n });\n return maybeDocuments;\n });\n }\n };\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal> {\n return IndexedDbPersistence.getStore<\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobal\n >(txn, DbRemoteDocumentGlobal.store);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbRemoteDocumentKey, DbRemoteDocument> {\n return IndexedDbPersistence.getStore<DbRemoteDocumentKey, DbRemoteDocument>(\n txn,\n DbRemoteDocument.store\n );\n}\n\nfunction dbKey(docKey: DocumentKey): DbRemoteDocumentKey {\n return docKey.path.toArray();\n}\n\n/**\n * Retrusn an approximate size for the given document.\n */\nexport function dbDocumentSize(doc: DbRemoteDocument): number {\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail('Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { ResourcePath } from '../model/path';\nimport * as api from '../protos/firestore_proto_api';\nimport { assert } from '../util/assert';\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BATCHID_UNKNOWN } from '../model/mutation_batch';\nimport { decode, encode, EncodedResourcePath } from './encoded_resource_path';\nimport { removeMutationBatch } from './indexeddb_mutation_queue';\nimport { getHighestListenSequenceNumber } from './indexeddb_target_cache';\nimport { dbDocumentSize } from './indexeddb_remote_document_cache';\nimport { LocalSerializer } from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote Document\n * Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n */\nexport const SCHEMA_VERSION = 9;\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise<void> {\n assert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v{toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction(txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n createRemoteDocumentReadTimeIndex(txn);\n });\n }\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n let byteCount = 0;\n return txn\n .store<DbRemoteDocumentKey, DbRemoteDocument>(DbRemoteDocument.store)\n .iterate((_, doc) => {\n byteCount += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata = new DbRemoteDocumentGlobal(byteCount);\n return txn\n .store<DbRemoteDocumentGlobalKey, DbRemoteDocumentGlobal>(\n DbRemoteDocumentGlobal.store\n )\n .put(DbRemoteDocumentGlobal.key, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const queuesStore = txn.store<DbMutationQueueKey, DbMutationQueue>(\n DbMutationQueue.store\n );\n const mutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatch.store\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatch.userMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n assert(\n dbBatch.userId === queue.userId,\n `Cannot process batch ${dbBatch.batchId} from unexpected user`\n );\n const batch = this.serializer.fromDbMutationBatch(dbBatch);\n\n return removeMutationBatch(\n txn,\n queue.userId,\n batch\n ).next(() => {});\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocument.store);\n const documentsStore = txn.store<DbRemoteDocumentKey, DbRemoteDocument>(\n DbRemoteDocument.store\n );\n\n return getHighestListenSequenceNumber(txn).next(currentSequenceNumber => {\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise<void> => {\n return documentTargetStore.put(\n new DbTargetDocument(0, encode(path), currentSequenceNumber)\n );\n };\n\n const promises: Array<PersistencePromise<void>> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n // Create the index.\n db.createObjectStore(DbCollectionParent.store, {\n keyPath: DbCollectionParent.keyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParent.store);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise<void> | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encode(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store<DbRemoteDocumentKey, DbRemoteDocument>(DbRemoteDocument.store)\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store<DbDocumentMutationKey, DbDocumentMutation>(\n DbDocumentMutation.store\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decode(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encode(path)];\n}\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport class DbTimestamp {\n constructor(public seconds: number, public nanoseconds: number) {}\n}\n\n/** A timestamp type that can be used in IndexedDb keys. */\nexport type DbTimestampKey = [/* seconds */ number, /* nanos */ number];\n\n// The key for the singleton object in the DbPrimaryClient is a single string.\nexport type DbPrimaryClientKey = typeof DbPrimaryClient.key;\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport class DbPrimaryClient {\n /**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n static store = 'owner';\n\n /**\n * The key string used for the single object that exists in the\n * DbPrimaryClient store.\n */\n static key = 'owner';\n\n constructor(\n public ownerId: string,\n /** Whether to allow shared access from multiple tabs. */\n public allowTabSynchronization: boolean,\n public leaseTimestampMs: number\n ) {}\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClient.store);\n}\n\n/** Object keys in the 'mutationQueues' store are userId strings. */\nexport type DbMutationQueueKey = string;\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport class DbMutationQueue {\n /** Name of the IndexedDb object store. */\n static store = 'mutationQueues';\n\n /** Keys are automatically assigned via the userId property. */\n static keyPath = 'userId';\n\n constructor(\n /**\n * The normalized user ID to which this queue belongs.\n */\n public userId: string,\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n public lastAcknowledgedBatchId: number,\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n */\n public lastStreamToken: string\n ) {}\n}\n\n/** The 'mutations' store is keyed by batch ID. */\nexport type DbMutationBatchKey = BatchId;\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport class DbMutationBatch {\n /** Name of the IndexedDb object store. */\n static store = 'mutations';\n\n /** Keys are automatically assigned via the userId, batchId properties. */\n static keyPath = 'batchId';\n\n /** The index name for lookup of mutations by user. */\n static userMutationsIndex = 'userMutationsIndex';\n\n /** The user mutations index is keyed by [userId, batchId] pairs. */\n static userMutationsKeyPath = ['userId', 'batchId'];\n\n constructor(\n /**\n * The normalized user ID to which this batch belongs.\n */\n public userId: string,\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n public batchId: BatchId,\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n public localWriteTimeMs: number,\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n public baseMutations: api.Write[] | undefined,\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via JsonProtoSerializer.toMutation().\n */\n public mutations: api.Write[]\n ) {}\n}\n\n/**\n * The key for a db document mutation, which is made up of a userID, path, and\n * batchId. Note that the path must be serialized into a form that indexedDB can\n * sort.\n */\nexport type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId];\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatch.userMutationsIndex,\n DbMutationBatch.userMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutation.store);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise<void> {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatch.store\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatch.store);\n\n const mutationsStore = db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatch.userMutationsIndex,\n DbMutationBatch.userMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store<DbMutationBatchKey, DbMutationBatch>(\n DbMutationBatch.store\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport class DbDocumentMutation {\n static store = 'documentMutations';\n\n /**\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\n * over all of a user's document mutations.\n */\n static prefixForUser(userId: string): [string] {\n return [userId];\n }\n\n /**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\n static prefixForPath(\n userId: string,\n path: ResourcePath\n ): [string, EncodedResourcePath] {\n return [userId, encode(path)];\n }\n\n /**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */\n static key(\n userId: string,\n path: ResourcePath,\n batchId: BatchId\n ): DbDocumentMutationKey {\n return [userId, encode(path), batchId];\n }\n\n /**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */\n static PLACEHOLDER = new DbDocumentMutation();\n\n private constructor() {}\n}\n\n/**\n * A key in the 'remoteDocuments' object store is a string array containing the\n * segments that make up the path.\n */\nexport type DbRemoteDocumentKey = string[];\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocument.store);\n}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport class DbNoDocument {\n constructor(public path: string[], public readTime: DbTimestamp) {}\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport class DbUnknownDocument {\n constructor(public path: string[], public version: DbTimestamp) {}\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport class DbRemoteDocument {\n static store = 'remoteDocuments';\n\n /**\n * An index that provides access to all entries sorted by read time (which\n * corresponds to the last modification time of each row).\n *\n * This index is used to provide a changelog for Multi-Tab.\n */\n static readTimeIndex = 'readTimeIndex';\n\n static readTimeIndexPath = 'readTime';\n\n /**\n * An index that provides access to documents in a collection sorted by read\n * time.\n *\n * This index is used to allow the RemoteDocumentCache to fetch newly changed\n * documents in a collection.\n */\n static collectionReadTimeIndex = 'collectionReadTimeIndex';\n\n static collectionReadTimeIndexPath = ['parentPath', 'readTime'];\n\n // TODO: We are currently storing full document keys almost three times\n // (once as part of the primary key, once - partly - as `parentPath` and once\n // inside the encoded documents). During our next migration, we should\n // rewrite the primary key as parentPath + document ID which would allow us\n // to drop one value.\n\n constructor(\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n public unknownDocument: DbUnknownDocument | null | undefined,\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n public noDocument: DbNoDocument | null,\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n public document: api.Document | null,\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n public hasCommittedMutations: boolean | undefined,\n\n /**\n * When the document was read from the backend. Undefined for data written\n * prior to schema version 9.\n */\n public readTime: DbTimestampKey | undefined,\n\n /**\n * The path of the collection this document is part of. Undefined for data\n * written prior to schema version 9.\n */\n public parentPath: string[] | undefined\n ) {}\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport class DbRemoteDocumentGlobal {\n static store = 'remoteDocumentGlobal';\n\n static key = 'remoteDocumentGlobalKey';\n\n /**\n * @param byteSize Approximately the total size in bytes of all the documents in the document\n * cache.\n */\n constructor(public byteSize: number) {}\n}\n\nexport type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobal.key;\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobal.store);\n}\n\n/**\n * A key in the 'targets' object store is a targetId of the query.\n */\nexport type DbTargetKey = TargetId;\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = api.QueryTarget | api.DocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport class DbTarget {\n static store = 'targets';\n\n /** Keys are automatically assigned via the targetId property. */\n static keyPath = 'targetId';\n\n /** The name of the queryTargets index. */\n static queryTargetsIndexName = 'queryTargetsIndex';\n\n /**\n * The index of all canonicalIds to the targets that they match. This is not\n * a unique mapping because canonicalId does not promise a unique name for all\n * possible queries, so we append the targetId to make the mapping unique.\n */\n static queryTargetsKeyPath = ['canonicalId', 'targetId'];\n\n constructor(\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n public targetId: TargetId,\n /**\n * The canonical string representing this query. This is not unique.\n */\n public canonicalId: string,\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n public readTime: DbTimestamp,\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n public resumeToken: string,\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n public lastListenSequenceNumber: number,\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n public lastLimboFreeSnapshotVersion: DbTimestamp | undefined,\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n public query: DbQuery\n ) {}\n}\n\n/**\n * The key for a DbTargetDocument, containing a targetId and an encoded resource\n * path.\n */\nexport type DbTargetDocumentKey = [TargetId, EncodedResourcePath];\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport class DbTargetDocument {\n /** Name of the IndexedDb object store. */\n static store = 'targetDocuments';\n\n /** Keys are automatically assigned via the targetId, path properties. */\n static keyPath = ['targetId', 'path'];\n\n /** The index name for the reverse index. */\n static documentTargetsIndex = 'documentTargetsIndex';\n\n /** We also need to create the reverse index for these properties. */\n static documentTargetsKeyPath = ['path', 'targetId'];\n\n constructor(\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n public targetId: TargetId,\n /**\n * The path to the document, as encoded in the key.\n */\n public path: EncodedResourcePath,\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n public sequenceNumber?: ListenSequenceNumber\n ) {\n assert(\n (targetId === 0) === (sequenceNumber !== undefined),\n 'A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number'\n );\n }\n}\n\n/**\n * The type to represent the single allowed key for the DbTargetGlobal store.\n */\nexport type DbTargetGlobalKey = typeof DbTargetGlobal.key;\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport class DbTargetGlobal {\n /**\n * The key string used for the single object that exists in the\n * DbTargetGlobal store.\n */\n static key = 'targetGlobalKey';\n static store = 'targetGlobal';\n\n constructor(\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n public highestTargetId: TargetId,\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n public highestListenSequenceNumber: number,\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n public lastRemoteSnapshotVersion: DbTimestamp,\n /**\n * The number of targets persisted.\n */\n public targetCount: number\n ) {}\n}\n\n/**\n * The key for a DbCollectionParent entry, containing the collection ID\n * and the parent path that contains it. Note that the parent path will be an\n * empty path in the case of root-level collections.\n */\nexport type DbCollectionParentKey = [string, EncodedResourcePath];\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport class DbCollectionParent {\n /** Name of the IndexedDb object store. */\n static store = 'collectionParents';\n\n /** Keys are automatically assigned via the collectionId, parent properties. */\n static keyPath = ['collectionId', 'parent'];\n\n constructor(\n /**\n * The collectionId (e.g. 'messages')\n */\n public collectionId: string,\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n public parent: EncodedResourcePath\n ) {}\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, {\n keyPath: DbTargetDocument.keyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocument.documentTargetsIndex,\n DbTargetDocument.documentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTarget.queryTargetsIndexName,\n DbTarget.queryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobal.store);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocument.store);\n db.deleteObjectStore(DbTarget.store);\n db.deleteObjectStore(DbTargetGlobal.store);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise<void> {\n const globalStore = txn.store<DbTargetGlobalKey, DbTargetGlobal>(\n DbTargetGlobal.store\n );\n const metadata = new DbTargetGlobal(\n /*highestTargetId=*/ 0,\n /*lastListenSequenceNumber=*/ 0,\n SnapshotVersion.MIN.toTimestamp(),\n /*targetCount=*/ 0\n );\n return globalStore.put(DbTargetGlobal.key, metadata);\n}\n\n/**\n * Creates indices on the RemoteDocuments store used for both multi-tab\n * and Index-Free queries.\n */\nfunction createRemoteDocumentReadTimeIndex(txn: IDBTransaction): void {\n const remoteDocumentStore = txn.objectStore(DbRemoteDocument.store);\n remoteDocumentStore.createIndex(\n DbRemoteDocument.readTimeIndex,\n DbRemoteDocument.readTimeIndexPath,\n { unique: false }\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocument.collectionReadTimeIndex,\n DbRemoteDocument.collectionReadTimeIndexPath,\n { unique: false }\n );\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport class DbClientMetadata {\n /** Name of the IndexedDb object store. */\n static store = 'clientMetadata';\n\n /** Keys are automatically assigned via the clientId properties. */\n static keyPath = 'clientId';\n\n constructor(\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n public clientId: string,\n /** The last time this state was updated. */\n public updateTimeMs: number,\n /** Whether the client's network connection is enabled. */\n public networkEnabled: boolean,\n /** Whether this client is running in a foreground tab. */\n public inForeground: boolean\n ) {}\n}\n\n/** Object keys in the 'clientMetadata' store are clientId strings. */\nexport type DbClientMetadataKey = string;\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadata.store, {\n keyPath: DbClientMetadata.keyPath\n });\n}\n\n// Visible for testing\nexport const V1_STORES = [\n DbMutationQueue.store,\n DbMutationBatch.store,\n DbDocumentMutation.store,\n DbRemoteDocument.store,\n DbTarget.store,\n DbPrimaryClient.store,\n DbTargetGlobal.store,\n DbTargetDocument.store\n];\n\n// V2 is no longer usable (see comment at top of file)\n\n// Visible for testing\nexport const V3_STORES = V1_STORES;\n\n// Visible for testing\n// Note: DbRemoteDocumentChanges is no longer used and dropped with v9.\nexport const V4_STORES = [...V3_STORES, DbClientMetadata.store];\n\n// V5 does not change the set of stores.\n\nexport const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobal.store];\n\n// V7 does not change the set of stores.\n\nexport const V8_STORES = [...V6_STORES, DbCollectionParent.store];\n\n// V9 does not change the set of stores.\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V8_STORES;\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ResourcePath } from '../model/path';\nimport { assert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\nimport { decode, encode } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbPersistence } from './indexeddb_persistence';\nimport { DbCollectionParent, DbCollectionParentKey } from './indexeddb_schema';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { PersistenceTransaction } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * A persisted implementation of IndexManager.\n */\nexport class IndexedDbIndexManager implements IndexManager {\n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be used to\n * satisfy reads.\n */\n private collectionParentsCache = new MemoryCollectionParentIndex();\n\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise<void> {\n assert(collectionPath.length % 2 === 1, 'Expected a collection path.');\n if (!this.collectionParentsCache.has(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n\n transaction.addOnCommittedListener(() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.collectionParentsCache.add(collectionPath);\n });\n\n const collectionParent: DbCollectionParent = {\n collectionId,\n parent: encode(parentPath)\n };\n return collectionParentsStore(transaction).put(collectionParent);\n }\n return PersistencePromise.resolve();\n }\n\n getCollectionParents(\n transaction: PersistenceTransaction,\n collectionId: string\n ): PersistencePromise<ResourcePath[]> {\n const parentPaths = [] as ResourcePath[];\n const range = IDBKeyRange.bound(\n [collectionId, ''],\n [immediateSuccessor(collectionId), ''],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return collectionParentsStore(transaction)\n .loadAll(range)\n .next(entries => {\n for (const entry of entries) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (entry.collectionId !== collectionId) {\n break;\n }\n parentPaths.push(decode(entry.parent));\n }\n return parentPaths;\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */\nfunction collectionParentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore<DbCollectionParentKey, DbCollectionParent> {\n return IndexedDbPersistence.getStore<\n DbCollectionParentKey,\n DbCollectionParent\n >(txn, DbCollectionParent.store);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n Document,\n MaybeDocument,\n NoDocument,\n UnknownDocument\n} from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { MutationBatch } from '../model/mutation_batch';\nimport * as api from '../protos/firestore_proto_api';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { assert, fail } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { Target } from '../core/target';\nimport { decode, encode, EncodedResourcePath } from './encoded_resource_path';\nimport {\n DbMutationBatch,\n DbNoDocument,\n DbQuery,\n DbRemoteDocument,\n DbTarget,\n DbTimestamp,\n DbTimestampKey,\n DbUnknownDocument\n} from './indexeddb_schema';\nimport { TargetData, TargetPurpose } from './target_data';\n\n/** Serializer for values stored in the LocalStore. */\nexport class LocalSerializer {\n constructor(private remoteSerializer: JsonProtoSerializer) {}\n\n /** Decodes a remote document from storage locally to a Document. */\n fromDbRemoteDocument(remoteDoc: DbRemoteDocument): MaybeDocument {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(\n remoteDoc.document,\n !!remoteDoc.hasCommittedMutations\n );\n } else if (remoteDoc.noDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n const version = this.fromDbTimestamp(remoteDoc.noDocument.readTime);\n return new NoDocument(key, version, {\n hasCommittedMutations: !!remoteDoc.hasCommittedMutations\n });\n } else if (remoteDoc.unknownDocument) {\n const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n const version = this.fromDbTimestamp(remoteDoc.unknownDocument.version);\n return new UnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n }\n\n /** Encodes a document for storage locally. */\n toDbRemoteDocument(\n maybeDoc: MaybeDocument,\n readTime: SnapshotVersion\n ): DbRemoteDocument {\n const dbReadTime = this.toDbTimestampKey(readTime);\n const parentPath = maybeDoc.key.path.popLast().toArray();\n if (maybeDoc instanceof Document) {\n const doc = maybeDoc.proto\n ? maybeDoc.proto\n : this.remoteSerializer.toDocument(maybeDoc);\n const hasCommittedMutations = maybeDoc.hasCommittedMutations;\n return new DbRemoteDocument(\n /* unknownDocument= */ null,\n /* noDocument= */ null,\n doc,\n hasCommittedMutations,\n dbReadTime,\n parentPath\n );\n } else if (maybeDoc instanceof NoDocument) {\n const path = maybeDoc.key.path.toArray();\n const readTime = this.toDbTimestamp(maybeDoc.version);\n const hasCommittedMutations = maybeDoc.hasCommittedMutations;\n return new DbRemoteDocument(\n /* unknownDocument= */ null,\n new DbNoDocument(path, readTime),\n /* document= */ null,\n hasCommittedMutations,\n dbReadTime,\n parentPath\n );\n } else if (maybeDoc instanceof UnknownDocument) {\n const path = maybeDoc.key.path.toArray();\n const readTime = this.toDbTimestamp(maybeDoc.version);\n return new DbRemoteDocument(\n new DbUnknownDocument(path, readTime),\n /* noDocument= */ null,\n /* document= */ null,\n /* hasCommittedMutations= */ true,\n dbReadTime,\n parentPath\n );\n } else {\n return fail('Unexpected MaybeDocument');\n }\n }\n\n toDbTimestampKey(snapshotVersion: SnapshotVersion): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n }\n\n fromDbTimestampKey(dbTimestampKey: DbTimestampKey): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n }\n\n private toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return new DbTimestamp(timestamp.seconds, timestamp.nanoseconds);\n }\n\n private fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(\n dbTimestamp.seconds,\n dbTimestamp.nanoseconds\n );\n return SnapshotVersion.fromTimestamp(timestamp);\n }\n\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n toDbMutationBatch(userId: string, batch: MutationBatch): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n this.remoteSerializer.toMutation(m)\n );\n const serializedMutations = batch.mutations.map(m =>\n this.remoteSerializer.toMutation(m)\n );\n return new DbMutationBatch(\n userId,\n batch.batchId,\n batch.localWriteTime.toMillis(),\n serializedBaseMutations,\n serializedMutations\n );\n }\n\n /** Decodes a DbMutationBatch into a MutationBatch */\n fromDbMutationBatch(dbBatch: DbMutationBatch): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n this.remoteSerializer.fromMutation(m)\n );\n const mutations = dbBatch.mutations.map(m =>\n this.remoteSerializer.fromMutation(m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n }\n\n /*\n * Encodes a set of document keys into an array of EncodedResourcePaths.\n */\n toDbResourcePaths(keys: DocumentKeySet): EncodedResourcePath[] {\n const encodedKeys: EncodedResourcePath[] = [];\n\n keys.forEach(key => {\n encodedKeys.push(encode(key.path));\n });\n\n return encodedKeys;\n }\n\n /** Decodes an array of EncodedResourcePaths into a set of document keys. */\n fromDbResourcePaths(encodedPaths: EncodedResourcePath[]): DocumentKeySet {\n let keys = documentKeySet();\n\n for (const documentKey of encodedPaths) {\n keys = keys.add(new DocumentKey(decode(documentKey)));\n }\n\n return keys;\n }\n\n /** Decodes a DbTarget into TargetData */\n fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = this.fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? this.fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.MIN;\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n } else {\n target = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n }\n\n /** Encodes TargetData into a DbTarget for storage locally. */\n toDbTarget(targetData: TargetData): DbTarget {\n assert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = this.toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = this.toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetData.target.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(targetData.target);\n } else {\n queryProto = this.remoteSerializer.toQueryTarget(targetData.target);\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return new DbTarget(\n targetData.targetId,\n targetData.target.canonicalId(),\n dbTimestamp,\n resumeToken,\n targetData.sequenceNumber,\n dbLastLimboFreeTimestamp,\n queryProto\n );\n }\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is api.DocumentsTarget {\n return (dbQuery as api.DocumentsTarget).documents !== undefined;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { User } from '../auth/user';\nimport { DatabaseInfo } from '../core/database_info';\nimport { PersistenceSettings } from '../core/firestore_client';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\nimport { Platform } from '../platform/platform';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { assert, fail } from '../util/assert';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { CancelablePromise } from '../util/promise';\n\nimport { decode, encode, EncodedResourcePath } from './encoded_resource_path';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport {\n IndexedDbMutationQueue,\n mutationQueuesContainKey\n} from './indexeddb_mutation_queue';\nimport { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n ALL_STORES,\n DbClientMetadata,\n DbClientMetadataKey,\n DbPrimaryClient,\n DbPrimaryClientKey,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION,\n SchemaConverter\n} from './indexeddb_schema';\nimport {\n documentTargetStore,\n getHighestListenSequenceNumber,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport { LocalSerializer } from './local_serializer';\nimport {\n ActiveTargets,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruScheduler\n} from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport {\n GarbageCollectionScheduler,\n Persistence,\n PersistenceProvider,\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG,\n PrimaryStateListener,\n ReferenceDelegate\n} from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nimport {\n ClientId,\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} from './shared_client_state';\nimport { TargetData } from './target_data';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Another tab has exclusive access to the persistence layer. ' +\n 'To allow shared access, make sure to invoke ' +\n '`enablePersistence()` with `synchronizeTabs:true` in all tabs.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing' +\n ' IndexedDB or is known to have an incomplete implementation. Offline' +\n ' persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie_<persistence_prefix>_<instance_key>\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n static getStore<Key extends IDBValidKey, Value>(\n txn: PersistenceTransaction,\n store: string\n ): SimpleDbStore<Key, Value> {\n if (txn instanceof IndexedDbTransaction) {\n return SimpleDb.getStore<Key, Value>(txn.simpleDbTransaction, store);\n } else {\n throw fail(\n 'IndexedDbPersistence must use instances of IndexedDbTransaction'\n );\n }\n }\n\n /**\n * The name of the main (and currently only) IndexedDB database. this name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\n static MAIN_DATABASE = 'main';\n\n static async createIndexedDbPersistence(options: {\n allowTabSynchronization: boolean;\n persistenceKey: string;\n clientId: ClientId;\n platform: Platform;\n lruParams: LruParams;\n queue: AsyncQueue;\n serializer: JsonProtoSerializer;\n sequenceNumberSyncer: SequenceNumberSyncer;\n }): Promise<IndexedDbPersistence> {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n const persistence = new IndexedDbPersistence(\n options.allowTabSynchronization,\n options.persistenceKey,\n options.clientId,\n options.platform,\n options.lruParams,\n options.queue,\n options.serializer,\n options.sequenceNumberSyncer\n );\n await persistence.start();\n return persistence;\n }\n\n private readonly document: Document | null;\n private readonly window: Window;\n\n // Technically these types should be `| undefined` because they are\n // initialized asynchronously by start(), but that would be more misleading\n // than useful.\n private simpleDb!: SimpleDb;\n private listenSequence!: ListenSequence;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: CancelablePromise<void> | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly targetCache: IndexedDbTargetCache;\n private readonly indexManager: IndexedDbIndexManager;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly webStorage: Storage;\n readonly referenceDelegate: IndexedDbLruDelegate;\n\n private constructor(\n private readonly allowTabSynchronization: boolean,\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n platform: Platform,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer\n ) {\n this.referenceDelegate = new IndexedDbLruDelegate(this, lruParams);\n this.dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.document = platform.document;\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.indexManager = new IndexedDbIndexManager();\n this.remoteDocumentCache = new IndexedDbRemoteDocumentCache(\n this.serializer,\n this.indexManager\n );\n if (platform.window && platform.window.localStorage) {\n this.window = platform.window;\n this.webStorage = this.window.localStorage;\n } else {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @return {Promise<void>} Whether persistence was enabled.\n */\n private start(): Promise<void> {\n assert(!this.started, 'IndexedDbPersistence double-started!');\n assert(this.window !== null, \"Expected 'window' to be defined\");\n\n return SimpleDb.openOrCreate(\n this.dbName,\n SCHEMA_VERSION,\n new SchemaConverter(this.serializer)\n )\n .then(db => {\n this.simpleDb = db;\n // NOTE: This is expected to fail sometimes (in the case of another tab already\n // having the persistence lock), so it's the first thing we should do.\n return this.updateClientMetadataAndTryBecomePrimary();\n })\n .then(() => {\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.simpleDb.runTransaction(\n 'readonly',\n [DbTargetGlobal.store],\n txn => getHighestListenSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise<void> {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise<void>\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise<void> {\n return this.simpleDb\n .runTransaction('readwrite', ALL_STORES, txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put(\n new DbClientMetadata(\n this.clientId,\n Date.now(),\n this.networkEnabled,\n this.inForeground\n )\n )\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueAndForget(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n })\n .catch(e => {\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n log.debug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueAndForget(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: SimpleDbTransaction\n ): PersistencePromise<boolean> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise<void> {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = IndexedDbPersistence.getStore<\n DbClientMetadataKey,\n DbClientMetadata\n >(txn, DbClientMetadata.store);\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n inactiveClients.forEach(inactiveClient => {\n this.window.localStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n });\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: SimpleDbTransaction\n ): PersistencePromise<boolean> {\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClient.key)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n log.debug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise<void> {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n await this.simpleDb.runTransaction(\n 'readwrite',\n [DbPrimaryClient.store, DbClientMetadata.store],\n txn => {\n return this.releasePrimaryLeaseIfHeld(txn).next(() =>\n this.removeClientMetadata(txn)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n getActiveClients(): Promise<ClientId[]> {\n return this.simpleDb.runTransaction(\n 'readonly',\n [DbClientMetadata.store],\n txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n }\n );\n }\n\n static async clearPersistence(persistenceKey: string): Promise<void> {\n if (!IndexedDbPersistence.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getMutationQueue(user: User): MutationQueue {\n assert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n this.indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n assert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n assert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(): IndexedDbIndexManager {\n assert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return this.indexManager;\n }\n\n runTransaction<T>(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise<T>\n ): Promise<T> {\n log.debug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(simpleDbMode, ALL_STORES, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence.next()\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(simpleDbTxn)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(simpleDbTxn);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n log.error(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueAndForget(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(simpleDbTxn).next(\n () => result\n );\n });\n } else {\n return this.verifyAllowTabSynchronization(simpleDbTxn).next(() =>\n transactionOperation(persistenceTransaction)\n );\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const newPrimary = new DbPrimaryClient(\n this.clientId,\n this.allowTabSynchronization,\n Date.now()\n );\n return primaryClientStore(txn).put(DbPrimaryClient.key, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\n static buildStoragePrefix(databaseInfo: DatabaseInfo): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseInfo.databaseId.projectId;\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: SimpleDbTransaction\n ): PersistencePromise<void> {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n log.debug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClient.key);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n log.error(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n assert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('unload', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n assert(\n typeof this.window.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage.getItem(this.zombiedClientLocalStorageKey(clientId)) !==\n null;\n log.debug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n log.error(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n log.error('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: SimpleDbTransaction\n): SimpleDbStore<DbPrimaryClientKey, DbPrimaryClient> {\n return txn.store<DbPrimaryClientKey, DbPrimaryClient>(DbPrimaryClient.store);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: SimpleDbTransaction\n): SimpleDbStore<DbClientMetadataKey, DbClientMetadata> {\n return txn.store<DbClientMetadataKey, DbClientMetadata>(\n DbClientMetadata.store\n );\n}\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegate implements ReferenceDelegate, LruDelegate {\n private inMemoryPins: ReferenceSet | null = null;\n\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: IndexedDbPersistence, params: LruParams) {\n this.garbageCollector = new LruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n const docCountPromise = this.orphanedDocmentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocmentCount(\n txn: PersistenceTransaction\n ): PersistencePromise<number> {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise<void> {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n setInMemoryPins(inMemoryPins: ReferenceSet): void {\n this.inMemoryPins = inMemoryPins;\n }\n\n addReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise<number> {\n return this.db\n .getTargetCache()\n .removeTargets(txn, upperBound, activeTargetIds);\n }\n\n removeMutationReference(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise<boolean> {\n if (this.inMemoryPins!.containsKey(docKey)) {\n return PersistencePromise.resolve<boolean>(true);\n } else {\n return mutationQueuesContainKey(txn, docKey);\n }\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise<number> {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array<PersistencePromise<void>> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey);\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise<void> {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise<void> {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise<void> {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocument.documentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decode(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decode(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise<number> {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encode(key.path)];\n}\n\n/**\n * @return A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return new DbTargetDocument(0, encode(key.path), sequenceNumber);\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise<void> {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n\n/**\n * Provides all components needed for IndexedDb persistence.\n */\nexport class IndexedDbPersistenceProvider implements PersistenceProvider {\n private persistence?: IndexedDbPersistence;\n private gcScheduler?: GarbageCollectionScheduler;\n private sharedClientState?: SharedClientState;\n\n async initialize(\n asyncQueue: AsyncQueue,\n databaseInfo: DatabaseInfo,\n platform: Platform,\n clientId: ClientId,\n initialUser: User,\n settings: PersistenceSettings\n ): Promise<void> {\n assert(\n settings.durable,\n 'IndexedDbPersistenceProvider can only provide durable persistence'\n );\n assert(!this.persistence, 'configure() already called');\n\n const persistenceKey = IndexedDbPersistence.buildStoragePrefix(\n databaseInfo\n );\n\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n const serializer = new JsonProtoSerializer(databaseInfo.databaseId, {\n useProto3Json: true\n });\n\n if (!WebStorageSharedClientState.isAvailable(platform)) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n\n this.sharedClientState = settings.synchronizeTabs\n ? new WebStorageSharedClientState(\n asyncQueue,\n platform,\n persistenceKey,\n clientId,\n initialUser\n )\n : new MemorySharedClientState();\n\n this.persistence = await IndexedDbPersistence.createIndexedDbPersistence({\n allowTabSynchronization: settings.synchronizeTabs,\n persistenceKey,\n clientId,\n platform,\n queue: asyncQueue,\n serializer,\n lruParams: LruParams.withCacheSize(settings.cacheSizeBytes),\n sequenceNumberSyncer: this.sharedClientState\n });\n\n const garbageCollector = this.persistence.referenceDelegate\n .garbageCollector;\n this.gcScheduler = new LruScheduler(garbageCollector, asyncQueue);\n }\n\n getPersistence(): Persistence {\n assert(!!this.persistence, 'initialize() not called');\n return this.persistence;\n }\n\n getSharedClientState(): SharedClientState {\n assert(!!this.sharedClientState, 'initialize() not called');\n return this.sharedClientState;\n }\n\n getGarbageCollectionScheduler(): GarbageCollectionScheduler {\n assert(!!this.gcScheduler, 'initialize() not called');\n return this.gcScheduler;\n }\n\n clearPersistence(databaseInfo: DatabaseInfo): Promise<void> {\n const persistenceKey = IndexedDbPersistence.buildStoragePrefix(\n databaseInfo\n );\n return IndexedDbPersistence.clearPersistence(persistenceKey);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FirebaseNamespace, FirebaseApp } from '@firebase/app-types';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType, Provider } from '@firebase/component';\nimport { PublicBlob } from '../api/blob';\nimport {\n CACHE_SIZE_UNLIMITED,\n Firestore,\n PublicCollectionReference,\n PublicDocumentReference,\n PublicDocumentSnapshot,\n PublicFirestore,\n PublicQuery,\n PublicQueryDocumentSnapshot,\n PublicQuerySnapshot,\n PublicTransaction,\n PublicWriteBatch\n} from '../api/database';\nimport { FieldPath } from '../api/field_path';\nimport { PublicFieldValue } from '../api/field_value';\nimport { GeoPoint } from '../api/geo_point';\nimport { Timestamp } from '../api/timestamp';\nimport { shallowCopy } from '../util/obj';\n\nconst firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint,\n Timestamp,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath,\n FieldValue: PublicFieldValue,\n setLogLevel: Firestore.setLogLevel,\n CACHE_SIZE_UNLIMITED\n};\n\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerService.\n *\n * @param firebase The FirebaseNamespace to register Firestore with\n * @param firestoreFactory A factory function that returns a new Firestore\n * instance.\n */\nexport function configureForFirebase(\n firebase: FirebaseNamespace,\n firestoreFactory: (\n app: FirebaseApp,\n auth: Provider<FirebaseAuthInternalName>\n ) => Firestore\n): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'firestore',\n container => {\n const app = container.getProvider('app').getImmediate()!;\n return firestoreFactory(app, container.getProvider('auth-internal'));\n },\n ComponentType.PUBLIC\n ).setServiceProps(shallowCopy(firestoreNamespace))\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\nimport { FirebaseNamespace } from '@firebase/app-types';\n\nimport { Firestore } from './src/api/database';\nimport { IndexedDbPersistenceProvider } from './src/local/indexeddb_persistence';\nimport { configureForFirebase } from './src/platform/config';\nimport { name, version } from './package.json';\n\nimport './register-module';\nimport './src/platform_browser/browser_init';\n\n/**\n * Registers the main Firestore build with the components framework.\n * Persistence can be enabled via `firebase.firestore().enablePersistence()`.\n */\nexport function registerFirestore(instance: FirebaseNamespace): void {\n configureForFirebase(\n instance,\n (app, auth) => new Firestore(app, auth, new IndexedDbPersistenceProvider())\n );\n instance.registerVersion(name, version);\n}\n\nregisterFirestore(firebase);\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor';\n\nexport class NoopConnectivityMonitor implements ConnectivityMonitor {\n addCallback(callback: (status: NetworkStatus) => void): void {\n // No-op.\n }\n\n shutdown(): void {\n // No-op.\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { debug } from '../util/log';\nimport {\n ConnectivityMonitor,\n ConnectivityMonitorCallback,\n NetworkStatus\n} from './../remote/connectivity_monitor';\n\nconst LOG_TAG = 'ConnectivityMonitor';\n\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nexport class BrowserConnectivityMonitor implements ConnectivityMonitor {\n private readonly networkAvailableListener = (): void =>\n this.onNetworkAvailable();\n private readonly networkUnavailableListener = (): void =>\n this.onNetworkUnavailable();\n private callbacks: ConnectivityMonitorCallback[] = [];\n\n constructor() {\n this.configureNetworkMonitoring();\n }\n\n addCallback(callback: (status: NetworkStatus) => void): void {\n this.callbacks.push(callback);\n }\n\n shutdown(): void {\n window.removeEventListener('online', this.networkAvailableListener);\n window.removeEventListener('offline', this.networkUnavailableListener);\n }\n\n private configureNetworkMonitoring(): void {\n window.addEventListener('online', this.networkAvailableListener);\n window.addEventListener('offline', this.networkUnavailableListener);\n }\n\n private onNetworkAvailable(): void {\n debug(LOG_TAG, 'Network connectivity changed: AVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.AVAILABLE);\n }\n }\n\n private onNetworkUnavailable(): void {\n debug(LOG_TAG, 'Network connectivity changed: UNAVAILABLE');\n for (const callback of this.callbacks) {\n callback(NetworkStatus.UNAVAILABLE);\n }\n }\n\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static isAvailable(): boolean {\n return (\n typeof window !== 'undefined' &&\n window.addEventListener !== undefined &&\n window.removeEventListener !== undefined\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '../util/assert';\nimport { FirestoreError } from '../util/error';\n\nimport { Stream } from './connection';\n\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nexport class StreamBridge<I, O> implements Stream<I, O> {\n private wrappedOnOpen: (() => void) | undefined;\n private wrappedOnClose: ((err?: FirestoreError) => void) | undefined;\n private wrappedOnMessage: ((msg: O) => void) | undefined;\n\n private sendFn: (msg: I) => void;\n private closeFn: () => void;\n\n constructor(args: { sendFn: (msg: I) => void; closeFn: () => void }) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n\n onOpen(callback: () => void): void {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n }\n\n onClose(callback: (err?: FirestoreError) => void): void {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n }\n\n onMessage(callback: (msg: O) => void): void {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n }\n\n close(): void {\n this.closeFn();\n }\n\n send(msg: I): void {\n this.sendFn(msg);\n }\n\n callOnOpen(): void {\n assert(\n this.wrappedOnOpen !== undefined,\n 'Cannot call onOpen because no callback was set'\n );\n this.wrappedOnOpen();\n }\n\n callOnClose(err?: FirestoreError): void {\n assert(\n this.wrappedOnClose !== undefined,\n 'Cannot call onClose because no callback was set'\n );\n this.wrappedOnClose(err);\n }\n\n callOnMessage(msg: O): void {\n assert(\n this.wrappedOnMessage !== undefined,\n 'Cannot call onMessage because no callback was set'\n );\n this.wrappedOnMessage(msg);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 createWebChannelTransport,\n ErrorCode,\n EventType,\n WebChannel,\n WebChannelError,\n WebChannelOptions,\n XhrIo\n} from '@firebase/webchannel-wrapper';\n\nimport {\n isBrowserExtension,\n isElectron,\n isIE,\n isMobileCordova,\n isReactNative,\n isUWP\n} from '@firebase/util';\n\nimport { Token } from '../api/credentials';\nimport { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { SDK_VERSION } from '../core/version';\nimport { Connection, Stream } from '../remote/connection';\nimport {\n mapCodeFromRpcStatus,\n mapCodeFromHttpResponseErrorStatus\n} from '../remote/rpc_error';\nimport { StreamBridge } from '../remote/stream_bridge';\nimport { assert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport * as log from '../util/log';\nimport { Indexable } from '../util/misc';\nimport { Rejecter, Resolver } from '../util/promise';\nimport { StringMap } from '../util/types';\n\nconst LOG_TAG = 'Connection';\n\nconst RPC_STREAM_SERVICE = 'google.firestore.v1.Firestore';\nconst RPC_URL_VERSION = 'v1';\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n * Uses Object Literal notation to avoid renaming.\n */\nconst RPC_NAME_REST_MAPPING: { [key: string]: string } = {};\nRPC_NAME_REST_MAPPING['BatchGetDocuments'] = 'batchGet';\nRPC_NAME_REST_MAPPING['Commit'] = 'commit';\n\n// TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\nconst X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\n\nconst XHR_TIMEOUT_SECS = 15;\n\nexport class WebChannelConnection implements Connection {\n private readonly databaseId: DatabaseId;\n private readonly baseUrl: string;\n private readonly forceLongPolling: boolean;\n\n constructor(info: DatabaseInfo) {\n this.databaseId = info.databaseId;\n const proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n this.forceLongPolling = info.forceLongPolling;\n }\n\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */\n private modifyHeadersForRequest(\n headers: StringMap,\n token: Token | null\n ): void {\n if (token) {\n for (const header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n }\n\n invokeRPC<Req, Resp>(\n rpcName: string,\n request: Req,\n token: Token | null\n ): Promise<Resp> {\n const url = this.makeUrl(rpcName);\n\n return new Promise((resolve: Resolver<Resp>, reject: Rejecter) => {\n const xhr = new XhrIo();\n xhr.listenOnce(EventType.COMPLETE, () => {\n try {\n switch (xhr.getLastErrorCode()) {\n case ErrorCode.NO_ERROR:\n const json = xhr.getResponseJson() as Resp;\n log.debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n case ErrorCode.TIMEOUT:\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\n reject(\n new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out')\n );\n break;\n case ErrorCode.HTTP_ERROR:\n const status = xhr.getStatus();\n log.debug(\n LOG_TAG,\n 'RPC \"' + rpcName + '\" failed with status:',\n status,\n 'response text:',\n xhr.getResponseText()\n );\n if (status > 0) {\n const responseError = (xhr.getResponseJson() as WebChannelError)\n .error;\n if (\n !!responseError &&\n !!responseError.status &&\n !!responseError.message\n ) {\n const firestoreErrorCode = mapCodeFromHttpResponseErrorStatus(\n responseError.status\n );\n reject(\n new FirestoreError(\n firestoreErrorCode,\n responseError.message\n )\n );\n } else {\n reject(\n new FirestoreError(\n Code.UNKNOWN,\n 'Server responded with status ' + xhr.getStatus()\n )\n );\n }\n } else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\n reject(\n new FirestoreError(Code.UNAVAILABLE, 'Connection failed.')\n );\n }\n break;\n default:\n fail(\n 'RPC \"' +\n rpcName +\n '\" failed with unanticipated ' +\n 'webchannel error ' +\n xhr.getLastErrorCode() +\n ': ' +\n xhr.getLastError() +\n ', giving up.'\n );\n }\n } finally {\n log.debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n }\n });\n\n // The database field is already encoded in URL. Specifying it again in\n // the body is not necessary in production, and will cause duplicate field\n // errors in the Firestore Emulator. Let's remove it.\n const jsonObj = ({ ...request } as unknown) as Indexable;\n delete jsonObj.database;\n\n const requestString = JSON.stringify(jsonObj);\n log.debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString);\n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n const headers: StringMap = { 'Content-Type': 'text/plain' };\n\n this.modifyHeadersForRequest(headers, token);\n\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n }\n\n invokeStreamingRPC<Req, Resp>(\n rpcName: string,\n request: Req,\n token: Token | null\n ): Promise<Resp[]> {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.invokeRPC<Req, Resp[]>(rpcName, request, token);\n }\n\n openStream<Req, Resp>(\n rpcName: string,\n token: Token | null\n ): Stream<Req, Resp> {\n const urlParts = [\n this.baseUrl,\n '/',\n RPC_STREAM_SERVICE,\n '/',\n rpcName,\n '/channel'\n ];\n const webchannelTransport = createWebChannelTransport();\n const request: WebChannelOptions = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: 'gsessionid',\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: true,\n supportsCrossDomainXhr: true,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 10 * 60 * 1000\n },\n forceLongPolling: this.forceLongPolling\n };\n\n this.modifyHeadersForRequest(request.initMessageHeaders!, token);\n\n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n //\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the httpHeadersOverwriteParam option to specify that\n // the headers should instead be encoded into a special \"$httpHeaders\" query\n // parameter, which is recognized by the webchannel backend. This is\n // formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32\n //\n // TODO(b/145624756): There is a backend bug where $httpHeaders isn't respected if the request\n // doesn't have an Origin header. So we have to exclude a few browser environments that are\n // known to (sometimes) not include an Origin. See\n // https://github.com/firebase/firebase-js-sdk/issues/1491.\n if (\n !isMobileCordova() &&\n !isReactNative() &&\n !isElectron() &&\n !isIE() &&\n !isUWP() &&\n !isBrowserExtension()\n ) {\n request.httpHeadersOverwriteParam = '$httpHeaders';\n }\n\n const url = urlParts.join('');\n log.debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request);\n const channel = webchannelTransport.createWebChannel(url, request);\n\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let opened = false;\n\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n let closed = false;\n\n const streamBridge = new StreamBridge<Req, Resp>({\n sendFn: (msg: Req) => {\n if (!closed) {\n if (!opened) {\n log.debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n log.debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n } else {\n log.debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: () => channel.close()\n });\n\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n const unguardedEventListen = <T>(\n type: string,\n fn: (param?: T) => void\n ): void => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, (param: unknown) => {\n try {\n fn(param as T);\n } catch (e) {\n setTimeout(() => {\n throw e;\n }, 0);\n }\n });\n };\n\n unguardedEventListen(WebChannel.EventType.OPEN, () => {\n if (!closed) {\n log.debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n\n unguardedEventListen(WebChannel.EventType.CLOSE, () => {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n\n unguardedEventListen<Error>(WebChannel.EventType.ERROR, err => {\n if (!closed) {\n closed = true;\n log.debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(\n new FirestoreError(\n Code.UNAVAILABLE,\n 'The operation could not be completed'\n )\n );\n }\n });\n\n // WebChannel delivers message events as array. If batching is not enabled\n // (it's off by default) each message will be delivered alone, resulting in\n // a single element array.\n interface WebChannelResponse {\n data: Resp[];\n }\n\n unguardedEventListen<WebChannelResponse>(\n WebChannel.EventType.MESSAGE,\n msg => {\n if (!closed) {\n const msgData = msg!.data[0];\n assert(!!msgData, 'Got a webchannel message without data.');\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const msgDataOrError: WebChannelError | object = msgData;\n const error =\n msgDataOrError.error ||\n (msgDataOrError as WebChannelError[])[0]?.error;\n if (error) {\n log.debug(LOG_TAG, 'WebChannel received error:', error);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const status: string = error.status;\n let code = mapCodeFromRpcStatus(status);\n let message = error.message;\n if (code === undefined) {\n code = Code.INTERNAL;\n message =\n 'Unknown error status: ' +\n status +\n ' with message ' +\n error.message;\n }\n // Mark closed so no further events are propagated\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n } else {\n log.debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n }\n );\n\n setTimeout(() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n streamBridge.callOnOpen();\n }, 0);\n return streamBridge;\n }\n\n // visible for testing\n makeUrl(rpcName: string): string {\n const urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\n return (\n this.baseUrl +\n '/' +\n RPC_URL_VERSION +\n '/projects/' +\n this.databaseId.projectId +\n '/databases/' +\n this.databaseId.database +\n '/documents:' +\n urlRpcName\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { Platform } from '../platform/platform';\nimport { Connection } from '../remote/connection';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { ConnectivityMonitor } from './../remote/connectivity_monitor';\n\nimport { NoopConnectivityMonitor } from '../remote/connectivity_monitor_noop';\nimport { BrowserConnectivityMonitor } from './browser_connectivity_monitor';\nimport { WebChannelConnection } from './webchannel_connection';\n\nexport class BrowserPlatform implements Platform {\n readonly base64Available: boolean;\n\n constructor() {\n this.base64Available = typeof atob !== 'undefined';\n }\n\n get document(): Document | null {\n return typeof document !== 'undefined' ? document : null;\n }\n\n get window(): Window | null {\n return typeof window !== 'undefined' ? window : null;\n }\n\n loadConnection(databaseInfo: DatabaseInfo): Promise<Connection> {\n return Promise.resolve(new WebChannelConnection(databaseInfo));\n }\n\n newConnectivityMonitor(): ConnectivityMonitor {\n if (BrowserConnectivityMonitor.isAvailable()) {\n return new BrowserConnectivityMonitor();\n } else {\n return new NoopConnectivityMonitor();\n }\n }\n\n newSerializer(databaseId: DatabaseId): JsonProtoSerializer {\n return new JsonProtoSerializer(databaseId, { useProto3Json: true });\n }\n\n formatJSON(value: unknown): string {\n return JSON.stringify(value);\n }\n\n atob(encoded: string): string {\n return atob(encoded);\n }\n\n btoa(raw: string): string {\n return btoa(raw);\n }\n\n randomBytes(nBytes: number): Uint8Array {\n if (nBytes <= 0) {\n return new Uint8Array();\n }\n\n const v = new Uint8Array(nBytes);\n crypto.getRandomValues(v);\n return v;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { PlatformSupport } from '../platform/platform';\nimport { BrowserPlatform } from './browser_platform';\n\n/**\n * This code needs to run before Firestore is used. This can be achieved in\n * several ways:\n * 1) Through the JSCompiler compiling this code and then (automatically)\n * executing it before exporting the Firestore symbols.\n * 2) Through importing this module first in a Firestore main module\n */\nPlatformSupport.setPlatform(new BrowserPlatform());\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { HttpsError, FunctionsErrorCode } from '@firebase/functions-types';\nimport { Serializer } from '../serializer';\nimport { HttpResponseBody } from './service';\n\n/**\n * Standard error codes for different ways a request can fail, as defined by:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * This map is used primarily to convert from a backend error code string to\n * a client SDK error code string, and make sure it's in the supported set.\n */\nconst errorCodeMap: { [name: string]: FunctionsErrorCode } = {\n OK: 'ok',\n CANCELLED: 'cancelled',\n UNKNOWN: 'unknown',\n INVALID_ARGUMENT: 'invalid-argument',\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n NOT_FOUND: 'not-found',\n ALREADY_EXISTS: 'already-exists',\n PERMISSION_DENIED: 'permission-denied',\n UNAUTHENTICATED: 'unauthenticated',\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n FAILED_PRECONDITION: 'failed-precondition',\n ABORTED: 'aborted',\n OUT_OF_RANGE: 'out-of-range',\n UNIMPLEMENTED: 'unimplemented',\n INTERNAL: 'internal',\n UNAVAILABLE: 'unavailable',\n DATA_LOSS: 'data-loss'\n};\n\n/**\n * An explicit error that can be thrown from a handler to send an error to the\n * client that called the function.\n */\nexport class HttpsErrorImpl extends Error implements HttpsError {\n /**\n * A standard error code that will be returned to the client. This also\n * determines the HTTP status code of the response, as defined in code.proto.\n */\n readonly code: FunctionsErrorCode;\n\n /**\n * Extra data to be converted to JSON and included in the error response.\n */\n readonly details?: unknown;\n\n constructor(code: FunctionsErrorCode, message?: string, details?: unknown) {\n super(message);\n\n // This is a workaround for a bug in TypeScript when extending Error:\n // tslint:disable-next-line\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, HttpsErrorImpl.prototype);\n\n this.code = code;\n this.details = details;\n }\n}\n\n/**\n * Takes an HTTP status code and returns the corresponding ErrorCode.\n * This is the standard HTTP status code -> error mapping defined in:\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\n *\n * @param status An HTTP status code.\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\n */\nfunction codeForHTTPStatus(status: number): FunctionsErrorCode {\n // Make sure any successful status is OK.\n if (status >= 200 && status < 300) {\n return 'ok';\n }\n switch (status) {\n case 0:\n // This can happen if the server returns 500.\n return 'internal';\n case 400:\n return 'invalid-argument';\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission-denied';\n case 404:\n return 'not-found';\n case 409:\n return 'aborted';\n case 429:\n return 'resource-exhausted';\n case 499:\n return 'cancelled';\n case 500:\n return 'internal';\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline-exceeded';\n default: // ignore\n }\n return 'unknown';\n}\n\n/**\n * Takes an HTTP response and returns the corresponding Error, if any.\n */\nexport function _errorForResponse(\n status: number,\n bodyJSON: HttpResponseBody | null,\n serializer: Serializer\n): Error | null {\n let code = codeForHTTPStatus(status);\n\n // Start with reasonable defaults from the status code.\n let description: string = code;\n\n let details: unknown = undefined;\n\n // Then look through the body for explicit details.\n try {\n const errorJSON = bodyJSON && bodyJSON.error;\n if (errorJSON) {\n const status = errorJSON.status;\n if (typeof status === 'string') {\n if (!errorCodeMap[status]) {\n // They must've included an unknown error code in the body.\n return new HttpsErrorImpl('internal', 'internal');\n }\n code = errorCodeMap[status];\n\n // TODO(klimt): Add better default descriptions for error enums.\n // The default description needs to be updated for the new code.\n description = status;\n }\n\n const message = errorJSON.message;\n if (typeof message === 'string') {\n description = message;\n }\n\n details = errorJSON.details;\n if (details !== undefined) {\n details = serializer.decode(details as {} | null);\n }\n }\n } catch (e) {\n // If we couldn't parse explicit error data, that's fine.\n }\n\n if (code === 'ok') {\n // Technically, there's an edge case where a developer could explicitly\n // return an error code of OK, and we will treat it as success, but that\n // seems reasonable.\n return null;\n }\n\n return new HttpsErrorImpl(code, description, details);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { _FirebaseApp } from '@firebase/app-types/private';\nimport {\n FirebaseMessaging,\n FirebaseMessagingName\n} from '@firebase/messaging-types';\nimport {\n FirebaseAuthInternal,\n FirebaseAuthInternalName\n} from '@firebase/auth-interop-types';\nimport { Provider } from '@firebase/component';\n\n/**\n * The metadata that should be supplied with function calls.\n */\nexport interface Context {\n authToken?: string;\n instanceIdToken?: string;\n}\n\n/**\n * Helper class to get metadata that should be included with a function call.\n */\nexport class ContextProvider {\n private auth: FirebaseAuthInternal | null = null;\n private messaging: FirebaseMessaging | null = null;\n constructor(\n authProvider: Provider<FirebaseAuthInternalName>,\n messagingProvider: Provider<FirebaseMessagingName>\n ) {\n this.auth = authProvider.getImmediate({ optional: true });\n this.messaging = messagingProvider.getImmediate({\n optional: true\n });\n\n if (!this.auth) {\n authProvider.get().then(\n auth => (this.auth = auth),\n () => {\n /* get() never rejects */\n }\n );\n }\n\n if (!this.messaging) {\n messagingProvider.get().then(\n messaging => (this.messaging = messaging),\n () => {\n /* get() never rejects */\n }\n );\n }\n }\n\n async getAuthToken(): Promise<string | undefined> {\n if (!this.auth) {\n return undefined;\n }\n\n try {\n const token = await this.auth.getToken();\n if (!token) {\n return undefined;\n }\n return token.accessToken;\n } catch (e) {\n // If there's any error when trying to get the auth token, leave it off.\n return undefined;\n }\n }\n\n async getInstanceIdToken(): Promise<string | undefined> {\n if (\n !this.messaging ||\n !('Notification' in self) ||\n Notification.permission !== 'granted'\n ) {\n return undefined;\n }\n\n try {\n return this.messaging.getToken();\n } catch (e) {\n // We don't warn on this, because it usually means messaging isn't set up.\n // console.warn('Failed to retrieve instance id token.', e);\n\n // If there's any error when trying to get the token, leave it off.\n return undefined;\n }\n }\n\n async getContext(): Promise<Context> {\n const authToken = await this.getAuthToken();\n const instanceIdToken = await this.getInstanceIdToken();\n return { authToken, instanceIdToken };\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\nconst LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\nconst UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\n\nfunction mapValues(\n // { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n o: { [key: string]: any },\n f: (arg0: unknown) => unknown\n): object {\n const result: { [key: string]: unknown } = {};\n for (const key in o) {\n if (o.hasOwnProperty(key)) {\n result[key] = f(o[key]);\n }\n }\n return result;\n}\n\nexport class Serializer {\n // Takes data and encodes it in a JSON-friendly way, such that types such as\n // Date are preserved.\n encode(data: unknown): unknown {\n if (data == null) {\n return null;\n }\n if (data instanceof Number) {\n data = data.valueOf();\n }\n if (typeof data === 'number' && isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n if (data === true || data === false) {\n return data;\n }\n if (Object.prototype.toString.call(data) === '[object String]') {\n return data;\n }\n if (Array.isArray(data)) {\n return data.map(x => this.encode(x));\n }\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data as object, x => this.encode(x));\n }\n // If we got this far, the data is not encodable.\n throw new Error('Data cannot be encoded in JSON: ' + data);\n }\n\n // Takes data that's been encoded in a JSON-friendly form and returns a form\n // with richer datatypes, such as Dates, etc.\n decode(json: unknown): unknown {\n if (json == null) {\n return json;\n }\n if ((json as { [key: string]: unknown })['@type']) {\n switch ((json as { [key: string]: unknown })['@type']) {\n case LONG_TYPE:\n // Fall through and handle this the same as unsigned.\n case UNSIGNED_LONG_TYPE: {\n // Technically, this could work return a valid number for malformed\n // data if there was a number followed by garbage. But it's just not\n // worth all the extra code to detect that case.\n const value = Number((json as { [key: string]: unknown })['value']);\n if (isNaN(value)) {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n return value;\n }\n default: {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n }\n }\n if (Array.isArray(json)) {\n return json.map(x => this.decode(x));\n }\n if (typeof json === 'function' || typeof json === 'object') {\n return mapValues(json as object, x => this.decode(x as {} | null));\n }\n // Anything else is safe to return.\n return json;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app-types';\nimport { FirebaseService } from '@firebase/app-types/private';\nimport {\n FirebaseFunctions,\n HttpsCallable,\n HttpsCallableResult,\n HttpsCallableOptions\n} from '@firebase/functions-types';\nimport { _errorForResponse, HttpsErrorImpl } from './error';\nimport { ContextProvider } from '../context';\nimport { Serializer } from '../serializer';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\nimport { FirebaseMessagingName } from '@firebase/messaging-types';\n\n/**\n * The response to an http request.\n */\ninterface HttpResponse {\n status: number;\n json: HttpResponseBody | null;\n}\n/**\n * Describes the shape of the HttpResponse body.\n * It makes functions that would otherwise take {} able to access the\n * possible elements in the body more easily\n */\nexport interface HttpResponseBody {\n data?: unknown;\n result?: unknown;\n error?: {\n message?: unknown;\n status?: unknown;\n details?: unknown;\n };\n}\n\n/**\n * Returns a Promise that will be rejected after the given duration.\n * The error will be of type HttpsErrorImpl.\n *\n * @param millis Number of milliseconds to wait before rejecting.\n */\nfunction failAfter(millis: number): Promise<never> {\n return new Promise((_, reject) => {\n setTimeout(() => {\n reject(new HttpsErrorImpl('deadline-exceeded', 'deadline-exceeded'));\n }, millis);\n });\n}\n\n/**\n * The main class for the Firebase Functions SDK.\n */\nexport class Service implements FirebaseFunctions, FirebaseService {\n private readonly contextProvider: ContextProvider;\n private readonly serializer = new Serializer();\n private emulatorOrigin: string | null = null;\n private cancelAllRequests: Promise<void>;\n private deleteService!: Function;\n\n /**\n * Creates a new Functions service for the given app and (optional) region.\n * @param app_ The FirebaseApp to use.\n * @param region_ The region to call functions in.\n */\n constructor(\n private app_: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n messagingProvider: Provider<FirebaseMessagingName>,\n private region_: string = 'us-central1'\n ) {\n this.contextProvider = new ContextProvider(authProvider, messagingProvider);\n // Cancels all ongoing requests when resolved.\n this.cancelAllRequests = new Promise(resolve => {\n this.deleteService = () => {\n return resolve();\n };\n });\n }\n\n get app(): FirebaseApp {\n return this.app_;\n }\n\n INTERNAL = {\n delete: (): Promise<void> => {\n return this.deleteService();\n }\n };\n\n /**\n * Returns the URL for a callable with the given name.\n * @param name The name of the callable.\n */\n _url(name: string): string {\n const projectId = this.app_.options.projectId;\n const region = this.region_;\n if (this.emulatorOrigin !== null) {\n const origin = this.emulatorOrigin;\n return `${origin}/${projectId}/${region}/${name}`;\n }\n return `https://${region}-${projectId}.cloudfunctions.net/${name}`;\n }\n\n /**\n * Changes this instance to point to a Cloud Functions emulator running\n * locally. See https://firebase.google.com/docs/functions/local-emulator\n *\n * @param origin The origin of the local emulator, such as\n * \"http://localhost:5005\".\n */\n useFunctionsEmulator(origin: string): void {\n this.emulatorOrigin = origin;\n }\n\n /**\n * Returns a reference to the callable https trigger with the given name.\n * @param name The name of the trigger.\n */\n httpsCallable(name: string, options?: HttpsCallableOptions): HttpsCallable {\n return data => {\n return this.call(name, data, options || {});\n };\n }\n\n /**\n * Does an HTTP POST and returns the completed response.\n * @param url The url to post to.\n * @param body The JSON body of the post.\n * @param headers The HTTP headers to include in the request.\n * @return A Promise that will succeed when the request finishes.\n */\n private async postJSON(\n url: string,\n body: {},\n headers: Headers\n ): Promise<HttpResponse> {\n headers.append('Content-Type', 'application/json');\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers\n });\n } catch (e) {\n // This could be an unhandled error on the backend, or it could be a\n // network error. There's no way to know, since an unhandled error on the\n // backend will fail to set the proper CORS header, and thus will be\n // treated as a network error by fetch.\n return {\n status: 0,\n json: null\n };\n }\n let json: {} | null = null;\n try {\n json = await response.json();\n } catch (e) {\n // If we fail to parse JSON, it will fail the same as an empty body.\n }\n return {\n status: response.status,\n json\n };\n }\n\n /**\n * Calls a callable function asynchronously and returns the result.\n * @param name The name of the callable trigger.\n * @param data The data to pass as params to the function.s\n */\n private async call(\n name: string,\n data: unknown,\n options: HttpsCallableOptions\n ): Promise<HttpsCallableResult> {\n const url = this._url(name);\n\n // Encode any special types, such as dates, in the input data.\n data = this.serializer.encode(data);\n const body = { data };\n\n // Add a header for the authToken.\n const headers = new Headers();\n const context = await this.contextProvider.getContext();\n if (context.authToken) {\n headers.append('Authorization', 'Bearer ' + context.authToken);\n }\n if (context.instanceIdToken) {\n headers.append('Firebase-Instance-ID-Token', context.instanceIdToken);\n }\n\n // Default timeout to 70s, but let the options override it.\n const timeout = options.timeout || 70000;\n\n const response = await Promise.race([\n this.postJSON(url, body, headers),\n failAfter(timeout),\n this.cancelAllRequests\n ]);\n\n // If service was deleted, interrupted response throws an error.\n if (!response) {\n throw new HttpsErrorImpl(\n 'cancelled',\n 'Firebase Functions instance was deleted.'\n );\n }\n\n // Check for an error status, regardless of http status.\n const error = _errorForResponse(\n response.status,\n response.json,\n this.serializer\n );\n if (error) {\n throw error;\n }\n\n if (!response.json) {\n throw new HttpsErrorImpl(\n 'internal',\n 'Response is not valid JSON object.'\n );\n }\n\n let responseData = response.json.data;\n // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\n // backwards compatibility.\n if (typeof responseData === 'undefined') {\n responseData = response.json.result;\n }\n if (typeof responseData === 'undefined') {\n // Consider the response malformed.\n throw new HttpsErrorImpl('internal', 'Response is missing data field.');\n }\n\n // Decode any special types, such as dates, in the returned data.\n const decodedData = this.serializer.decode(responseData as {} | null);\n\n return { data: decodedData };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Service } from './api/service';\nimport {\n Component,\n ComponentType,\n ComponentContainer\n} from '@firebase/component';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\n\n/**\n * Type constant for Firebase Functions.\n */\nconst FUNCTIONS_TYPE = 'functions';\n\nfunction factory(container: ComponentContainer, region?: string): Service {\n // Dependencies\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider('auth-internal');\n const messagingProvider = container.getProvider('messaging');\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new Service(app, authProvider, messagingProvider, region);\n}\n\nexport function registerFunctions(instance: _FirebaseNamespace): void {\n const namespaceExports = {\n // no-inline\n Functions: Service\n };\n instance.INTERNAL.registerComponent(\n new Component(FUNCTIONS_TYPE, factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n}\n","function toArray(arr) {\n return Array.prototype.slice.call(arr);\n}\n\nfunction promisifyRequest(request) {\n return new Promise(function(resolve, reject) {\n request.onsuccess = function() {\n resolve(request.result);\n };\n\n request.onerror = function() {\n reject(request.error);\n };\n });\n}\n\nfunction promisifyRequestCall(obj, method, args) {\n var request;\n var p = new Promise(function(resolve, reject) {\n request = obj[method].apply(obj, args);\n promisifyRequest(request).then(resolve, reject);\n });\n\n p.request = request;\n return p;\n}\n\nfunction promisifyCursorRequestCall(obj, method, args) {\n var p = promisifyRequestCall(obj, method, args);\n return p.then(function(value) {\n if (!value) return;\n return new Cursor(value, p.request);\n });\n}\n\nfunction proxyProperties(ProxyClass, targetProp, properties) {\n properties.forEach(function(prop) {\n Object.defineProperty(ProxyClass.prototype, prop, {\n get: function() {\n return this[targetProp][prop];\n },\n set: function(val) {\n this[targetProp][prop] = val;\n }\n });\n });\n}\n\nfunction proxyRequestMethods(ProxyClass, targetProp, Constructor, properties) {\n properties.forEach(function(prop) {\n if (!(prop in Constructor.prototype)) return;\n ProxyClass.prototype[prop] = function() {\n return promisifyRequestCall(this[targetProp], prop, arguments);\n };\n });\n}\n\nfunction proxyMethods(ProxyClass, targetProp, Constructor, properties) {\n properties.forEach(function(prop) {\n if (!(prop in Constructor.prototype)) return;\n ProxyClass.prototype[prop] = function() {\n return this[targetProp][prop].apply(this[targetProp], arguments);\n };\n });\n}\n\nfunction proxyCursorRequestMethods(ProxyClass, targetProp, Constructor, properties) {\n properties.forEach(function(prop) {\n if (!(prop in Constructor.prototype)) return;\n ProxyClass.prototype[prop] = function() {\n return promisifyCursorRequestCall(this[targetProp], prop, arguments);\n };\n });\n}\n\nfunction Index(index) {\n this._index = index;\n}\n\nproxyProperties(Index, '_index', [\n 'name',\n 'keyPath',\n 'multiEntry',\n 'unique'\n]);\n\nproxyRequestMethods(Index, '_index', IDBIndex, [\n 'get',\n 'getKey',\n 'getAll',\n 'getAllKeys',\n 'count'\n]);\n\nproxyCursorRequestMethods(Index, '_index', IDBIndex, [\n 'openCursor',\n 'openKeyCursor'\n]);\n\nfunction Cursor(cursor, request) {\n this._cursor = cursor;\n this._request = request;\n}\n\nproxyProperties(Cursor, '_cursor', [\n 'direction',\n 'key',\n 'primaryKey',\n 'value'\n]);\n\nproxyRequestMethods(Cursor, '_cursor', IDBCursor, [\n 'update',\n 'delete'\n]);\n\n// proxy 'next' methods\n['advance', 'continue', 'continuePrimaryKey'].forEach(function(methodName) {\n if (!(methodName in IDBCursor.prototype)) return;\n Cursor.prototype[methodName] = function() {\n var cursor = this;\n var args = arguments;\n return Promise.resolve().then(function() {\n cursor._cursor[methodName].apply(cursor._cursor, args);\n return promisifyRequest(cursor._request).then(function(value) {\n if (!value) return;\n return new Cursor(value, cursor._request);\n });\n });\n };\n});\n\nfunction ObjectStore(store) {\n this._store = store;\n}\n\nObjectStore.prototype.createIndex = function() {\n return new Index(this._store.createIndex.apply(this._store, arguments));\n};\n\nObjectStore.prototype.index = function() {\n return new Index(this._store.index.apply(this._store, arguments));\n};\n\nproxyProperties(ObjectStore, '_store', [\n 'name',\n 'keyPath',\n 'indexNames',\n 'autoIncrement'\n]);\n\nproxyRequestMethods(ObjectStore, '_store', IDBObjectStore, [\n 'put',\n 'add',\n 'delete',\n 'clear',\n 'get',\n 'getAll',\n 'getKey',\n 'getAllKeys',\n 'count'\n]);\n\nproxyCursorRequestMethods(ObjectStore, '_store', IDBObjectStore, [\n 'openCursor',\n 'openKeyCursor'\n]);\n\nproxyMethods(ObjectStore, '_store', IDBObjectStore, [\n 'deleteIndex'\n]);\n\nfunction Transaction(idbTransaction) {\n this._tx = idbTransaction;\n this.complete = new Promise(function(resolve, reject) {\n idbTransaction.oncomplete = function() {\n resolve();\n };\n idbTransaction.onerror = function() {\n reject(idbTransaction.error);\n };\n idbTransaction.onabort = function() {\n reject(idbTransaction.error);\n };\n });\n}\n\nTransaction.prototype.objectStore = function() {\n return new ObjectStore(this._tx.objectStore.apply(this._tx, arguments));\n};\n\nproxyProperties(Transaction, '_tx', [\n 'objectStoreNames',\n 'mode'\n]);\n\nproxyMethods(Transaction, '_tx', IDBTransaction, [\n 'abort'\n]);\n\nfunction UpgradeDB(db, oldVersion, transaction) {\n this._db = db;\n this.oldVersion = oldVersion;\n this.transaction = new Transaction(transaction);\n}\n\nUpgradeDB.prototype.createObjectStore = function() {\n return new ObjectStore(this._db.createObjectStore.apply(this._db, arguments));\n};\n\nproxyProperties(UpgradeDB, '_db', [\n 'name',\n 'version',\n 'objectStoreNames'\n]);\n\nproxyMethods(UpgradeDB, '_db', IDBDatabase, [\n 'deleteObjectStore',\n 'close'\n]);\n\nfunction DB(db) {\n this._db = db;\n}\n\nDB.prototype.transaction = function() {\n return new Transaction(this._db.transaction.apply(this._db, arguments));\n};\n\nproxyProperties(DB, '_db', [\n 'name',\n 'version',\n 'objectStoreNames'\n]);\n\nproxyMethods(DB, '_db', IDBDatabase, [\n 'close'\n]);\n\n// Add cursor iterators\n// TODO: remove this once browsers do the right thing with promises\n['openCursor', 'openKeyCursor'].forEach(function(funcName) {\n [ObjectStore, Index].forEach(function(Constructor) {\n // Don't create iterateKeyCursor if openKeyCursor doesn't exist.\n if (!(funcName in Constructor.prototype)) return;\n\n Constructor.prototype[funcName.replace('open', 'iterate')] = function() {\n var args = toArray(arguments);\n var callback = args[args.length - 1];\n var nativeObject = this._store || this._index;\n var request = nativeObject[funcName].apply(nativeObject, args.slice(0, -1));\n request.onsuccess = function() {\n callback(request.result);\n };\n };\n });\n});\n\n// polyfill getAll\n[Index, ObjectStore].forEach(function(Constructor) {\n if (Constructor.prototype.getAll) return;\n Constructor.prototype.getAll = function(query, count) {\n var instance = this;\n var items = [];\n\n return new Promise(function(resolve) {\n instance.iterateCursor(query, function(cursor) {\n if (!cursor) {\n resolve(items);\n return;\n }\n items.push(cursor.value);\n\n if (count !== undefined && items.length == count) {\n resolve(items);\n return;\n }\n cursor.continue();\n });\n });\n };\n});\n\nexport function openDb(name, version, upgradeCallback) {\n var p = promisifyRequestCall(indexedDB, 'open', [name, version]);\n var request = p.request;\n\n if (request) {\n request.onupgradeneeded = function(event) {\n if (upgradeCallback) {\n upgradeCallback(new UpgradeDB(request.result, event.oldVersion, request.transaction));\n }\n };\n }\n\n return p.then(function(db) {\n return new DB(db);\n });\n}\n\nexport function deleteDb(name) {\n return promisifyRequestCall(indexedDB, 'deleteDatabase', [name]);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 firebase from '@firebase/app';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport * as types from '@firebase/functions-types';\nimport { registerFunctions } from './src/config';\n\nimport { name, version } from './package.json';\n\nregisterFunctions(firebase as _FirebaseNamespace);\nfirebase.registerVersion(name, version);\n\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n functions?: {\n (app?: FirebaseApp): types.FirebaseFunctions;\n Functions: typeof types.FirebaseFunctions;\n };\n }\n interface FirebaseApp {\n functions?(region?: string): types.FirebaseFunctions;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { version } from '../../package.json';\n\nexport const PENDING_TIMEOUT_MS = 10000;\n\nexport const PACKAGE_VERSION = `w:${version}`;\nexport const INTERNAL_AUTH_VERSION = 'FIS_v2';\n\nexport const INSTALLATIONS_API_URL =\n 'https://firebaseinstallations.googleapis.com/v1';\n\nexport const TOKEN_EXPIRATION_BUFFER = 60 * 60 * 1000; // One hour\n\nexport const SERVICE = 'installations';\nexport const SERVICE_NAME = 'Installations';\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ErrorFactory, FirebaseError } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from './constants';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n NOT_REGISTERED = 'not-registered',\n INSTALLATION_NOT_FOUND = 'installation-not-found',\n REQUEST_FAILED = 'request-failed',\n APP_OFFLINE = 'app-offline',\n DELETE_PENDING_REGISTRATION = 'delete-pending-registration'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.NOT_REGISTERED]: 'Firebase Installation is not registered.',\n [ErrorCode.INSTALLATION_NOT_FOUND]: 'Firebase Installation not found.',\n [ErrorCode.REQUEST_FAILED]:\n '{$requestName} request failed with error \"{$serverCode} {$serverStatus}: {$serverMessage}\"',\n [ErrorCode.APP_OFFLINE]: 'Could not process request. Application offline.',\n [ErrorCode.DELETE_PENDING_REGISTRATION]:\n \"Can't delete installation while there is a pending registration request.\"\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.REQUEST_FAILED]: {\n requestName: string;\n [index: string] : string | number; // to make Typescript 3.8 happy\n } & ServerErrorData;\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n\nexport interface ServerErrorData {\n serverCode: number;\n serverMessage: string;\n serverStatus: string;\n}\n\nexport type ServerError = FirebaseError & ServerErrorData;\n\n/** Returns true if error is a FirebaseError that is based on an error from the server. */\nexport function isServerError(error: unknown): error is ServerError {\n return (\n error instanceof FirebaseError &&\n error.code.includes(ErrorCode.REQUEST_FAILED)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FirebaseError } from '@firebase/util';\nimport { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport { AppConfig } from '../interfaces/app-config';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport {\n INSTALLATIONS_API_URL,\n INTERNAL_AUTH_VERSION\n} from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function getInstallationsEndpoint({ projectId }: AppConfig): string {\n return `${INSTALLATIONS_API_URL}/projects/${projectId}/installations`;\n}\n\nexport function extractAuthTokenInfoFromResponse(\n response: GenerateAuthTokenResponse\n): CompletedAuthToken {\n return {\n token: response.token,\n requestStatus: RequestStatus.COMPLETED,\n expiresIn: getExpiresInFromResponseExpiresIn(response.expiresIn),\n creationTime: Date.now()\n };\n}\n\nexport async function getErrorFromResponse(\n requestName: string,\n response: Response\n): Promise<FirebaseError> {\n const responseJson: ErrorResponse = await response.json();\n const errorData = responseJson.error;\n return ERROR_FACTORY.create(ErrorCode.REQUEST_FAILED, {\n requestName,\n serverCode: errorData.code,\n serverMessage: errorData.message,\n serverStatus: errorData.status\n });\n}\n\nexport function getHeaders({ apiKey }: AppConfig): Headers {\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': apiKey\n });\n}\n\nexport function getHeadersWithAuth(\n appConfig: AppConfig,\n { refreshToken }: RegisteredInstallationEntry\n): Headers {\n const headers = getHeaders(appConfig);\n headers.append('Authorization', getAuthorizationHeader(refreshToken));\n return headers;\n}\n\nexport interface ErrorResponse {\n error: {\n code: number;\n message: string;\n status: string;\n };\n}\n\n/**\n * Calls the passed in fetch wrapper and returns the response.\n * If the returned response has a status of 5xx, re-runs the function once and\n * returns the response.\n */\nexport async function retryIfServerError(\n fn: () => Promise<Response>\n): Promise<Response> {\n const result = await fn();\n\n if (result.status >= 500 && result.status < 600) {\n // Internal Server Error. Retry request.\n return fn();\n }\n\n return result;\n}\n\nfunction getExpiresInFromResponseExpiresIn(responseExpiresIn: string): number {\n // This works because the server will never respond with fractions of a second.\n return Number(responseExpiresIn.replace('s', '000'));\n}\n\nfunction getAuthorizationHeader(refreshToken: string): string {\n return `${INTERNAL_AUTH_VERSION} ${refreshToken}`;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { bufferToBase64UrlSafe } from './buffer-to-base64-url-safe';\n\nexport const VALID_FID_PATTERN = /^[cdef][\\w-]{21}$/;\nexport const INVALID_FID = '';\n\n/**\n * Generates a new FID using random values from Web Crypto API.\n * Returns an empty string if FID generation fails for any reason.\n */\nexport function generateFid(): string {\n try {\n // A valid FID has exactly 22 base64 characters, which is 132 bits, or 16.5\n // bytes. our implementation generates a 17 byte array instead.\n const fidByteArray = new Uint8Array(17);\n const crypto =\n self.crypto || ((self as unknown) as { msCrypto: Crypto }).msCrypto;\n crypto.getRandomValues(fidByteArray);\n\n // Replace the first 4 random bits with the constant FID header of 0b0111.\n fidByteArray[0] = 0b01110000 + (fidByteArray[0] % 0b00010000);\n\n const fid = encode(fidByteArray);\n\n return VALID_FID_PATTERN.test(fid) ? fid : INVALID_FID;\n } catch {\n // FID generation errored\n return INVALID_FID;\n }\n}\n\n/** Converts a FID Uint8Array to a base64 string representation. */\nfunction encode(fidByteArray: Uint8Array): string {\n const b64String = bufferToBase64UrlSafe(fidByteArray);\n\n // Remove the 23rd character that was added because of the extra 4 bits at the\n // end of our 17 byte array, and the '=' padding.\n return b64String.substr(0, 22);\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 function bufferToBase64UrlSafe(array: Uint8Array): string {\n const b64 = btoa(String.fromCharCode(...array));\n return b64.replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { AppConfig } from '../interfaces/app-config';\n\n/** Returns a string key that can be used to identify the app. */\nexport function getKey(appConfig: AppConfig): string {\n return `${appConfig.appName}!${appConfig.appId}`;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { getKey } from '../util/get-key';\nimport { AppConfig } from '../interfaces/app-config';\nimport { IdChangeCallbackFn } from '../functions';\n\nconst fidChangeCallbacks: Map<string, Set<IdChangeCallbackFn>> = new Map();\n\n/**\n * Calls the onIdChange callbacks with the new FID value, and broadcasts the\n * change to other tabs.\n */\nexport function fidChanged(appConfig: AppConfig, fid: string): void {\n const key = getKey(appConfig);\n\n callFidChangeCallbacks(key, fid);\n broadcastFidChange(key, fid);\n}\n\nexport function addCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n // Open the broadcast channel if it's not already open,\n // to be able to listen to change events from other tabs.\n getBroadcastChannel();\n\n const key = getKey(appConfig);\n\n let callbackSet = fidChangeCallbacks.get(key);\n if (!callbackSet) {\n callbackSet = new Set();\n fidChangeCallbacks.set(key, callbackSet);\n }\n callbackSet.add(callback);\n}\n\nexport function removeCallback(\n appConfig: AppConfig,\n callback: IdChangeCallbackFn\n): void {\n const key = getKey(appConfig);\n\n const callbackSet = fidChangeCallbacks.get(key);\n\n if (!callbackSet) {\n return;\n }\n\n callbackSet.delete(callback);\n if (callbackSet.size === 0) {\n fidChangeCallbacks.delete(key);\n }\n\n // Close broadcast channel if there are no more callbacks.\n closeBroadcastChannel();\n}\n\nfunction callFidChangeCallbacks(key: string, fid: string): void {\n const callbacks = fidChangeCallbacks.get(key);\n if (!callbacks) {\n return;\n }\n\n for (const callback of callbacks) {\n callback(fid);\n }\n}\n\nfunction broadcastFidChange(key: string, fid: string): void {\n const channel = getBroadcastChannel();\n if (channel) {\n channel.postMessage({ key, fid });\n }\n closeBroadcastChannel();\n}\n\nlet broadcastChannel: BroadcastChannel | null = null;\n/** Opens and returns a BroadcastChannel if it is supported by the browser. */\nfunction getBroadcastChannel(): BroadcastChannel | null {\n if (!broadcastChannel && 'BroadcastChannel' in self) {\n broadcastChannel = new BroadcastChannel('[Firebase] FID Change');\n broadcastChannel.onmessage = e => {\n callFidChangeCallbacks(e.data.key, e.data.fid);\n };\n }\n return broadcastChannel;\n}\n\nfunction closeBroadcastChannel(): void {\n if (fidChangeCallbacks.size === 0 && broadcastChannel) {\n broadcastChannel.close();\n broadcastChannel = null;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DB, openDb } from 'idb';\nimport { AppConfig } from '../interfaces/app-config';\nimport { InstallationEntry } from '../interfaces/installation-entry';\nimport { getKey } from '../util/get-key';\nimport { fidChanged } from './fid-changed';\n\nconst DATABASE_NAME = 'firebase-installations-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-installations-store';\n\nlet dbPromise: Promise<DB> | null = null;\nfunction getDbPromise(): Promise<DB> {\n if (!dbPromise) {\n dbPromise = openDb(DATABASE_NAME, DATABASE_VERSION, upgradeDB => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (upgradeDB.oldVersion) {\n case 0:\n upgradeDB.createObjectStore(OBJECT_STORE_NAME);\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function get(\n appConfig: AppConfig\n): Promise<InstallationEntry | undefined> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n return db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key);\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function set<ValueType extends InstallationEntry>(\n appConfig: AppConfig,\n value: ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const objectStore = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue = await objectStore.get(key);\n await objectStore.put(value, key);\n await tx.complete;\n\n if (!oldValue || oldValue.fid !== value.fid) {\n fidChanged(appConfig, value.fid);\n }\n\n return value;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function remove(appConfig: AppConfig): Promise<void> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.complete;\n}\n\n/**\n * Atomically updates a record with the result of updateFn, which gets\n * called with the current value. If newValue is undefined, the record is\n * deleted instead.\n * @return Updated value\n */\nexport async function update<ValueType extends InstallationEntry | undefined>(\n appConfig: AppConfig,\n updateFn: (previousValue: InstallationEntry | undefined) => ValueType\n): Promise<ValueType> {\n const key = getKey(appConfig);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n const store = tx.objectStore(OBJECT_STORE_NAME);\n const oldValue: InstallationEntry | undefined = await store.get(key);\n const newValue = updateFn(oldValue);\n\n if (newValue === undefined) {\n await store.delete(key);\n } else {\n await store.put(newValue, key);\n }\n await tx.complete;\n\n if (newValue && (!oldValue || oldValue.fid !== newValue.fid)) {\n fidChanged(appConfig, newValue.fid);\n }\n\n return newValue;\n}\n\nexport async function clear(): Promise<void> {\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).clear();\n await tx.complete;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\nimport {\n _FirebaseNamespace,\n FirebaseService\n} from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport { FirebaseInstallations } from '@firebase/installations-types';\nimport {\n deleteInstallation,\n getId,\n getToken,\n IdChangeCallbackFn,\n IdChangeUnsubscribeFn,\n onIdChange\n} from './functions';\nimport { extractAppConfig } from './helpers/extract-app-config';\nimport { FirebaseDependencies } from './interfaces/firebase-dependencies';\n\nimport { name, version } from '../package.json';\n\nexport function registerInstallations(instance: _FirebaseNamespace): void {\n const installationsName = 'installations';\n\n instance.INTERNAL.registerComponent(\n new Component(\n installationsName,\n container => {\n const app = container.getProvider('app').getImmediate();\n\n // Throws if app isn't configured properly.\n const appConfig = extractAppConfig(app);\n const platformLoggerProvider = container.getProvider('platform-logger');\n const dependencies: FirebaseDependencies = {\n appConfig,\n platformLoggerProvider\n };\n\n const installations: FirebaseInstallations & FirebaseService = {\n app,\n getId: () => getId(dependencies),\n getToken: (forceRefresh?: boolean) =>\n getToken(dependencies, forceRefresh),\n delete: () => deleteInstallation(dependencies),\n onIdChange: (callback: IdChangeCallbackFn): IdChangeUnsubscribeFn =>\n onIdChange(dependencies, callback)\n };\n return installations;\n },\n ComponentType.PUBLIC\n )\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterInstallations(firebase as _FirebaseNamespace);\n\n/**\n * Define extension behavior of `registerInstallations`\n */\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n installations(app?: FirebaseApp): FirebaseInstallations;\n }\n interface FirebaseApp {\n installations(): FirebaseInstallations;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { createInstallationRequest } from '../api/create-installation-request';\nimport { AppConfig } from '../interfaces/app-config';\nimport {\n InProgressInstallationEntry,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { generateFid, INVALID_FID } from './generate-fid';\nimport { remove, set, update } from './idb-manager';\n\nexport interface InstallationEntryWithRegistrationPromise {\n installationEntry: InstallationEntry;\n /** Exist iff the installationEntry is not registered. */\n registrationPromise?: Promise<RegisteredInstallationEntry>;\n}\n\n/**\n * Updates and returns the InstallationEntry from the database.\n * Also triggers a registration request if it is necessary and possible.\n */\nexport async function getInstallationEntry(\n appConfig: AppConfig\n): Promise<InstallationEntryWithRegistrationPromise> {\n let registrationPromise: Promise<RegisteredInstallationEntry> | undefined;\n\n const installationEntry = await update(appConfig, oldEntry => {\n const installationEntry = updateOrCreateInstallationEntry(oldEntry);\n const entryWithPromise = triggerRegistrationIfNecessary(\n appConfig,\n installationEntry\n );\n registrationPromise = entryWithPromise.registrationPromise;\n return entryWithPromise.installationEntry;\n });\n\n if (installationEntry.fid === INVALID_FID) {\n // FID generation failed. Waiting for the FID from the server.\n return { installationEntry: await registrationPromise! };\n }\n\n return {\n installationEntry,\n registrationPromise\n };\n}\n\n/**\n * Creates a new Installation Entry if one does not exist.\n * Also clears timed out pending requests.\n */\nfunction updateOrCreateInstallationEntry(\n oldEntry: InstallationEntry | undefined\n): InstallationEntry {\n const entry: InstallationEntry = oldEntry || {\n fid: generateFid(),\n registrationStatus: RequestStatus.NOT_STARTED\n };\n\n return clearTimedOutRequest(entry);\n}\n\n/**\n * If the Firebase Installation is not registered yet, this will trigger the\n * registration and return an InProgressInstallationEntry.\n *\n * If registrationPromise does not exist, the installationEntry is guaranteed\n * to be registered.\n */\nfunction triggerRegistrationIfNecessary(\n appConfig: AppConfig,\n installationEntry: InstallationEntry\n): InstallationEntryWithRegistrationPromise {\n if (installationEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n if (!navigator.onLine) {\n // Registration required but app is offline.\n const registrationPromiseWithError = Promise.reject(\n ERROR_FACTORY.create(ErrorCode.APP_OFFLINE)\n );\n return {\n installationEntry,\n registrationPromise: registrationPromiseWithError\n };\n }\n\n // Try registering. Change status to IN_PROGRESS.\n const inProgressEntry: InProgressInstallationEntry = {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.IN_PROGRESS,\n registrationTime: Date.now()\n };\n const registrationPromise = registerInstallation(\n appConfig,\n inProgressEntry\n );\n return { installationEntry: inProgressEntry, registrationPromise };\n } else if (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS\n ) {\n return {\n installationEntry,\n registrationPromise: waitUntilFidRegistration(appConfig)\n };\n } else {\n return { installationEntry };\n }\n}\n\n/** This will be executed only once for each new Firebase Installation. */\nasync function registerInstallation(\n appConfig: AppConfig,\n installationEntry: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n try {\n const registeredInstallationEntry = await createInstallationRequest(\n appConfig,\n installationEntry\n );\n return set(appConfig, registeredInstallationEntry);\n } catch (e) {\n if (isServerError(e) && e.serverCode === 409) {\n // Server returned a \"FID can not be used\" error.\n // Generate a new ID next time.\n await remove(appConfig);\n } else {\n // Registration failed. Set FID as not registered.\n await set(appConfig, {\n fid: installationEntry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n });\n }\n throw e;\n }\n}\n\n/** Call if FID registration is pending in another request. */\nasync function waitUntilFidRegistration(\n appConfig: AppConfig\n): Promise<RegisteredInstallationEntry> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry: InstallationEntry = await updateInstallationRequest(appConfig);\n while (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // createInstallation request still in progress.\n await sleep(100);\n\n entry = await updateInstallationRequest(appConfig);\n }\n\n if (entry.registrationStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n const {\n installationEntry,\n registrationPromise\n } = await getInstallationEntry(appConfig);\n\n if (registrationPromise) {\n return registrationPromise;\n } else {\n // if there is no registrationPromise, entry is registered.\n return installationEntry as RegisteredInstallationEntry;\n }\n }\n\n return entry;\n}\n\n/**\n * Called only if there is a CreateInstallation request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * CreateInstallation request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateInstallationRequest(\n appConfig: AppConfig\n): Promise<InstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!oldEntry) {\n throw ERROR_FACTORY.create(ErrorCode.INSTALLATION_NOT_FOUND);\n }\n return clearTimedOutRequest(oldEntry);\n });\n}\n\nfunction clearTimedOutRequest(entry: InstallationEntry): InstallationEntry {\n if (hasInstallationRequestTimedOut(entry)) {\n return {\n fid: entry.fid,\n registrationStatus: RequestStatus.NOT_STARTED\n };\n }\n\n return entry;\n}\n\nfunction hasInstallationRequestTimedOut(\n installationEntry: InstallationEntry\n): boolean {\n return (\n installationEntry.registrationStatus === RequestStatus.IN_PROGRESS &&\n installationEntry.registrationTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { CreateInstallationResponse } from '../interfaces/api-response';\nimport { AppConfig } from '../interfaces/app-config';\nimport {\n InProgressInstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { INTERNAL_AUTH_VERSION, PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeaders,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\n\nexport async function createInstallationRequest(\n appConfig: AppConfig,\n { fid }: InProgressInstallationEntry\n): Promise<RegisteredInstallationEntry> {\n const endpoint = getInstallationsEndpoint(appConfig);\n\n const headers = getHeaders(appConfig);\n const body = {\n fid,\n authVersion: INTERNAL_AUTH_VERSION,\n appId: appConfig.appId,\n sdkVersion: PACKAGE_VERSION\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: CreateInstallationResponse = await response.json();\n const registeredInstallationEntry: RegisteredInstallationEntry = {\n fid: responseValue.fid || fid,\n registrationStatus: RequestStatus.COMPLETED,\n refreshToken: responseValue.refreshToken,\n authToken: extractAuthTokenInfoFromResponse(responseValue.authToken)\n };\n return registeredInstallationEntry;\n } else {\n throw await getErrorFromResponse('Create Installation', response);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { GenerateAuthTokenResponse } from '../interfaces/api-response';\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseDependencies } from '../interfaces/firebase-dependencies';\nimport {\n CompletedAuthToken,\n RegisteredInstallationEntry\n} from '../interfaces/installation-entry';\nimport { PACKAGE_VERSION } from '../util/constants';\nimport {\n extractAuthTokenInfoFromResponse,\n getErrorFromResponse,\n getHeadersWithAuth,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\n\nexport async function generateAuthTokenRequest(\n { appConfig, platformLoggerProvider }: FirebaseDependencies,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n const endpoint = getGenerateAuthTokenEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n\n // If platform logger exists, add the platform info string to the header.\n const platformLogger = platformLoggerProvider.getImmediate({\n optional: true\n });\n if (platformLogger) {\n headers.append('x-firebase-client', platformLogger.getPlatformInfoString());\n }\n\n const body = {\n installation: {\n sdkVersion: PACKAGE_VERSION\n }\n };\n\n const request: RequestInit = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (response.ok) {\n const responseValue: GenerateAuthTokenResponse = await response.json();\n const completedAuthToken: CompletedAuthToken = extractAuthTokenInfoFromResponse(\n responseValue\n );\n return completedAuthToken;\n } else {\n throw await getErrorFromResponse('Generate Auth Token', response);\n }\n}\n\nfunction getGenerateAuthTokenEndpoint(\n appConfig: AppConfig,\n { fid }: RegisteredInstallationEntry\n): string {\n return `${getInstallationsEndpoint(appConfig)}/${fid}/authTokens:generate`;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { generateAuthTokenRequest } from '../api/generate-auth-token-request';\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseDependencies } from '../interfaces/firebase-dependencies';\nimport {\n AuthToken,\n CompletedAuthToken,\n InProgressAuthToken,\n InstallationEntry,\n RegisteredInstallationEntry,\n RequestStatus\n} from '../interfaces/installation-entry';\nimport { PENDING_TIMEOUT_MS, TOKEN_EXPIRATION_BUFFER } from '../util/constants';\nimport { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';\nimport { sleep } from '../util/sleep';\nimport { remove, set, update } from './idb-manager';\n\n/**\n * Returns a valid authentication token for the installation. Generates a new\n * token if one doesn't exist, is expired or about to expire.\n *\n * Should only be called if the Firebase Installation is registered.\n */\nexport async function refreshAuthToken(\n dependencies: FirebaseDependencies,\n forceRefresh = false\n): Promise<CompletedAuthToken> {\n let tokenPromise: Promise<CompletedAuthToken> | undefined;\n const entry = await update(dependencies.appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (!forceRefresh && isAuthTokenValid(oldAuthToken)) {\n // There is a valid token in the DB.\n return oldEntry;\n } else if (oldAuthToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // There already is a token request in progress.\n tokenPromise = waitUntilAuthTokenRequest(dependencies, forceRefresh);\n return oldEntry;\n } else {\n // No token or token expired.\n if (!navigator.onLine) {\n throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n }\n\n const inProgressEntry = makeAuthTokenRequestInProgressEntry(oldEntry);\n tokenPromise = fetchAuthTokenFromServer(dependencies, inProgressEntry);\n return inProgressEntry;\n }\n });\n\n const authToken = tokenPromise\n ? await tokenPromise\n : (entry.authToken as CompletedAuthToken);\n return authToken;\n}\n\n/**\n * Call only if FID is registered and Auth Token request is in progress.\n *\n * Waits until the current pending request finishes. If the request times out,\n * tries once in this thread as well.\n */\nasync function waitUntilAuthTokenRequest(\n dependencies: FirebaseDependencies,\n forceRefresh: boolean\n): Promise<CompletedAuthToken> {\n // Unfortunately, there is no way of reliably observing when a value in\n // IndexedDB changes (yet, see https://github.com/WICG/indexed-db-observers),\n // so we need to poll.\n\n let entry = await updateAuthTokenRequest(dependencies.appConfig);\n while (entry.authToken.requestStatus === RequestStatus.IN_PROGRESS) {\n // generateAuthToken still in progress.\n await sleep(100);\n\n entry = await updateAuthTokenRequest(dependencies.appConfig);\n }\n\n const authToken = entry.authToken;\n if (authToken.requestStatus === RequestStatus.NOT_STARTED) {\n // The request timed out or failed in a different call. Try again.\n return refreshAuthToken(dependencies, forceRefresh);\n } else {\n return authToken;\n }\n}\n\n/**\n * Called only if there is a GenerateAuthToken request in progress.\n *\n * Updates the InstallationEntry in the DB based on the status of the\n * GenerateAuthToken request.\n *\n * Returns the updated InstallationEntry.\n */\nfunction updateAuthTokenRequest(\n appConfig: AppConfig\n): Promise<RegisteredInstallationEntry> {\n return update(appConfig, oldEntry => {\n if (!isEntryRegistered(oldEntry)) {\n throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);\n }\n\n const oldAuthToken = oldEntry.authToken;\n if (hasAuthTokenRequestTimedOut(oldAuthToken)) {\n return {\n ...oldEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n }\n\n return oldEntry;\n });\n}\n\nasync function fetchAuthTokenFromServer(\n dependencies: FirebaseDependencies,\n installationEntry: RegisteredInstallationEntry\n): Promise<CompletedAuthToken> {\n try {\n const authToken = await generateAuthTokenRequest(\n dependencies,\n installationEntry\n );\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken\n };\n await set(dependencies.appConfig, updatedInstallationEntry);\n return authToken;\n } catch (e) {\n if (isServerError(e) && (e.serverCode === 401 || e.serverCode === 404)) {\n // Server returned a \"FID not found\" or a \"Invalid authentication\" error.\n // Generate a new ID next time.\n await remove(dependencies.appConfig);\n } else {\n const updatedInstallationEntry: RegisteredInstallationEntry = {\n ...installationEntry,\n authToken: { requestStatus: RequestStatus.NOT_STARTED }\n };\n await set(dependencies.appConfig, updatedInstallationEntry);\n }\n throw e;\n }\n}\n\nfunction isEntryRegistered(\n installationEntry: InstallationEntry | undefined\n): installationEntry is RegisteredInstallationEntry {\n return (\n installationEntry !== undefined &&\n installationEntry.registrationStatus === RequestStatus.COMPLETED\n );\n}\n\nfunction isAuthTokenValid(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.COMPLETED &&\n !isAuthTokenExpired(authToken)\n );\n}\n\nfunction isAuthTokenExpired(authToken: CompletedAuthToken): boolean {\n const now = Date.now();\n return (\n now < authToken.creationTime ||\n authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER\n );\n}\n\n/** Returns an updated InstallationEntry with an InProgressAuthToken. */\nfunction makeAuthTokenRequestInProgressEntry(\n oldEntry: RegisteredInstallationEntry\n): RegisteredInstallationEntry {\n const inProgressAuthToken: InProgressAuthToken = {\n requestStatus: RequestStatus.IN_PROGRESS,\n requestTime: Date.now()\n };\n return {\n ...oldEntry,\n authToken: inProgressAuthToken\n };\n}\n\nfunction hasAuthTokenRequestTimedOut(authToken: AuthToken): boolean {\n return (\n authToken.requestStatus === RequestStatus.IN_PROGRESS &&\n authToken.requestTime + PENDING_TIMEOUT_MS < Date.now()\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { AppConfig } from '../interfaces/app-config';\nimport { FirebaseDependencies } from '../interfaces/firebase-dependencies';\n\nexport async function getToken(\n dependencies: FirebaseDependencies,\n forceRefresh = false\n): Promise<string> {\n await completeInstallationRegistration(dependencies.appConfig);\n\n // At this point we either have a Registered Installation in the DB, or we've\n // already thrown an error.\n const authToken = await refreshAuthToken(dependencies, forceRefresh);\n return authToken.token;\n}\n\nasync function completeInstallationRegistration(\n appConfig: AppConfig\n): Promise<void> {\n const { registrationPromise } = await getInstallationEntry(appConfig);\n\n if (registrationPromise) {\n // A createInstallation request is in progress. Wait until it finishes.\n await registrationPromise;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { AppConfig } from '../interfaces/app-config';\nimport { RegisteredInstallationEntry } from '../interfaces/installation-entry';\nimport {\n getErrorFromResponse,\n getHeadersWithAuth,\n getInstallationsEndpoint,\n retryIfServerError\n} from './common';\n\nexport async function deleteInstallationRequest(\n appConfig: AppConfig,\n installationEntry: RegisteredInstallationEntry\n): Promise<void> {\n const endpoint = getDeleteEndpoint(appConfig, installationEntry);\n\n const headers = getHeadersWithAuth(appConfig, installationEntry);\n const request: RequestInit = {\n method: 'DELETE',\n headers\n };\n\n const response = await retryIfServerError(() => fetch(endpoint, request));\n if (!response.ok) {\n throw await getErrorFromResponse('Delete Installation', response);\n }\n}\n\nfunction getDeleteEndpoint(\n appConfig: AppConfig,\n { fid }: RegisteredInstallationEntry\n): string {\n return `${getInstallationsEndpoint(appConfig)}/${fid}`;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { addCallback, removeCallback } from '../helpers/fid-changed';\nimport { FirebaseDependencies } from '../interfaces/firebase-dependencies';\n\nexport type IdChangeCallbackFn = (installationId: string) => void;\nexport type IdChangeUnsubscribeFn = () => void;\n\n/**\n * Sets a new callback that will get called when Installation ID changes.\n * Returns an unsubscribe function that will remove the callback when called.\n */\nexport function onIdChange(\n { appConfig }: FirebaseDependencies,\n callback: IdChangeCallbackFn\n): IdChangeUnsubscribeFn {\n addCallback(appConfig, callback);\n\n return () => {\n removeCallback(appConfig, callback);\n };\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, FirebaseOptions } from '@firebase/app-types';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/app-config';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: Array<keyof FirebaseOptions> = [\n 'projectId',\n 'apiKey',\n 'appId'\n ];\n\n for (const keyName of configKeys) {\n if (!app.options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: app.options.projectId!,\n apiKey: app.options.apiKey!,\n appId: app.options.appId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { getInstallationEntry } from '../helpers/get-installation-entry';\nimport { refreshAuthToken } from '../helpers/refresh-auth-token';\nimport { FirebaseDependencies } from '../interfaces/firebase-dependencies';\n\nexport async function getId(\n dependencies: FirebaseDependencies\n): Promise<string> {\n const { installationEntry, registrationPromise } = await getInstallationEntry(\n dependencies.appConfig\n );\n\n if (registrationPromise) {\n registrationPromise.catch(console.error);\n } else {\n // If the installation is already registered, update the authentication\n // token if needed.\n refreshAuthToken(dependencies).catch(console.error);\n }\n\n return installationEntry.fid;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { deleteInstallationRequest } from '../api/delete-installation-request';\nimport { remove, update } from '../helpers/idb-manager';\nimport { FirebaseDependencies } from '../interfaces/firebase-dependencies';\nimport { RequestStatus } from '../interfaces/installation-entry';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport async function deleteInstallation(\n dependencies: FirebaseDependencies\n): Promise<void> {\n const { appConfig } = dependencies;\n\n const entry = await update(appConfig, oldEntry => {\n if (oldEntry && oldEntry.registrationStatus === RequestStatus.NOT_STARTED) {\n // Delete the unregistered entry without sending a deleteInstallation request.\n return undefined;\n }\n return oldEntry;\n });\n\n if (entry) {\n if (entry.registrationStatus === RequestStatus.IN_PROGRESS) {\n // Can't delete while trying to register.\n throw ERROR_FACTORY.create(ErrorCode.DELETE_PENDING_REGISTRATION);\n } else if (entry.registrationStatus === RequestStatus.COMPLETED) {\n if (!navigator.onLine) {\n throw ERROR_FACTORY.create(ErrorCode.APP_OFFLINE);\n } else {\n await deleteInstallationRequest(appConfig, entry);\n await remove(appConfig);\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ErrorFactory, ErrorMap } from '@firebase/util';\n\nexport const enum ErrorCode {\n MISSING_APP_CONFIG_VALUES = 'missing-app-config-values',\n AVAILABLE_IN_WINDOW = 'only-available-in-window',\n AVAILABLE_IN_SW = 'only-available-in-sw',\n PERMISSION_DEFAULT = 'permission-default',\n PERMISSION_BLOCKED = 'permission-blocked',\n UNSUPPORTED_BROWSER = 'unsupported-browser',\n FAILED_DEFAULT_REGISTRATION = 'failed-service-worker-registration',\n TOKEN_SUBSCRIBE_FAILED = 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN = 'token-subscribe-no-token',\n TOKEN_UNSUBSCRIBE_FAILED = 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED = 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN = 'token-update-no-token',\n INVALID_BG_HANDLER = 'invalid-bg-handler',\n USE_SW_AFTER_GET_TOKEN = 'use-sw-after-get-token',\n INVALID_SW_REGISTRATION = 'invalid-sw-registration',\n USE_VAPID_KEY_AFTER_GET_TOKEN = 'use-vapid-key-after-get-token',\n INVALID_VAPID_KEY = 'invalid-vapid-key'\n}\n\nexport const ERROR_MAP: ErrorMap<ErrorCode> = {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]:\n 'Missing App configuration value: \"{$valueName}\"',\n [ErrorCode.AVAILABLE_IN_WINDOW]:\n 'This method is available in a Window context.',\n [ErrorCode.AVAILABLE_IN_SW]:\n 'This method is available in a service worker context.',\n [ErrorCode.PERMISSION_DEFAULT]:\n 'The notification permission was not granted and dismissed instead.',\n [ErrorCode.PERMISSION_BLOCKED]:\n 'The notification permission was not granted and blocked instead.',\n [ErrorCode.UNSUPPORTED_BROWSER]:\n \"This browser doesn't support the API's required to use the firebase SDK.\",\n [ErrorCode.FAILED_DEFAULT_REGISTRATION]:\n 'We are unable to register the default service worker. {$browserErrorMessage}',\n [ErrorCode.TOKEN_SUBSCRIBE_FAILED]:\n 'A problem occured while subscribing the user to FCM: {$errorInfo}',\n [ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN]:\n 'FCM returned no token when subscribing the user to push.',\n [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]:\n 'A problem occured while unsubscribing the ' +\n 'user from FCM: {$errorInfo}',\n [ErrorCode.TOKEN_UPDATE_FAILED]:\n 'A problem occured while updating the user from FCM: {$errorInfo}',\n [ErrorCode.TOKEN_UPDATE_NO_TOKEN]:\n 'FCM returned no token when updating the user to push.',\n [ErrorCode.USE_SW_AFTER_GET_TOKEN]:\n 'The useServiceWorker() method may only be called once and must be ' +\n 'called before calling getToken() to ensure your service worker is used.',\n [ErrorCode.INVALID_SW_REGISTRATION]:\n 'The input to useServiceWorker() must be a ServiceWorkerRegistration.',\n [ErrorCode.INVALID_BG_HANDLER]:\n 'The input to setBackgroundMessageHandler() must be a function.',\n [ErrorCode.INVALID_VAPID_KEY]: 'The public VAPID key must be a string.',\n [ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN]:\n 'The usePublicVapidKey() method may only be called once and must be ' +\n 'called before calling getToken() to ensure your VAPID key is used.'\n};\n\ninterface ErrorParams {\n [ErrorCode.MISSING_APP_CONFIG_VALUES]: {\n valueName: string;\n };\n [ErrorCode.FAILED_DEFAULT_REGISTRATION]: { browserErrorMessage: string };\n [ErrorCode.TOKEN_SUBSCRIBE_FAILED]: { errorInfo: string };\n [ErrorCode.TOKEN_UNSUBSCRIBE_FAILED]: { errorInfo: string };\n [ErrorCode.TOKEN_UPDATE_FAILED]: { errorInfo: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n 'messaging',\n 'Messaging',\n ERROR_MAP\n);\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, FirebaseOptions } from '@firebase/app-types';\nimport { FirebaseError } from '@firebase/util';\nimport { AppConfig } from '../interfaces/app-config';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\nexport function extractAppConfig(app: FirebaseApp): AppConfig {\n if (!app || !app.options) {\n throw getMissingValueError('App Configuration Object');\n }\n\n if (!app.name) {\n throw getMissingValueError('App Name');\n }\n\n // Required app config keys\n const configKeys: ReadonlyArray<keyof FirebaseOptions> = [\n 'projectId',\n 'apiKey',\n 'appId',\n 'messagingSenderId'\n ];\n\n const { options } = app;\n for (const keyName of configKeys) {\n if (!options[keyName]) {\n throw getMissingValueError(keyName);\n }\n }\n\n return {\n appName: app.name,\n projectId: options.projectId!,\n apiKey: options.apiKey!,\n appId: options.appId!,\n senderId: options.messagingSenderId!\n };\n}\n\nfunction getMissingValueError(valueName: string): FirebaseError {\n return ERROR_FACTORY.create(ErrorCode.MISSING_APP_CONFIG_VALUES, {\n valueName\n });\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 function arrayToBase64(array: Uint8Array | ArrayBuffer): string {\n const uint8Array = new Uint8Array(array);\n const base64String = btoa(String.fromCharCode(...uint8Array));\n return base64String\n .replace(/=/g, '')\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_');\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { openDb, deleteDb } from 'idb';\nimport { TokenDetails } from '../interfaces/token-details';\nimport { arrayToBase64 } from './array-to-base64';\n\n// https://github.com/firebase/firebase-js-sdk/blob/7857c212f944a2a9eb421fd4cb7370181bc034b5/packages/messaging/src/interfaces/token-details.ts\nexport interface V2TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: string | Uint8Array;\n subscription: PushSubscription;\n fcmSenderId: string;\n fcmPushSet: string;\n createTime?: number;\n endpoint?: string;\n auth?: string;\n p256dh?: string;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/6b5b15ce4ea3df5df5df8a8b33a4e41e249c7715/packages/messaging/src/interfaces/token-details.ts\nexport interface V3TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: Uint8Array;\n fcmSenderId: string;\n fcmPushSet: string;\n endpoint: string;\n auth: ArrayBuffer;\n p256dh: ArrayBuffer;\n createTime: number;\n}\n\n// https://github.com/firebase/firebase-js-sdk/blob/9567dba664732f681fa7fe60f5b7032bb1daf4c9/packages/messaging/src/interfaces/token-details.ts\nexport interface V4TokenDetails {\n fcmToken: string;\n swScope: string;\n vapidKey: Uint8Array;\n fcmSenderId: string;\n endpoint: string;\n auth: ArrayBufferLike;\n p256dh: ArrayBufferLike;\n createTime: number;\n}\n\nconst OLD_DB_NAME = 'fcm_token_details_db';\n/**\n * The last DB version of 'fcm_token_details_db' was 4. This is one higher,\n * so that the upgrade callback is called for all versions of the old DB.\n */\nconst OLD_DB_VERSION = 5;\nconst OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\n\nexport async function migrateOldDatabase(\n senderId: string\n): Promise<TokenDetails | null> {\n if ('databases' in indexedDB) {\n // indexedDb.databases() is an IndexedDB v3 API\n // and does not exist in all browsers.\n // TODO: Remove typecast when it lands in TS types.\n const databases = await (indexedDB as {\n databases(): Promise<Array<{ name: string; version: number }>>;\n }).databases();\n const dbNames = databases.map(db => db.name);\n\n if (!dbNames.includes(OLD_DB_NAME)) {\n // old DB didn't exist, no need to open.\n return null;\n }\n }\n\n let tokenDetails: TokenDetails | null = null;\n\n const db = await openDb(OLD_DB_NAME, OLD_DB_VERSION, async db => {\n if (db.oldVersion < 2) {\n // Database too old, skip migration.\n return;\n }\n\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // Database did not exist. Nothing to do.\n return;\n }\n\n const objectStore = db.transaction.objectStore(OLD_OBJECT_STORE_NAME);\n const value = await objectStore.index('fcmSenderId').get(senderId);\n await objectStore.clear();\n\n if (!value) {\n // No entry in the database, nothing to migrate.\n return;\n }\n\n if (db.oldVersion === 2) {\n const oldDetails = value as V2TokenDetails;\n\n if (!oldDetails.auth || !oldDetails.p256dh || !oldDetails.endpoint) {\n return;\n }\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime ?? Date.now(),\n subscriptionOptions: {\n auth: oldDetails.auth,\n p256dh: oldDetails.p256dh,\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey:\n typeof oldDetails.vapidKey === 'string'\n ? oldDetails.vapidKey\n : arrayToBase64(oldDetails.vapidKey)\n }\n };\n } else if (db.oldVersion === 3) {\n const oldDetails = value as V3TokenDetails;\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime,\n subscriptionOptions: {\n auth: arrayToBase64(oldDetails.auth),\n p256dh: arrayToBase64(oldDetails.p256dh),\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey: arrayToBase64(oldDetails.vapidKey)\n }\n };\n } else if (db.oldVersion === 4) {\n const oldDetails = value as V4TokenDetails;\n\n tokenDetails = {\n token: oldDetails.fcmToken,\n createTime: oldDetails.createTime,\n subscriptionOptions: {\n auth: arrayToBase64(oldDetails.auth),\n p256dh: arrayToBase64(oldDetails.p256dh),\n endpoint: oldDetails.endpoint,\n swScope: oldDetails.swScope,\n vapidKey: arrayToBase64(oldDetails.vapidKey)\n }\n };\n }\n });\n db.close();\n\n // Delete all old databases.\n await deleteDb(OLD_DB_NAME);\n await deleteDb('fcm_vapid_details_db');\n await deleteDb('undefined');\n\n return checkTokenDetails(tokenDetails) ? tokenDetails : null;\n}\n\nfunction checkTokenDetails(\n tokenDetails: TokenDetails | null\n): tokenDetails is TokenDetails {\n if (!tokenDetails || !tokenDetails.subscriptionOptions) {\n return false;\n }\n const { subscriptionOptions } = tokenDetails;\n return (\n typeof tokenDetails.createTime === 'number' &&\n tokenDetails.createTime > 0 &&\n typeof tokenDetails.token === 'string' &&\n tokenDetails.token.length > 0 &&\n typeof subscriptionOptions.auth === 'string' &&\n subscriptionOptions.auth.length > 0 &&\n typeof subscriptionOptions.p256dh === 'string' &&\n subscriptionOptions.p256dh.length > 0 &&\n typeof subscriptionOptions.endpoint === 'string' &&\n subscriptionOptions.endpoint.length > 0 &&\n typeof subscriptionOptions.swScope === 'string' &&\n subscriptionOptions.swScope.length > 0 &&\n typeof subscriptionOptions.vapidKey === 'string' &&\n subscriptionOptions.vapidKey.length > 0\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DB, openDb, deleteDb } from 'idb';\nimport { TokenDetails } from '../interfaces/token-details';\nimport { migrateOldDatabase } from './migrate-old-database';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\n\n// Exported for tests.\nexport const DATABASE_NAME = 'firebase-messaging-database';\nconst DATABASE_VERSION = 1;\nconst OBJECT_STORE_NAME = 'firebase-messaging-store';\n\nlet dbPromise: Promise<DB> | null = null;\nfunction getDbPromise(): Promise<DB> {\n if (!dbPromise) {\n dbPromise = openDb(DATABASE_NAME, DATABASE_VERSION, upgradeDb => {\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (upgradeDb.oldVersion) {\n case 0:\n upgradeDb.createObjectStore(OBJECT_STORE_NAME);\n }\n });\n }\n return dbPromise;\n}\n\n/** Gets record(s) from the objectStore that match the given key. */\nexport async function dbGet(\n firebaseDependencies: FirebaseInternalDependencies\n): Promise<TokenDetails | undefined> {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tokenDetails = await db\n .transaction(OBJECT_STORE_NAME)\n .objectStore(OBJECT_STORE_NAME)\n .get(key);\n\n if (tokenDetails) {\n return tokenDetails;\n } else {\n // Check if there is a tokenDetails object in the old DB.\n const oldTokenDetails = await migrateOldDatabase(\n firebaseDependencies.appConfig.senderId\n );\n if (oldTokenDetails) {\n await dbSet(firebaseDependencies, oldTokenDetails);\n return oldTokenDetails;\n }\n }\n}\n\n/** Assigns or overwrites the record for the given key with the given value. */\nexport async function dbSet(\n firebaseDependencies: FirebaseInternalDependencies,\n tokenDetails: TokenDetails\n): Promise<TokenDetails> {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).put(tokenDetails, key);\n await tx.complete;\n return tokenDetails;\n}\n\n/** Removes record(s) from the objectStore that match the given key. */\nexport async function dbRemove(\n firebaseDependencies: FirebaseInternalDependencies\n): Promise<void> {\n const key = getKey(firebaseDependencies);\n const db = await getDbPromise();\n const tx = db.transaction(OBJECT_STORE_NAME, 'readwrite');\n await tx.objectStore(OBJECT_STORE_NAME).delete(key);\n await tx.complete;\n}\n\n/** Deletes the DB. Useful for tests. */\nexport async function dbDelete(): Promise<void> {\n if (dbPromise) {\n (await dbPromise).close();\n await deleteDb(DATABASE_NAME);\n dbPromise = null;\n }\n}\n\nfunction getKey({ appConfig }: FirebaseInternalDependencies): string {\n return appConfig.appId;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\nexport const DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\n\nexport const DEFAULT_VAPID_KEY =\n 'BDOU99-h67HcA6JeFXHbSNMu7e2yNNu3RzoMj8TM4W88jITfq7ZmPvIM1Iv-4_l2LxQcYwhqby2xGpWwzjfAnG4';\n\nexport const ENDPOINT = 'https://fcmregistrations.googleapis.com/v1';\n\n/** Key of FCM Payload in Notification's data field. */\nexport const FCM_MSG = 'FCM_MSG';\n\nexport const CONSOLE_CAMPAIGN_ID = 'google.c.a.c_id';\nexport const CONSOLE_CAMPAIGN_NAME = 'google.c.a.c_l';\nexport const CONSOLE_CAMPAIGN_TIME = 'google.c.a.ts';\n/** Set to '1' if Analytics is enabled for the campaign */\nexport const CONSOLE_CAMPAIGN_ANALYTICS_ENABLED = 'google.c.a.e';\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ErrorCode, ERROR_FACTORY } from '../util/errors';\nimport { DEFAULT_VAPID_KEY, ENDPOINT } from '../util/constants';\nimport { TokenDetails, SubscriptionOptions } from '../interfaces/token-details';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { AppConfig } from '../interfaces/app-config';\n\nexport interface ApiResponse {\n token?: string;\n error?: { message: string };\n}\n\nexport interface ApiRequestBody {\n web: {\n endpoint: string;\n p256dh: string;\n auth: string;\n applicationPubKey?: string;\n };\n}\n\nexport async function requestGetToken(\n firebaseDependencies: FirebaseInternalDependencies,\n subscriptionOptions: SubscriptionOptions\n): Promise<string> {\n const headers = await getHeaders(firebaseDependencies);\n const body = getBody(subscriptionOptions);\n\n const subscribeOptions = {\n method: 'POST',\n headers,\n body: JSON.stringify(body)\n };\n\n let responseData: ApiResponse;\n try {\n const response = await fetch(\n getEndpoint(firebaseDependencies.appConfig),\n subscribeOptions\n );\n responseData = await response.json();\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n errorInfo: err\n });\n }\n\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {\n errorInfo: message\n });\n }\n\n if (!responseData.token) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n\n return responseData.token;\n}\n\nexport async function requestUpdateToken(\n firebaseDependencies: FirebaseInternalDependencies,\n tokenDetails: TokenDetails\n): Promise<string> {\n const headers = await getHeaders(firebaseDependencies);\n const body = getBody(tokenDetails.subscriptionOptions!);\n\n const updateOptions = {\n method: 'PATCH',\n headers,\n body: JSON.stringify(body)\n };\n\n let responseData: ApiResponse;\n try {\n const response = await fetch(\n `${getEndpoint(firebaseDependencies.appConfig)}/${tokenDetails.token}`,\n updateOptions\n );\n responseData = await response.json();\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n errorInfo: err\n });\n }\n\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {\n errorInfo: message\n });\n }\n\n if (!responseData.token) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_NO_TOKEN);\n }\n\n return responseData.token;\n}\n\nexport async function requestDeleteToken(\n firebaseDependencies: FirebaseInternalDependencies,\n token: string\n): Promise<void> {\n const headers = await getHeaders(firebaseDependencies);\n\n const unsubscribeOptions = {\n method: 'DELETE',\n headers\n };\n\n try {\n const response = await fetch(\n `${getEndpoint(firebaseDependencies.appConfig)}/${token}`,\n unsubscribeOptions\n );\n const responseData: ApiResponse = await response.json();\n if (responseData.error) {\n const message = responseData.error.message;\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n errorInfo: message\n });\n }\n } catch (err) {\n throw ERROR_FACTORY.create(ErrorCode.TOKEN_UNSUBSCRIBE_FAILED, {\n errorInfo: err\n });\n }\n}\n\nfunction getEndpoint({ projectId }: AppConfig): string {\n return `${ENDPOINT}/projects/${projectId!}/registrations`;\n}\n\nasync function getHeaders({\n appConfig,\n installations\n}: FirebaseInternalDependencies): Promise<Headers> {\n const authToken = await installations.getToken();\n\n return new Headers({\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'x-goog-api-key': appConfig.apiKey!,\n 'x-goog-firebase-installations-auth': `FIS ${authToken}`\n });\n}\n\nfunction getBody({\n p256dh,\n auth,\n endpoint,\n vapidKey\n}: SubscriptionOptions): ApiRequestBody {\n const body: ApiRequestBody = {\n web: {\n endpoint,\n auth,\n p256dh\n }\n };\n\n if (vapidKey !== DEFAULT_VAPID_KEY) {\n body.web.applicationPubKey = vapidKey;\n }\n\n return body;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { dbGet, dbSet, dbRemove } from '../helpers/idb-manager';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { TokenDetails, SubscriptionOptions } from '../interfaces/token-details';\nimport { requestUpdateToken, requestGetToken, requestDeleteToken } from './api';\nimport { arrayToBase64 } from '../helpers/array-to-base64';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\n\n/** UpdateRegistration will be called once every week. */\nconst TOKEN_EXPIRATION_MS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nexport async function getToken(\n firebaseDependencies: FirebaseInternalDependencies,\n swRegistration: ServiceWorkerRegistration,\n vapidKey: string\n): Promise<string> {\n if (Notification.permission !== 'granted') {\n throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n }\n\n // If a PushSubscription exists it's returned, otherwise a new subscription\n // is generated and returned.\n const pushSubscription = await getPushSubscription(swRegistration, vapidKey);\n const tokenDetails = await dbGet(firebaseDependencies);\n\n const subscriptionOptions: SubscriptionOptions = {\n vapidKey,\n swScope: swRegistration.scope,\n endpoint: pushSubscription.endpoint,\n auth: arrayToBase64(pushSubscription.getKey('auth')!),\n p256dh: arrayToBase64(pushSubscription.getKey('p256dh')!)\n };\n\n if (!tokenDetails) {\n // No token, get a new one.\n return getNewToken(firebaseDependencies, subscriptionOptions);\n } else if (\n !isTokenValid(tokenDetails.subscriptionOptions!, subscriptionOptions)\n ) {\n // Invalid token, get a new one.\n try {\n await requestDeleteToken(firebaseDependencies, tokenDetails.token);\n } catch (e) {\n // Suppress errors because of #2364\n console.warn(e);\n }\n\n return getNewToken(firebaseDependencies, subscriptionOptions);\n } else if (Date.now() >= tokenDetails.createTime + TOKEN_EXPIRATION_MS) {\n // Weekly token refresh\n return updateToken(\n {\n token: tokenDetails.token,\n createTime: Date.now(),\n subscriptionOptions\n },\n firebaseDependencies,\n swRegistration\n );\n } else {\n // Valid token, nothing to do.\n return tokenDetails.token;\n }\n}\n\n/**\n * This method deletes the token from the database, unsubscribes the token from\n * FCM, and unregisters the push subscription if it exists.\n */\nexport async function deleteToken(\n firebaseDependencies: FirebaseInternalDependencies,\n swRegistration: ServiceWorkerRegistration\n): Promise<boolean> {\n const tokenDetails = await dbGet(firebaseDependencies);\n if (tokenDetails) {\n await requestDeleteToken(firebaseDependencies, tokenDetails.token);\n await dbRemove(firebaseDependencies);\n }\n\n // Unsubscribe from the push subscription.\n const pushSubscription = await swRegistration.pushManager.getSubscription();\n if (pushSubscription) {\n return pushSubscription.unsubscribe();\n }\n\n // If there's no SW, consider it a success.\n return true;\n}\n\nasync function updateToken(\n tokenDetails: TokenDetails,\n firebaseDependencies: FirebaseInternalDependencies,\n swRegistration: ServiceWorkerRegistration\n): Promise<string> {\n try {\n const updatedToken = await requestUpdateToken(\n firebaseDependencies,\n tokenDetails\n );\n\n const updatedTokenDetails: TokenDetails = {\n token: updatedToken,\n createTime: Date.now(),\n ...tokenDetails\n };\n\n await dbSet(firebaseDependencies, updatedTokenDetails);\n return updatedToken;\n } catch (e) {\n await deleteToken(firebaseDependencies, swRegistration);\n throw e;\n }\n}\n\nasync function getNewToken(\n firebaseDependencies: FirebaseInternalDependencies,\n subscriptionOptions: SubscriptionOptions\n): Promise<string> {\n const token = await requestGetToken(\n firebaseDependencies,\n subscriptionOptions\n );\n const tokenDetails: TokenDetails = {\n token,\n createTime: Date.now(),\n subscriptionOptions\n };\n await dbSet(firebaseDependencies, tokenDetails);\n return tokenDetails.token;\n}\n\n/**\n * Gets a PushSubscription for the current user.\n */\nasync function getPushSubscription(\n swRegistration: ServiceWorkerRegistration,\n vapidKey: string\n): Promise<PushSubscription> {\n const subscription = await swRegistration.pushManager.getSubscription();\n if (subscription) {\n return subscription;\n }\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: vapidKey\n });\n}\n\n/**\n * Checks if the saved tokenDetails object matches the configuration provided.\n */\nfunction isTokenValid(\n dbOptions: SubscriptionOptions,\n currentOptions: SubscriptionOptions\n): boolean {\n const isVapidKeyEqual = currentOptions.vapidKey === dbOptions.vapidKey;\n const isEndpointEqual = currentOptions.endpoint === dbOptions.endpoint;\n const isAuthEqual = currentOptions.auth === dbOptions.auth;\n const isP256dhEqual = currentOptions.p256dh === dbOptions.p256dh;\n\n return isVapidKeyEqual && isEndpointEqual && isAuthEqual && isP256dhEqual;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { MessagePayload } from './message-payload';\n\nexport enum MessageType {\n PUSH_RECEIVED = 'push-received',\n NOTIFICATION_CLICKED = 'notification-clicked'\n}\n\nexport interface InternalMessage {\n firebaseMessaging: {\n type: MessageType;\n payload: MessagePayload;\n };\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ConsoleMessageData } from '../interfaces/message-payload';\nimport { CONSOLE_CAMPAIGN_ID } from '../util/constants';\n\nexport function isConsoleMessage(data: unknown): data is ConsoleMessageData {\n // This message has a campaign ID, meaning it was sent using the\n // Firebase Console.\n return typeof data === 'object' && !!data && CONSOLE_CAMPAIGN_ID in data;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { getToken, deleteToken } from '../core/token-management';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { FirebaseMessaging } from '@firebase/messaging-types';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport { NextFn, Observer, Unsubscribe } from '@firebase/util';\nimport { InternalMessage, MessageType } from '../interfaces/internal-message';\nimport {\n CONSOLE_CAMPAIGN_ID,\n CONSOLE_CAMPAIGN_ANALYTICS_ENABLED,\n CONSOLE_CAMPAIGN_NAME,\n CONSOLE_CAMPAIGN_TIME,\n DEFAULT_SW_PATH,\n DEFAULT_SW_SCOPE,\n DEFAULT_VAPID_KEY\n} from '../util/constants';\nimport { FirebaseApp } from '@firebase/app-types';\nimport { ConsoleMessageData } from '../interfaces/message-payload';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { FirebaseService } from '@firebase/app-types/private';\n\nexport class WindowController implements FirebaseMessaging, FirebaseService {\n private vapidKey: string | null = null;\n private swRegistration?: ServiceWorkerRegistration;\n private onMessageCallback: NextFn<object> | null = null;\n\n constructor(\n private readonly firebaseDependencies: FirebaseInternalDependencies\n ) {\n navigator.serviceWorker.addEventListener('message', e =>\n this.messageEventListener(e)\n );\n }\n\n get app(): FirebaseApp {\n return this.firebaseDependencies.app;\n }\n\n async getToken(): Promise<string> {\n if (!this.vapidKey) {\n this.vapidKey = DEFAULT_VAPID_KEY;\n }\n\n const swRegistration = await this.getServiceWorkerRegistration();\n\n // Check notification permission.\n if (Notification.permission === 'default') {\n // The user hasn't allowed or denied notifications yet. Ask them.\n await Notification.requestPermission();\n }\n\n if (Notification.permission !== 'granted') {\n throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n }\n\n return getToken(this.firebaseDependencies, swRegistration, this.vapidKey);\n }\n\n async deleteToken(): Promise<boolean> {\n const swRegistration = await this.getServiceWorkerRegistration();\n\n return deleteToken(this.firebaseDependencies, swRegistration);\n }\n\n /**\n * Request permission if it is not currently granted.\n *\n * @return Resolves if the permission was granted, rejects otherwise.\n *\n * @deprecated Use Notification.requestPermission() instead.\n * https://developer.mozilla.org/en-US/docs/Web/API/Notification/requestPermission\n */\n async requestPermission(): Promise<void> {\n if (Notification.permission === 'granted') {\n return;\n }\n\n const permissionResult = await Notification.requestPermission();\n if (permissionResult === 'granted') {\n return;\n } else if (permissionResult === 'denied') {\n throw ERROR_FACTORY.create(ErrorCode.PERMISSION_BLOCKED);\n } else {\n throw ERROR_FACTORY.create(ErrorCode.PERMISSION_DEFAULT);\n }\n }\n\n // TODO: Deprecate this and make VAPID key a parameter in getToken.\n usePublicVapidKey(vapidKey: string): void {\n if (this.vapidKey !== null) {\n throw ERROR_FACTORY.create(ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN);\n }\n\n if (typeof vapidKey !== 'string' || vapidKey.length === 0) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_VAPID_KEY);\n }\n\n this.vapidKey = vapidKey;\n }\n\n useServiceWorker(swRegistration: ServiceWorkerRegistration): void {\n if (!(swRegistration instanceof ServiceWorkerRegistration)) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_SW_REGISTRATION);\n }\n\n if (this.swRegistration) {\n throw ERROR_FACTORY.create(ErrorCode.USE_SW_AFTER_GET_TOKEN);\n }\n\n this.swRegistration = swRegistration;\n }\n\n /**\n * @param nextOrObserver An observer object or a function triggered on\n * message.\n * @return The unsubscribe function for the observer.\n */\n // TODO: Simplify this to only accept a function and not an Observer.\n onMessage(nextOrObserver: NextFn<object> | Observer<object>): Unsubscribe {\n this.onMessageCallback =\n typeof nextOrObserver === 'function'\n ? nextOrObserver\n : nextOrObserver.next;\n\n return () => {\n this.onMessageCallback = null;\n };\n }\n\n setBackgroundMessageHandler(): void {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_SW);\n }\n\n // Unimplemented\n onTokenRefresh(): Unsubscribe {\n return () => {};\n }\n\n /**\n * Creates or updates the default service worker registration.\n * @return The service worker registration to be used for the push service.\n */\n private async getServiceWorkerRegistration(): Promise<\n ServiceWorkerRegistration\n > {\n if (!this.swRegistration) {\n try {\n this.swRegistration = await navigator.serviceWorker.register(\n DEFAULT_SW_PATH,\n {\n scope: DEFAULT_SW_SCOPE\n }\n );\n\n // The timing when browser updates sw when sw has an update is unreliable by my experiment.\n // It leads to version conflict when the SDK upgrades to a newer version in the main page, but\n // sw is stuck with the old version. For example, https://github.com/firebase/firebase-js-sdk/issues/2590\n // The following line reliably updates sw if there was an update.\n this.swRegistration.update().catch(() => {\n /* it is non blocking and we don't care if it failed */\n });\n } catch (e) {\n throw ERROR_FACTORY.create(ErrorCode.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: e.message\n });\n }\n }\n\n return this.swRegistration;\n }\n\n private async messageEventListener(event: MessageEvent): Promise<void> {\n if (!event.data?.firebaseMessaging) {\n // Not a message from FCM\n return;\n }\n\n const { type, payload } = (event.data as InternalMessage).firebaseMessaging;\n\n if (this.onMessageCallback && type === MessageType.PUSH_RECEIVED) {\n this.onMessageCallback(payload);\n }\n\n const { data } = payload;\n if (\n isConsoleMessage(data) &&\n data[CONSOLE_CAMPAIGN_ANALYTICS_ENABLED] === '1'\n ) {\n // Analytics is enabled on this message, so we should log it.\n await this.logEvent(type, data);\n }\n }\n\n private async logEvent(\n messageType: MessageType,\n data: ConsoleMessageData\n ): Promise<void> {\n const eventType = getEventType(messageType);\n const analytics = await this.firebaseDependencies.analyticsProvider.get();\n analytics.logEvent(eventType, {\n /* eslint-disable camelcase */\n message_id: data[CONSOLE_CAMPAIGN_ID],\n message_name: data[CONSOLE_CAMPAIGN_NAME],\n message_time: data[CONSOLE_CAMPAIGN_TIME],\n message_device_time: Math.floor(Date.now() / 1000)\n /* eslint-enable camelcase */\n });\n }\n}\n\nfunction getEventType(messageType: MessageType): string {\n switch (messageType) {\n case MessageType.NOTIFICATION_CLICKED:\n return 'notification_open';\n case MessageType.PUSH_RECEIVED:\n return 'notification_foreground';\n default:\n throw new Error();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { deleteToken, getToken } from '../core/token-management';\nimport { FirebaseInternalDependencies } from '../interfaces/internal-dependencies';\nimport { FirebaseMessaging } from '@firebase/messaging-types';\nimport { ERROR_FACTORY, ErrorCode } from '../util/errors';\nimport {\n MessagePayload,\n NotificationDetails\n} from '../interfaces/message-payload';\nimport { FCM_MSG, DEFAULT_VAPID_KEY } from '../util/constants';\nimport { MessageType, InternalMessage } from '../interfaces/internal-message';\nimport { dbGet } from '../helpers/idb-manager';\nimport { Unsubscribe } from '@firebase/util';\nimport { sleep } from '../helpers/sleep';\nimport { FirebaseApp } from '@firebase/app-types';\nimport { isConsoleMessage } from '../helpers/is-console-message';\nimport { FirebaseService } from '@firebase/app-types/private';\n\n// Let TS know that this is a service worker\ndeclare const self: ServiceWorkerGlobalScope;\n\nexport type BgMessageHandler = (payload: MessagePayload) => unknown;\n\nexport class SwController implements FirebaseMessaging, FirebaseService {\n private vapidKey: string | null = null;\n private bgMessageHandler: BgMessageHandler | null = null;\n\n constructor(\n private readonly firebaseDependencies: FirebaseInternalDependencies\n ) {\n self.addEventListener('push', e => {\n e.waitUntil(this.onPush(e));\n });\n self.addEventListener('pushsubscriptionchange', e => {\n e.waitUntil(this.onSubChange(e));\n });\n self.addEventListener('notificationclick', e => {\n e.waitUntil(this.onNotificationClick(e));\n });\n }\n\n get app(): FirebaseApp {\n return this.firebaseDependencies.app;\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 *\n * @param callback The callback to be called when a push message is received\n * and a notification must be shown. The callback will be given the data from\n * the push message.\n */\n setBackgroundMessageHandler(callback: BgMessageHandler): void {\n if (!callback || typeof callback !== 'function') {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_BG_HANDLER);\n }\n\n this.bgMessageHandler = callback;\n }\n\n // TODO: Remove getToken from SW Controller.\n // Calling this from an old SW can cause all kinds of trouble.\n async getToken(): Promise<string> {\n if (!this.vapidKey) {\n // Call getToken using the current VAPID key if there already is a token.\n // This is needed because usePublicVapidKey was not available in SW.\n // It will be removed when vapidKey becomes a parameter of getToken, or\n // when getToken is removed from SW.\n const tokenDetails = await dbGet(this.firebaseDependencies);\n this.vapidKey =\n tokenDetails?.subscriptionOptions?.vapidKey ?? DEFAULT_VAPID_KEY;\n }\n\n return getToken(\n this.firebaseDependencies,\n self.registration,\n this.vapidKey\n );\n }\n\n // TODO: Remove deleteToken from SW Controller.\n // Calling this from an old SW can cause all kinds of trouble.\n deleteToken(): Promise<boolean> {\n return deleteToken(this.firebaseDependencies, self.registration);\n }\n\n requestPermission(): Promise<void> {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n // TODO: Deprecate this and make VAPID key a parameter in getToken.\n // TODO: Remove this together with getToken from SW Controller.\n usePublicVapidKey(vapidKey: string): void {\n if (this.vapidKey !== null) {\n throw ERROR_FACTORY.create(ErrorCode.USE_VAPID_KEY_AFTER_GET_TOKEN);\n }\n\n if (typeof vapidKey !== 'string' || vapidKey.length === 0) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_VAPID_KEY);\n }\n\n this.vapidKey = vapidKey;\n }\n\n useServiceWorker(): void {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n onMessage(): Unsubscribe {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\n }\n\n onTokenRefresh(): Unsubscribe {\n throw ERROR_FACTORY.create(ErrorCode.AVAILABLE_IN_WINDOW);\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 */\n async onPush(event: PushEvent): Promise<void> {\n const payload = getMessagePayload(event);\n if (!payload) {\n return;\n }\n\n const clientList = await getClientList();\n if (hasVisibleClients(clientList)) {\n // App in foreground. Send to page.\n return sendMessageToWindowClients(clientList, payload);\n }\n\n const notificationDetails = getNotificationData(payload);\n if (notificationDetails) {\n await showNotification(notificationDetails);\n } else if (this.bgMessageHandler) {\n await this.bgMessageHandler(payload);\n }\n }\n\n async onSubChange(event: PushSubscriptionChangeEvent): Promise<void> {\n const { newSubscription } = event;\n if (!newSubscription) {\n // Subscription revoked, delete token\n await deleteToken(this.firebaseDependencies, self.registration);\n return;\n }\n\n const tokenDetails = await dbGet(this.firebaseDependencies);\n await deleteToken(this.firebaseDependencies, self.registration);\n await getToken(\n this.firebaseDependencies,\n self.registration,\n tokenDetails?.subscriptionOptions?.vapidKey ?? DEFAULT_VAPID_KEY\n );\n }\n\n async onNotificationClick(event: NotificationEvent): Promise<void> {\n const payload: MessagePayload = event.notification?.data?.[FCM_MSG];\n if (!payload) {\n // Not an FCM notification, do nothing.\n return;\n } else if (event.action) {\n // User clicked on an action button.\n // This will allow devs to act on action button clicks by using a custom\n // onNotificationClick listener that they define.\n return;\n }\n\n // Prevent other listeners from receiving the event\n event.stopImmediatePropagation();\n event.notification.close();\n\n const link = getLink(payload);\n if (!link) {\n return;\n }\n\n let client = await getWindowClient(link);\n if (!client) {\n // Unable to find window client so need to open one.\n // This also focuses the opened client.\n client = await self.clients.openWindow(link);\n // Wait three seconds for the client to initialize and set up the message\n // handler so that it can receive the message.\n await sleep(3000);\n } else {\n client = await client.focus();\n }\n\n if (!client) {\n // Window Client will not be returned if it's for a third party origin.\n return;\n }\n\n const message = createNewMessage(MessageType.NOTIFICATION_CLICKED, payload);\n return client.postMessage(message);\n }\n}\n\nfunction getMessagePayload({ data }: PushEvent): MessagePayload | null {\n if (!data) {\n return null;\n }\n\n try {\n return data.json();\n } catch (err) {\n // Not JSON so not an FCM message.\n return null;\n }\n}\n\nfunction getNotificationData(\n payload: MessagePayload\n): NotificationDetails | undefined {\n if (!payload || typeof payload.notification !== 'object') {\n return;\n }\n\n const notificationInformation: NotificationDetails = {\n ...payload.notification\n };\n\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 ...payload.notification.data,\n [FCM_MSG]: payload\n };\n\n return notificationInformation;\n}\n\n/**\n * @param url The URL to look for when focusing a client.\n * @return Returns an existing window client or a newly opened WindowClient.\n */\nasync function getWindowClient(url: string): Promise<WindowClient | null> {\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, self.location.href).href;\n\n const clientList = await getClientList();\n\n for (const client of clientList) {\n const parsedClientUrl = new URL(client.url, self.location.href).href;\n if (parsedClientUrl === parsedURL) {\n return client;\n }\n }\n\n return null;\n}\n\n/**\n * @returns If there is currently a visible WindowClient, this method will\n * resolve to true, otherwise false.\n */\nfunction hasVisibleClients(clientList: WindowClient[]): boolean {\n return clientList.some(\n client =>\n client.visibilityState === 'visible' &&\n // Ignore chrome-extension clients as that matches the background pages\n // of extensions, which are always considered visible for some reason.\n !client.url.startsWith('chrome-extension://')\n );\n}\n\n/**\n * @param payload The data from the push event that should be sent to all\n * available pages.\n * @returns Returns a promise that resolves once the message has been sent to\n * all WindowClients.\n */\nfunction sendMessageToWindowClients(\n clientList: WindowClient[],\n payload: MessagePayload\n): void {\n const message = createNewMessage(MessageType.PUSH_RECEIVED, payload);\n\n for (const client of clientList) {\n client.postMessage(message);\n }\n}\n\nfunction getClientList(): Promise<WindowClient[]> {\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true\n // TS doesn't know that \"type: 'window'\" means it'll return WindowClient[]\n }) as Promise<WindowClient[]>;\n}\n\nfunction createNewMessage(\n type: MessageType,\n payload: MessagePayload\n): InternalMessage {\n return {\n firebaseMessaging: { type, payload }\n };\n}\n\nfunction showNotification(details: NotificationDetails): Promise<void> {\n const title = details.title ?? '';\n\n const { actions } = details;\n const { maxActions } = Notification;\n if (actions && maxActions && actions.length > maxActions) {\n console.warn(\n `This browser only supports ${maxActions} actions. The remaining actions will not be displayed.`\n );\n }\n\n return self.registration.showNotification(title, details);\n}\n\nfunction getLink(payload: MessagePayload): string | null {\n // eslint-disable-next-line camelcase\n const link = payload.fcmOptions?.link ?? payload.notification?.click_action;\n if (link) {\n return link;\n }\n\n if (isConsoleMessage(payload.data)) {\n // Notification created in the Firebase Console. Redirect to origin.\n return self.location.origin;\n } else {\n return null;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Returns a promise that resolves after given time passes. */\nexport function sleep(ms: number): Promise<void> {\n return new Promise<void>(resolve => {\n setTimeout(resolve, ms);\n });\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\nimport '@firebase/installations';\nimport {\n _FirebaseNamespace,\n FirebaseService\n} from '@firebase/app-types/private';\nimport { FirebaseMessaging } from '@firebase/messaging-types';\nimport {\n Component,\n ComponentType,\n ComponentContainer\n} from '@firebase/component';\nimport { extractAppConfig } from './helpers/extract-app-config';\nimport { FirebaseInternalDependencies } from './interfaces/internal-dependencies';\nimport { ERROR_FACTORY, ErrorCode } from './util/errors';\nimport { WindowController } from './controllers/window-controller';\nimport { SwController } from './controllers/sw-controller';\n\nconst MESSAGING_NAME = 'messaging';\nfunction factoryMethod(\n container: ComponentContainer\n): FirebaseService & FirebaseMessaging {\n // Dependencies.\n const app = container.getProvider('app').getImmediate();\n const appConfig = extractAppConfig(app);\n const installations = container.getProvider('installations').getImmediate();\n const analyticsProvider = container.getProvider('analytics-internal');\n\n const firebaseDependencies: FirebaseInternalDependencies = {\n app,\n appConfig,\n installations,\n analyticsProvider\n };\n\n if (!isSupported()) {\n throw ERROR_FACTORY.create(ErrorCode.UNSUPPORTED_BROWSER);\n }\n\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // Running in ServiceWorker context\n return new SwController(firebaseDependencies);\n } else {\n // Assume we are in the window context.\n return new WindowController(firebaseDependencies);\n }\n}\n\nconst NAMESPACE_EXPORTS = {\n isSupported\n};\n\n(firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n MESSAGING_NAME,\n factoryMethod,\n ComponentType.PUBLIC\n ).setServiceProps(NAMESPACE_EXPORTS)\n);\n\n/**\n * Define extension behavior of `registerMessaging`\n */\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n messaging: {\n (app?: FirebaseApp): FirebaseMessaging;\n isSupported(): boolean;\n };\n }\n interface FirebaseApp {\n messaging(): FirebaseMessaging;\n }\n}\n\nfunction isSupported(): boolean {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // Running in ServiceWorker context\n return isSWControllerSupported();\n } else {\n // Assume we are in the window context.\n return isWindowControllerSupported();\n }\n}\n\n/**\n * Checks to see if the required APIs exist.\n */\nfunction isWindowControllerSupported(): boolean {\n return (\n 'indexedDB' in window &&\n indexedDB !== null &&\n navigator.cookieEnabled &&\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 * Checks to see if the required APIs exist within SW Context.\n */\nfunction isSWControllerSupported(): boolean {\n return (\n 'indexedDB' in self &&\n indexedDB !== null &&\n 'PushManager' in self &&\n 'Notification' in self &&\n ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') &&\n PushSubscription.prototype.hasOwnProperty('getKey')\n );\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 name for firebase storage.\n */\nexport const DEFAULT_HOST = 'firebasestorage.googleapis.com';\n\n/**\n * The key in Firebase config json for the storage bucket.\n */\nexport const CONFIG_STORAGE_BUCKET_KEY = 'storageBucket';\n\n/**\n * 2 minutes\n *\n * The timeout for all operations except upload.\n */\nexport const DEFAULT_MAX_OPERATION_RETRY_TIME = 2 * 60 * 1000;\n\n/**\n * 10 minutes\n *\n * The timeout for upload.\n */\nexport const DEFAULT_MAX_UPLOAD_RETRY_TIME = 10 * 60 * 1000;\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 MIN_SAFE_INTEGER = -9007199254740991;\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { CONFIG_STORAGE_BUCKET_KEY } 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): void {\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 const 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 const 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 CONFIG_STORAGE_BUCKET_KEY +\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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';\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: unknown): void {\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, contentType?: string | null) {\n this.contentType = contentType || null;\n }\n}\n\nexport function dataFromString(\n format: StringFormat,\n stringData: string\n): StringData {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(stringData));\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, stringData));\n case StringFormat.DATA_URL:\n return new StringData(\n dataURLBytes_(stringData),\n dataURLContentType_(stringData)\n );\n default:\n // do nothing\n }\n\n // assert(false);\n throw errorsExports.unknown();\n}\n\nexport function utf8Bytes_(value: string): Uint8Array {\n const b: number[] = [];\n for (let i = 0; i < value.length; i++) {\n let c = value.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 const valid =\n i < value.length - 1 && (value.charCodeAt(i + 1) & 64512) === 56320;\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n } else {\n const hi = c;\n const lo = value.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_(value: string): Uint8Array {\n let decoded;\n try {\n decoded = decodeURIComponent(value);\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, value: string): Uint8Array {\n switch (format) {\n case StringFormat.BASE64: {\n const hasMinus = value.indexOf('-') !== -1;\n const hasUnder = value.indexOf('_') !== -1;\n if (hasMinus || hasUnder) {\n const 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 const hasPlus = value.indexOf('+') !== -1;\n const hasSlash = value.indexOf('/') !== -1;\n if (hasPlus || hasSlash) {\n const invalidChar = hasPlus ? '+' : '/';\n throw errorsExports.invalidFormat(\n format,\n \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\"\n );\n }\n value = value.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n default:\n // do nothing\n }\n let bytes;\n try {\n bytes = atob(value);\n } catch (e) {\n throw errorsExports.invalidFormat(format, 'Invalid character found');\n }\n const 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 const matches = dataURL.match(/^data:([^,]+)?,/);\n if (matches === null) {\n throw errorsExports.invalidFormat(\n StringFormat.DATA_URL,\n \"Must be formatted 'data:[<mediatype>][;base64],<data>\"\n );\n }\n const 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_(dataUrl: string): Uint8Array {\n const parts = new DataURLParts(dataUrl);\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n } else {\n return percentEncodedBytes_(parts.rest);\n }\n}\n\nexport function dataURLContentType_(dataUrl: string): string | null {\n const parts = new DataURLParts(dataUrl);\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 interface Headers {\n [name: string]: string | number;\n}\n\nexport interface XhrIo {\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string | null,\n headers?: Headers\n ): Promise<XhrIo>;\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: ProgressEvent) => void): void;\n\n removeUploadProgressListener(listener: (p1: ProgressEvent) => 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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<T>(p: T | null | undefined): p is T {\n return p != null;\n}\n\nexport function isJustDef<T>(p: T | null | undefined): p is T | null {\n return p !== void 0;\n}\n\nexport function isFunction(p: unknown): p is Function {\n return typeof p === 'function';\n}\n\nexport function isObject(p: unknown): p is { [key: string]: unknown } | null {\n return typeof p === 'object';\n}\n\nexport function isNonNullObject(p: unknown): p is object {\n return isObject(p) && p !== null;\n}\n\nexport function isNonArrayObject(p: unknown): boolean {\n return isObject(p) && !Array.isArray(p);\n}\n\nexport function isString(p: unknown): p is string {\n return typeof p === 'string' || p instanceof String;\n}\n\nexport function isInteger(p: unknown): p is number {\n return isNumber(p) && Number.isInteger(p);\n}\n\nexport function isNumber(p: unknown): p is number {\n return typeof p === 'number' || p instanceof Number;\n}\n\nexport function isNativeBlob(p: unknown): p is Blob {\n return isNativeBlobDefined() && p instanceof Blob;\n}\n\nexport function isNativeBlobDefined(): boolean {\n return typeof Blob !== 'undefined';\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 type from './type';\nimport { Headers, XhrIo, ErrorCode } 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_: ErrorCode;\n private sendPromise_: Promise<XhrIo>;\n private sent_: boolean = false;\n\n constructor() {\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = new Promise(resolve => {\n this.xhr_.addEventListener('abort', () => {\n this.errorCode_ = ErrorCode.ABORT;\n resolve(this);\n });\n this.xhr_.addEventListener('error', () => {\n this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve(this);\n });\n this.xhr_.addEventListener('load', () => {\n resolve(this);\n });\n });\n }\n\n /**\n * @override\n */\n send(\n url: string,\n method: string,\n body?: ArrayBufferView | Blob | string | null,\n headers?: Headers\n ): Promise<XhrIo> {\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(headers)) {\n for (const key in headers) {\n if (headers.hasOwnProperty(key)) {\n this.xhr_.setRequestHeader(key, headers[key].toString());\n }\n }\n }\n if (type.isDef(body)) {\n this.xhr_.send(body);\n } else {\n this.xhr_.send();\n }\n return this.sendPromise_;\n }\n\n /**\n * @override\n */\n getErrorCode(): 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(): void {\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: ProgressEvent) => void): 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: ProgressEvent) => void): void {\n if (type.isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 type from './type';\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 args The values that will make up the resulting blob.\n * @return The blob.\n */\nexport function getBlob(...args: Array<string | Blob | ArrayBuffer>): Blob {\n const BlobBuilder = getBlobBuilder();\n if (BlobBuilder !== undefined) {\n const bb = new BlobBuilder();\n for (let i = 0; i < args.length; i++) {\n bb.append(args[i]);\n }\n return bb.getBlob();\n } else {\n if (type.isNativeBlobDefined()) {\n return new Blob(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.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","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { StringFormat, dataFromString } 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, 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 (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 (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 const realBlob = this.data_ as Blob;\n const sliced = fs.sliceBlob(realBlob, startByte, endByte);\n if (sliced === null) {\n return null;\n }\n return new FbsBlob(sliced);\n } else {\n const 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(...args: Array<string | FbsBlob>): FbsBlob | null {\n if (type.isNativeBlobDefined()) {\n const blobby: Array<Blob | Uint8Array | string> = args.map(\n (val: string | FbsBlob): Blob | Uint8Array | string => {\n if (val instanceof FbsBlob) {\n return val.data_;\n } else {\n return val;\n }\n }\n );\n return new FbsBlob(fs.getBlob.apply(null, blobby));\n } else {\n const uint8Arrays: Uint8Array[] = args.map(\n (val: string | FbsBlob): Uint8Array => {\n if (type.isString(val)) {\n return 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 );\n let finalLength = 0;\n uint8Arrays.forEach((array: Uint8Array): void => {\n finalLength += array.byteLength;\n });\n const merged = new Uint8Array(finalLength);\n let index = 0;\n uint8Arrays.forEach((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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DEFAULT_HOST } from './constants';\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 get isRoot(): boolean {\n return this.path.length === 0;\n }\n\n fullServerUrl(): string {\n const encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n }\n\n bucketOnlyServerUrl(): string {\n const 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: Location | null = null;\n const bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\n\n function gsModify(loc: Location): void {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n const gsPath = '(/(.*))?$';\n const path = '(/([^?#]*).*)?$';\n const gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n const gsIndices = { bucket: 1, path: 3 };\n\n function httpModify(loc: Location): void {\n loc.path_ = decodeURIComponent(loc.path);\n }\n const version = 'v[A-Za-z0-9_]+';\n const hostRegex = DEFAULT_HOST.replace(/[.]/g, '\\\\.');\n const httpRegex = new RegExp(\n `^https?://${hostRegex}/${version}/b/${bucketDomain}/o${path}`,\n 'i'\n );\n const httpIndices = { bucket: 1, path: 3 };\n const 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 const group = groups[i];\n const captures = group.regex.exec(url);\n if (captures) {\n const 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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(\n s: string\n): { [name: string]: unknown } | 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 const index = path.lastIndexOf('/');\n if (index === -1) {\n return '';\n }\n const newPath = path.slice(0, index);\n return newPath;\n}\n\nexport function child(path: string, childPath: string): string {\n const canonicalChildPath = childPath\n .split('/')\n .filter(component => component.length > 0)\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 const 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { DEFAULT_HOST } from './constants';\nimport { UrlParams } from './requestinfo';\n\nexport function makeUrl(urlPart: string): string {\n return `https://${DEFAULT_HOST}/v0${urlPart}`;\n}\n\nexport function makeQueryString(params: UrlParams): string {\n const encode = encodeURIComponent;\n let queryPart = '?';\n for (const key in params) {\n if (params.hasOwnProperty(key)) {\n // @ts-ignore TODO: remove once typescript is upgraded to 3.5.x\n const nextPart = encode(key) + '=' + encode(params[key]);\n queryPart = queryPart + nextPart + '&';\n }\n }\n\n // Chop off the extra '&' or '?' on the end\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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';\nimport { Reference } from '../reference';\n\nexport function noXform_<T>(metadata: Metadata, value: T): T {\n return value;\n}\n\n/**\n * @struct\n */\nclass Mapping<T> {\n local: string;\n writable: boolean;\n xform: (p1: Metadata, p2?: T) => T | undefined;\n\n constructor(\n public server: string,\n local?: string | null,\n writable?: boolean,\n xform?: ((p1: Metadata, p2?: T) => T | undefined) | null\n ) {\n this.local = local || server;\n this.writable = !!writable;\n this.xform = xform || noXform_;\n }\n}\ntype Mappings = Array<Mapping<string> | Mapping<number>>;\n\nexport { Mappings };\n\nlet mappings_: Mappings | null = null;\n\nexport function xformPath(fullPath: string | undefined): string | undefined {\n if (!type.isString(fullPath) || fullPath.length < 2) {\n return fullPath;\n } else {\n return path.lastComponent(fullPath);\n }\n}\n\nexport function getMappings(): Mappings {\n if (mappings_) {\n return mappings_;\n }\n const mappings: Mappings = [];\n mappings.push(new Mapping<string>('bucket'));\n mappings.push(new Mapping<string>('generation'));\n mappings.push(new Mapping<string>('metageneration'));\n mappings.push(new Mapping<string>('name', 'fullPath', true));\n\n function mappingsXformPath(\n _metadata: Metadata,\n fullPath: string | undefined\n ): string | undefined {\n return xformPath(fullPath);\n }\n const nameMapping = new Mapping<string>('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(\n _metadata: Metadata,\n size: number | string | undefined\n ): number | undefined {\n if (type.isDef(size)) {\n return Number(size);\n } else {\n return size;\n }\n }\n const sizeMapping = new Mapping<number>('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping<number>('timeCreated'));\n mappings.push(new Mapping<string>('updated'));\n mappings.push(new Mapping<string>('md5Hash', null, true));\n mappings.push(new Mapping<string>('cacheControl', null, true));\n mappings.push(new Mapping<string>('contentDisposition', null, true));\n mappings.push(new Mapping<string>('contentEncoding', null, true));\n mappings.push(new Mapping<string>('contentLanguage', null, true));\n mappings.push(new Mapping<string>('contentType', null, true));\n mappings.push(new Mapping<string>('metadata', 'customMetadata', true));\n mappings_ = mappings;\n return mappings_;\n}\n\nexport function addRef(metadata: Metadata, authWrapper: AuthWrapper): void {\n function generateRef(): Reference {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const 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]: unknown },\n mappings: Mappings\n): Metadata {\n const metadata: Metadata = {} as Metadata;\n metadata['type'] = 'file';\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const mapping = mappings[i];\n metadata[mapping.local] = (mapping as Mapping<unknown>).xform(\n metadata,\n resource[mapping.server]\n );\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 const obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = obj as Metadata;\n return fromResource(authWrapper, resource, mappings);\n}\n\nexport function downloadUrlFromResourceString(\n metadata: Metadata,\n resourceString: string\n): string | null {\n const obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n if (!type.isString(obj['downloadTokens'])) {\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 null;\n }\n const tokens: string = obj['downloadTokens'] as string;\n if (tokens.length === 0) {\n return null;\n }\n const encode = encodeURIComponent;\n const tokensList = tokens.split(',');\n const urls = tokensList.map((token: string): string => {\n const bucket: string = metadata['bucket'] as string;\n const path: string = metadata['fullPath'] as string;\n const urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n const base = UrlUtils.makeUrl(urlPart);\n const queryString = UrlUtils.makeQueryString({\n alt: 'media',\n token\n });\n return base + queryString;\n });\n return urls[0];\n}\n\nexport function toResourceString(\n metadata: Metadata,\n mappings: Mappings\n): string {\n const resource: {\n [prop: string]: unknown;\n } = {};\n const len = mappings.length;\n for (let i = 0; i < len; i++) {\n const 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: unknown): void {\n if (!type.isObject(p) || !p) {\n throw 'Expected Metadata object.';\n }\n for (const key in p) {\n if (p.hasOwnProperty(key)) {\n const 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 * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 listOptions and listResult format\n */\nimport { AuthWrapper } from './authwrapper';\nimport { Location } from './location';\nimport * as json from './json';\nimport * as type from './type';\nimport { ListResult } from '../list';\nimport * as errors from './error';\n\n/**\n * Represents the simplified object metadata returned by List API.\n * Other fields are filtered because list in Firebase Rules does not grant\n * the permission to read the metadata.\n */\ninterface ListMetadataResponse {\n name: string;\n bucket: string;\n}\n\n/**\n * Represents the JSON response of List API.\n */\ninterface ListResultResponse {\n prefixes: string[];\n items: ListMetadataResponse[];\n nextPageToken?: string;\n}\n\nconst MAX_RESULTS_KEY = 'maxResults';\nconst MAX_MAX_RESULTS = 1000;\nconst PAGE_TOKEN_KEY = 'pageToken';\nconst PREFIXES_KEY = 'prefixes';\nconst ITEMS_KEY = 'items';\n\nfunction fromBackendResponse(\n authWrapper: AuthWrapper,\n resource: ListResultResponse\n): ListResult {\n const listResult: ListResult = {\n prefixes: [],\n items: [],\n nextPageToken: resource['nextPageToken']\n };\n const bucket = authWrapper.bucket();\n if (bucket === null) {\n throw errors.noDefaultBucket();\n }\n if (resource[PREFIXES_KEY]) {\n for (const path of resource[PREFIXES_KEY]) {\n const pathWithoutTrailingSlash = path.replace(/\\/$/, '');\n const reference = authWrapper.makeStorageReference(\n new Location(bucket, pathWithoutTrailingSlash)\n );\n listResult.prefixes.push(reference);\n }\n }\n\n if (resource[ITEMS_KEY]) {\n for (const item of resource[ITEMS_KEY]) {\n const reference = authWrapper.makeStorageReference(\n new Location(bucket, item['name'])\n );\n listResult.items.push(reference);\n }\n }\n return listResult;\n}\n\nexport function fromResponseString(\n authWrapper: AuthWrapper,\n resourceString: string\n): ListResult | null {\n const obj = json.jsonObjectOrNull(resourceString);\n if (obj === null) {\n return null;\n }\n const resource = (obj as unknown) as ListResultResponse;\n return fromBackendResponse(authWrapper, resource);\n}\n\nexport function listOptionsValidator(p: unknown): void {\n if (!type.isObject(p) || !p) {\n throw 'Expected ListOptions object.';\n }\n for (const key in p) {\n if (key === MAX_RESULTS_KEY) {\n if (\n !type.isInteger(p[MAX_RESULTS_KEY]) ||\n (p[MAX_RESULTS_KEY] as number) <= 0\n ) {\n throw 'Expected maxResults to be a positive number.';\n }\n if ((p[MAX_RESULTS_KEY] as number) > 1000) {\n throw `Expected maxResults to be less than or equal to ${MAX_MAX_RESULTS}.`;\n }\n } else if (key === PAGE_TOKEN_KEY) {\n if (p[PAGE_TOKEN_KEY] && !type.isString(p[PAGE_TOKEN_KEY])) {\n throw 'Expected pageToken to be string.';\n }\n } else {\n throw 'Unknown option: ' + key;\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 interface UrlParams {\n [name: string]: string | number;\n}\n\nexport class RequestInfo<T> {\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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';\nimport { ListResult } from '../list';\nimport { AuthWrapper } from './authwrapper';\nimport { FbsBlob } from './blob';\nimport {\n FirebaseStorageError,\n cannotSliceBlob,\n unauthenticated,\n quotaExceeded,\n unauthorized,\n objectNotFound,\n serverFileWrongSize,\n unknown\n} from './error';\nimport { Location } from './location';\nimport * as MetadataUtils from './metadata';\nimport * as ListResultUtils from './list';\nimport { RequestInfo, UrlParams } 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): void {\n if (!cndn) {\n throw 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 const 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 listHandler(\n authWrapper: AuthWrapper\n): (p1: XhrIo, p2: string) => ListResult {\n function handler(xhr: XhrIo, text: string): ListResult {\n const listResult = ListResultUtils.fromResponseString(authWrapper, text);\n handlerCheck(listResult !== null);\n return listResult as ListResult;\n }\n return handler;\n}\n\nexport function downloadUrlHandler(\n authWrapper: AuthWrapper,\n mappings: MetadataUtils.Mappings\n): (p1: XhrIo, p2: string) => string | null {\n function handler(xhr: XhrIo, text: string): string | null {\n const metadata = MetadataUtils.fromResourceString(\n authWrapper,\n text,\n mappings\n );\n handlerCheck(metadata !== null);\n return MetadataUtils.downloadUrlFromResourceString(\n metadata as Metadata,\n text\n );\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 = 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}\n\nexport function objectErrorHandler(\n location: Location\n): (p1: XhrIo, p2: FirebaseStorageError) => FirebaseStorageError {\n const 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 = 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<Metadata> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'GET';\n const timeout = authWrapper.maxOperationRetryTime();\n const 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 list(\n authWrapper: AuthWrapper,\n location: Location,\n delimiter?: string,\n pageToken?: string | null,\n maxResults?: number | null\n): RequestInfo<ListResult> {\n const urlParams: UrlParams = {};\n if (location.isRoot) {\n urlParams['prefix'] = '';\n } else {\n urlParams['prefix'] = location.path + '/';\n }\n if (delimiter && delimiter.length > 0) {\n urlParams['delimiter'] = delimiter;\n }\n if (pageToken) {\n urlParams['pageToken'] = pageToken;\n }\n if (maxResults) {\n urlParams['maxResults'] = maxResults;\n }\n const urlPart = location.bucketOnlyServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'GET';\n const timeout = authWrapper.maxOperationRetryTime();\n const requestInfo = new RequestInfo(\n url,\n method,\n listHandler(authWrapper),\n timeout\n );\n requestInfo.urlParams = urlParams;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n\nexport function getDownloadUrl(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings\n): RequestInfo<string | null> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'GET';\n const timeout = authWrapper.maxOperationRetryTime();\n const requestInfo = new RequestInfo(\n url,\n method,\n downloadUrlHandler(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<Metadata> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'PATCH';\n const body = MetadataUtils.toResourceString(metadata, mappings);\n const headers = { 'Content-Type': 'application/json; charset=utf-8' };\n const timeout = authWrapper.maxOperationRetryTime();\n const 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<void> {\n const urlPart = location.fullServerUrl();\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'DELETE';\n const timeout = authWrapper.maxOperationRetryTime();\n\n function handler(_xhr: XhrIo, _text: string): void {}\n const 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 metadata?: Metadata | null\n): Metadata {\n const metadataClone = Object.assign({}, metadata);\n metadataClone['fullPath'] = location.path;\n metadataClone['size'] = blob.size();\n if (!metadataClone['contentType']) {\n metadataClone['contentType'] = determineContentType_(null, blob);\n }\n return metadataClone;\n}\n\nexport function multipartUpload(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<Metadata> {\n const urlPart = location.bucketOnlyServerUrl();\n const headers: { [prop: string]: string } = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n\n function genBoundary(): string {\n let str = '';\n for (let i = 0; i < 2; i++) {\n str =\n str +\n Math.random()\n .toString()\n .slice(2);\n }\n return str;\n }\n const boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n const metadata_ = metadataForUpload_(location, blob, metadata);\n const metadataString = MetadataUtils.toResourceString(metadata_, mappings);\n const 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 const postBlobPart = '\\r\\n--' + boundary + '--';\n const body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n if (body === null) {\n throw cannotSliceBlob();\n }\n const urlParams: UrlParams = { name: metadata_['fullPath']! };\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'POST';\n const timeout = authWrapper.maxUploadRetryTime();\n const 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, allowed?: string[]): string {\n let status: string | null = null;\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n } catch (e) {\n handlerCheck(false);\n }\n const allowedStatus = allowed || ['active'];\n handlerCheck(!!status && allowedStatus.indexOf(status) !== -1);\n return status as string;\n}\n\nexport function createResumableUpload(\n authWrapper: AuthWrapper,\n location: Location,\n mappings: MetadataUtils.Mappings,\n blob: FbsBlob,\n metadata?: Metadata | null\n): RequestInfo<string> {\n const urlPart = location.bucketOnlyServerUrl();\n const metadataForUpload = metadataForUpload_(location, blob, metadata);\n const urlParams: UrlParams = { name: metadataForUpload['fullPath']! };\n const url = UrlUtils.makeUrl(urlPart);\n const method = 'POST';\n const 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': metadataForUpload['contentType']!,\n 'Content-Type': 'application/json; charset=utf-8'\n };\n const body = MetadataUtils.toResourceString(metadataForUpload, mappings);\n const timeout = authWrapper.maxUploadRetryTime();\n\n function handler(xhr: XhrIo): 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 const 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<ResumableUploadStatus> {\n const headers = { 'X-Goog-Upload-Command': 'query' };\n\n function handler(xhr: XhrIo): ResumableUploadStatus {\n const status = checkResumeHeader_(xhr, ['active', 'final']);\n let sizeString: string | null = null;\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n } catch (e) {\n handlerCheck(false);\n }\n\n if (!sizeString) {\n // null or empty string\n handlerCheck(false);\n }\n\n const size = Number(sizeString);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n const method = 'POST';\n const timeout = authWrapper.maxUploadRetryTime();\n const 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 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 status?: ResumableUploadStatus | null,\n progressCallback?: ((p1: number, p2: number) => void) | null\n): RequestInfo<ResumableUploadStatus> {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n const status_ = new ResumableUploadStatus(0, 0);\n if (status) {\n status_.current = status.current;\n status_.total = 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 const bytesLeft = status_.total - status_.current;\n let bytesToUpload = bytesLeft;\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n const startByte = status_.current;\n const endByte = startByte + bytesToUpload;\n const uploadCommand =\n bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n const headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status_.current\n };\n const body = blob.slice(startByte, endByte);\n if (body === null) {\n throw 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 const uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n const newCurrent = status_.current + bytesToUpload;\n const 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 const method = 'POST';\n const timeout = authWrapper.maxUploadRetryTime();\n const requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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';\nimport { FirebaseStorageError } from './error';\n\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: Error | FirebaseStorageError) => void;\nexport type CompleteFn = () => void;\nexport type Unsubscribe = () => void;\n\nexport interface StorageObserver<T> {\n next?: NextFn<T> | null;\n error?: ErrorFn | null;\n complete?: CompleteFn | null;\n}\n\nexport type Subscribe<T> = (\n next?: NextFn<T> | StorageObserver<T> | null,\n error?: ErrorFn | null,\n complete?: CompleteFn | null\n) => Unsubscribe;\n\n/**\n * @struct\n */\nexport class Observer<T> implements StorageObserver<T> {\n next?: NextFn<T> | null;\n error?: ErrorFn | null;\n complete?: CompleteFn | null;\n\n constructor(\n nextOrObserver?: NextFn<T> | StorageObserver<T> | null,\n error?: ErrorFn | null,\n complete?: CompleteFn | null\n ) {\n const asFunctions =\n type.isFunction(nextOrObserver) ||\n type.isDef(error) ||\n type.isDef(complete);\n if (asFunctions) {\n this.next = nextOrObserver as NextFn<T> | null;\n this.error = error || null;\n this.complete = complete || null;\n } else {\n const observer = nextOrObserver as {\n next?: NextFn<T> | 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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { 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","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 MetadataUtils from './metadata';\nimport * as ListOptionsUtils from './list';\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(\n name: string,\n specs: ArgSpec[],\n passed: IArguments\n): void {\n let minArgs = specs.length;\n const 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 const 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: unknown) => void;\n optional: boolean;\n\n constructor(validator: (p1: unknown) => void, optional?: boolean) {\n const self = this;\n this.validator = function(p: unknown) {\n if (self.optional && !type.isJustDef(p)) {\n return;\n }\n validator(p);\n };\n this.optional = !!optional;\n }\n}\n\nexport function and_(\n v1: (p1: unknown) => void,\n v2: (p1: unknown) => void\n): (p1: unknown) => void {\n return function(p) {\n v1(p);\n v2(p);\n };\n}\n\nexport function stringSpec(\n validator?: (p1: unknown) => void | null,\n optional?: boolean\n): ArgSpec {\n function stringValidator(p: unknown): void {\n if (!type.isString(p)) {\n throw 'Expected string.';\n }\n }\n let chainedValidator;\n if (validator) {\n chainedValidator = and_(stringValidator, validator);\n } else {\n chainedValidator = stringValidator;\n }\n return new ArgSpec(chainedValidator, optional);\n}\n\nexport function uploadDataSpec(): ArgSpec {\n function validator(p: unknown): void {\n const 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(optional?: boolean): ArgSpec {\n return new ArgSpec(MetadataUtils.metadataValidator, optional);\n}\n\nexport function listOptionSpec(optional?: boolean): ArgSpec {\n return new ArgSpec(ListOptionsUtils.listOptionsValidator, optional);\n}\n\nexport function nonNegativeNumberSpec(): ArgSpec {\n function validator(p: unknown): void {\n const 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 validator?: ((p1: unknown) => void) | null,\n optional?: boolean\n): ArgSpec {\n function isLooseObjectValidator(p: unknown): void {\n const isLooseObject = p === null || (type.isDef(p) && p instanceof Object);\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n if (validator !== undefined && validator !== null) {\n validator(p);\n }\n }\n return new ArgSpec(isLooseObjectValidator, optional);\n}\n\nexport function nullFunctionSpec(optional?: boolean): ArgSpec {\n function validator(p: unknown): void {\n const valid = p === null || type.isFunction(p);\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n return new ArgSpec(validator, optional);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 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 (...argsToForward: unknown[]) => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => f(...argsToForward));\n };\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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, Code, canceled } from './implementation/error';\nimport {\n InternalTaskState,\n TaskEvent,\n TaskState,\n taskStateFromInternalTaskState\n} from './implementation/taskenums';\nimport { Metadata } from './metadata';\nimport {\n CompleteFn,\n ErrorFn,\n NextFn,\n Observer,\n StorageObserver,\n Subscribe,\n Unsubscribe\n} from './implementation/observer';\nimport { Request } from './implementation/request';\nimport { UploadTaskSnapshot } from './tasksnapshot';\nimport {\n ArgSpec,\n nullFunctionSpec,\n looseObjectSpec,\n stringSpec,\n validate\n} from './implementation/args';\nimport { async as fbsAsync } from './implementation/async';\nimport { Location } from './implementation/location';\nimport * as fbsMetadata from './implementation/metadata';\nimport * as fbsRequests from './implementation/requests';\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_: Array<Observer<UploadTaskSnapshot>> = [];\n private resumable_: boolean;\n private state_: InternalTaskState;\n private error_: Error | null = null;\n private uploadUrl_: string | null = null;\n private request_: Request<unknown> | 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<UploadTaskSnapshot>;\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(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(Code.CANCELED)) {\n this.completeTransitions_();\n } else {\n this.error_ = error;\n this.transition_(InternalTaskState.ERROR);\n }\n };\n this.promise_ = new Promise((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 => this.updateProgress_(sizeBefore + loaded);\n }\n\n private shouldDoResumable_(blob: FbsBlob): boolean {\n return blob.size() > 256 * 1024;\n }\n\n private start_(): void {\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): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\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_(): void {\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_(): void {\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_(): void {\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_(): void {\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_(): void {\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_(): void {\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): void {\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): void {\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_ = 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 default: // Ignore\n }\n }\n\n private completeTransitions_(): void {\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 = taskStateFromInternalTaskState(this.state_);\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?:\n | NextFn<UploadTaskSnapshot>\n | StorageObserver<UploadTaskSnapshot>\n | null,\n error?: ErrorFn | null,\n completed?: CompleteFn | null\n ): Unsubscribe | Subscribe<UploadTaskSnapshot> {\n function typeValidator(): void {\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 = nullFunctionSpec(true).validator;\n const observerValidator = looseObjectSpec(null, true).validator;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function nextOrObserverValidator(p: any): void {\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 stringSpec(typeValidator),\n looseObjectSpec(nextOrObserverValidator, true),\n nullFunctionSpec(true),\n nullFunctionSpec(true)\n ];\n validate('on', specs, arguments);\n const self = this;\n\n function makeBinder(\n specs: ArgSpec[] | null\n ): Subscribe<UploadTaskSnapshot> {\n function binder(\n nextOrObserver?:\n | NextFn<UploadTaskSnapshot>\n | StorageObserver<UploadTaskSnapshot>\n | null,\n error?: ErrorFn | null,\n complete?: CompleteFn | null\n ): () => void {\n if (specs !== null) {\n 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: unknown): void {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n nextOrObserverValidator(p);\n }\n const binderSpecs = [\n looseObjectSpec(binderNextOrObserverValidator),\n nullFunctionSpec(true),\n 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<U>(\n onFulfilled?: ((value: UploadTaskSnapshot) => U | Promise<U>) | null,\n onRejected?: ((error: Error) => U | Promise<U>) | null\n ): Promise<U> {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then<U>(\n onFulfilled as (value: UploadTaskSnapshot) => U | Promise<U>,\n onRejected as ((error: unknown) => Promise<never>) | null\n );\n }\n\n /**\n * Equivalent to calling `then(null, onRejected)`.\n */\n catch<T>(onRejected: (p1: Error) => T | Promise<T>): Promise<T> {\n return this.then(null, onRejected);\n }\n\n /**\n * Adds the given observer.\n */\n private addObserver_(observer: Observer<UploadTaskSnapshot>): void {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n }\n\n /**\n * Removes the given observer.\n */\n private removeObserver_(observer: Observer<UploadTaskSnapshot>): void {\n const i = this.observers_.indexOf(observer);\n if (i !== -1) {\n this.observers_.splice(i, 1);\n }\n }\n\n private notifyObservers_(): void {\n this.finishPromise_();\n const observers = this.observers_.slice();\n observers.forEach(observer => {\n this.notifyObserver_(observer);\n });\n }\n\n private finishPromise_(): void {\n if (this.resolve_ !== null) {\n let triggered = true;\n switch (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<UploadTaskSnapshot>): void {\n const externalState = taskStateFromInternalTaskState(this.state_);\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next) {\n fbsAsync(observer.next.bind(observer, this.snapshot))();\n }\n break;\n case TaskState.SUCCESS:\n if (observer.complete) {\n fbsAsync(observer.complete.bind(observer))();\n }\n break;\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error) {\n fbsAsync(observer.error.bind(observer, this.error_ as Error))();\n }\n break;\n default:\n // TODO(andysoto): assert(false);\n if (observer.error) {\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 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 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 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 * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { AuthWrapper } from './implementation/authwrapper';\nimport { FbsBlob } from './implementation/blob';\nimport * as errorsExports from './implementation/error';\nimport { Location } from './implementation/location';\nimport * as metadata from './implementation/metadata';\nimport * as path from './implementation/path';\nimport * as requests from './implementation/requests';\nimport {\n StringFormat,\n formatValidator,\n dataFromString\n} from './implementation/string';\nimport * as type from './implementation/type';\nimport { Metadata } from './metadata';\nimport { Service } from './service';\nimport { UploadTask } from './task';\nimport { ListOptions, ListResult } from './list';\nimport {\n listOptionSpec,\n stringSpec,\n validate,\n metadataSpec,\n uploadDataSpec\n} from './implementation/args';\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://<bucket>/<object-path>\n * http[s]://firebasestorage.googleapis.com/\n * <api-version>/b/<bucket>/o/<object-path>\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://<bucket>/<object-path>\n * @override\n */\n toString(): string {\n 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 validate('child', [stringSpec()], arguments);\n const newPath = path.child(this.location.path, childPath);\n const 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 const newPath = path.parent(this.location.path);\n if (newPath === null) {\n return null;\n }\n const 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 const 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 validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\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 value The string to upload.\n * @param 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 value: string,\n format: StringFormat = StringFormat.RAW,\n metadata?: Metadata\n ): UploadTask {\n validate(\n 'putString',\n [stringSpec(), stringSpec(formatValidator, true), metadataSpec(true)],\n arguments\n );\n this.throwIfRoot_('putString');\n const data = dataFromString(format, value);\n const metadataClone = Object.assign({}, metadata);\n if (\n !type.isDef(metadataClone['contentType']) &&\n type.isDef(data.contentType)\n ) {\n metadataClone['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 metadataClone\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<void> {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.deleteObject(\n this.authWrapper,\n this.location\n );\n return this.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n }\n\n /**\n * List all items (files) and prefixes (folders) under this storage reference.\n *\n * This is a helper method for calling list() repeatedly until there are\n * no more results. The default pagination size is 1000.\n *\n * Note: The results may not be consistent if objects are changed while this\n * operation is running.\n *\n * Warning: listAll may potentially consume too many resources if there are\n * too many results.\n *\n * @return A Promise that resolves with all the items and prefixes under\n * the current storage reference. `prefixes` contains references to\n * sub-directories and `items` contains references to objects in this\n * folder. `nextPageToken` is never returned.\n */\n listAll(): Promise<ListResult> {\n validate('listAll', [], arguments);\n const accumulator = {\n prefixes: [],\n items: []\n };\n return this.listAllHelper(accumulator).then(() => accumulator);\n }\n\n private async listAllHelper(\n accumulator: ListResult,\n pageToken?: string\n ): Promise<void> {\n const opt: ListOptions = {\n // maxResults is 1000 by default.\n pageToken\n };\n const nextPage = await this.list(opt);\n accumulator.prefixes.push(...nextPage.prefixes);\n accumulator.items.push(...nextPage.items);\n if (nextPage.nextPageToken != null) {\n await this.listAllHelper(accumulator, nextPage.nextPageToken);\n }\n }\n\n /**\n * List items (files) and prefixes (folders) under this storage reference.\n *\n * List API is only available for Firebase Rules Version 2.\n *\n * GCS is a key-blob store. Firebase Storage imposes the semantic of '/'\n * delimited folder structure.\n * Refer to GCS's List API if you want to learn more.\n *\n * To adhere to Firebase Rules's Semantics, Firebase Storage does not\n * support objects whose paths end with \"/\" or contain two consecutive\n * \"/\"s. Firebase Storage List API will filter these unsupported objects.\n * list() may fail if there are too many unsupported objects in the bucket.\n *\n * @param options See ListOptions for details.\n * @return A Promise that resolves with the items and prefixes.\n * `prefixes` contains references to sub-folders and `items`\n * contains references to objects in this folder. `nextPageToken`\n * can be used to get the rest of the results.\n */\n list(options?: ListOptions | null): Promise<ListResult> {\n validate('list', [listOptionSpec(true)], arguments);\n const self = this;\n return this.authWrapper.getAuthToken().then(authToken => {\n const op = options || {};\n const requestInfo = requests.list(\n self.authWrapper,\n self.location,\n /*delimiter= */ '/',\n op.pageToken,\n op.maxResults\n );\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<Metadata> {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.getMetadata(\n this.authWrapper,\n this.location,\n this.mappings()\n );\n return this.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<Metadata> {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.updateMetadata(\n this.authWrapper,\n this.location,\n metadata,\n this.mappings()\n );\n return this.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<string> {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n return this.authWrapper.getAuthToken().then(authToken => {\n const requestInfo = requests.getDownloadUrl(\n this.authWrapper,\n this.location,\n this.mappings()\n );\n return this.authWrapper\n .makeRequest(requestInfo, authToken)\n .getPromise()\n .then(url => {\n if (url === null) {\n throw errorsExports.noDownloadURL();\n }\n return url;\n });\n });\n }\n\n private throwIfRoot_(name: string): void {\n if (this.location.path === '') {\n throw errorsExports.invalidRootOperation(name);\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Request } from './request';\n\n/**\n * A request whose promise always fails.\n * @struct\n * @template T\n */\nexport class FailRequest<T> implements Request<T> {\n promise_: Promise<T>;\n\n constructor(error: FirebaseStorageError) {\n this.promise_ = Promise.reject<T>(error);\n }\n\n /** @inheritDoc */\n getPromise(): Promise<T> {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(_appDelete = false): void {}\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Request } from './request';\nimport * as constants from './constants';\n\nexport class RequestMap {\n private readonly map: Map<number, Request<unknown>> = new Map();\n private id: number;\n\n constructor() {\n this.id = constants.MIN_SAFE_INTEGER;\n }\n\n /**\n * Registers the given request with this map.\n * The request is unregistered when it completes.\n *\n * @param request The request to register.\n */\n addRequest(request: Request<unknown>): void {\n const id = this.id;\n this.id++;\n this.map.set(id, request);\n\n request.getPromise().then(\n () => this.map.delete(id),\n () => this.map.delete(id)\n );\n }\n\n /**\n * Cancels all registered requests.\n */\n clear(): void {\n this.map.forEach(v => {\n v && v.cancel(true);\n });\n this.map.clear();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FailRequest } from './failrequest';\nimport { Location } from './location';\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, FirebaseOptions } from '@firebase/app-types';\nimport {\n _FirebaseApp,\n FirebaseAuthTokenData\n} from '@firebase/app-types/private';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\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 authProvider_: Provider<FirebaseAuthInternalName>;\n private bucket_: string | null = null;\n private appId_: string | null = null;\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 authProvider: Provider<FirebaseAuthInternalName>,\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 const options = this.app_.options;\n if (type.isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n this.appId_ = options.appId ?? null;\n }\n }\n this.authProvider_ = authProvider;\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = constants.DEFAULT_MAX_OPERATION_RETRY_TIME;\n this.maxUploadRetryTime_ = constants.DEFAULT_MAX_UPLOAD_RETRY_TIME;\n this.requestMap_ = new RequestMap();\n }\n\n private static extractBucket_(config: FirebaseOptions): string | null {\n const bucketString = config[constants.CONFIG_STORAGE_BUCKET_KEY] || null;\n if (bucketString == null) {\n return null;\n }\n const loc: Location = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n }\n\n getAuthToken(): Promise<string | null> {\n const auth = this.authProvider_.getImmediate({ optional: true });\n if (auth) {\n return auth.getToken().then(\n (response: FirebaseAuthTokenData | null): string | null => {\n if (response !== null) {\n return response.accessToken;\n } else {\n return null;\n }\n },\n () => null\n );\n } else {\n return Promise.resolve(null);\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<T>(\n requestInfo: RequestInfo<T>,\n authToken: string | null\n ): Request<T> {\n if (!this.deleted_) {\n const request = this.requestMaker_(\n requestInfo,\n this.appId_,\n authToken,\n this.pool_\n );\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(): void {\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): void {\n this.maxUploadRetryTime_ = time;\n }\n\n maxOperationRetryTime(): number {\n return this.maxOperationRetryTime_;\n }\n\n setMaxOperationRetryTime(time: number): void {\n this.maxOperationRetryTime_ = time;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 */\n\nimport firebase from '@firebase/app';\nimport * as backoff from './backoff';\nimport {\n FirebaseStorageError,\n unknown,\n appDeleted,\n canceled,\n retryLimitExceeded\n} from './error';\nimport { RequestInfo } from './requestinfo';\nimport * as type from './type';\nimport * as UrlUtils from './url';\nimport { Headers, XhrIo, ErrorCode } from './xhrio';\nimport { XhrIoPool } from './xhriopool';\n\n/**\n * @template T\n */\nexport interface Request<T> {\n getPromise(): Promise<T>;\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<T> implements Request<T> {\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<T>;\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 this.promise_ = new Promise((resolve, reject) => {\n this.resolve_ = resolve;\n this.reject_ = reject;\n this.start_();\n });\n }\n\n /**\n * Actually starts the retry loop.\n */\n private start_(): void {\n const self = this;\n\n function doTheRequest(\n backoffCallback: (p1: boolean, ...p2: unknown[]) => void,\n canceled: boolean\n ): void {\n if (canceled) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n const xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n\n function progressListener(progressEvent: ProgressEvent): void {\n const loaded = progressEvent.loaded;\n const 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\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n xhr\n .send(self.url_, self.method_, self.body_, self.headers_)\n .then((xhr: XhrIo) => {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n self.pendingXhr_ = null;\n xhr = xhr as XhrIo;\n const hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n const status = xhr.getStatus();\n if (!hitServer || self.isRetryStatusCode_(status)) {\n const wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(\n false,\n new RequestEndStatus(false, null, wasCanceled)\n );\n return;\n }\n const successCode = self.successCodes_.indexOf(status) !== -1;\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 ): void {\n const resolve = self.resolve_ as Function;\n const reject = self.reject_ as Function;\n const xhr = status.xhr as XhrIo;\n if (status.wasSuccessCode) {\n try {\n const 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 const 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 const err = self.appDelete_ ? appDeleted() : canceled();\n reject(err);\n } else {\n const 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_ = backoff.start(doTheRequest, backoffDone, this.timeout_);\n }\n }\n\n /** @inheritDoc */\n getPromise(): Promise<T> {\n return this.promise_;\n }\n\n /** @inheritDoc */\n cancel(appDelete?: boolean): void {\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 const isFiveHundredCode = status >= 500 && status < 600;\n const 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 const isExtraRetryCode = extraRetryCodes.indexOf(status) !== -1;\n const isRequestSpecificRetryCode =\n this.additionalRetryCodes_.indexOf(status) !== -1;\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 canceled?: boolean\n ) {\n this.canceled = !!canceled;\n }\n}\n\nexport function addAuthHeader_(\n headers: Headers,\n authToken: string | null\n): void {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\n\nexport function addVersionHeader_(headers: Headers): void {\n const version =\n typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + version;\n}\n\nexport function addGmpidHeader_(headers: Headers, appId: string | null): void {\n if (appId) {\n headers['X-Firebase-GMPID'] = appId;\n }\n}\n\n/**\n * @template T\n */\nexport function makeRequest<T>(\n requestInfo: RequestInfo<T>,\n appId: string | null,\n authToken: string | null,\n pool: XhrIoPool\n): Request<T> {\n const queryPart = UrlUtils.makeQueryString(requestInfo.urlParams);\n const url = requestInfo.url + queryPart;\n const headers = Object.assign({}, requestInfo.headers);\n addGmpidHeader_(headers, appId);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest<T>(\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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: (p1: (success: boolean) => void, canceled: boolean) => 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 // TODO: find a way to exclude Node type definition for storage because storage only works in browser\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let timeoutId: any = null;\n let hitTimeout = false;\n let cancelState = 0;\n\n function canceled(): boolean {\n return cancelState === 2;\n }\n let triggeredCallback = false;\n\n // TODO: This disable can be removed and the 'ignoreRestArgs' option added to\n // the no-explicit-any rule when ESlint releases it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function triggerCallback(...args: any[]): void {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, args);\n }\n }\n\n function callWithDelay(millis: number): void {\n timeoutId = setTimeout(() => {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n\n // TODO: This disable can be removed and the 'ignoreRestArgs' option added to\n // the no-explicit-any rule when ESlint releases it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n function handler(success: boolean, ...args: any[]): void {\n if (triggeredCallback) {\n return;\n }\n if (success) {\n triggerCallback.call(null, success, ...args);\n return;\n }\n const mustStop = canceled() || hitTimeout;\n if (mustStop) {\n triggerCallback.call(null, success, ...args);\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(() => {\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): void {\n id(false);\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app-types';\nimport * as args from './implementation/args';\nimport { AuthWrapper } from './implementation/authwrapper';\nimport { Location } from './implementation/location';\nimport * as RequestExports from './implementation/request';\nimport { XhrIoPool } from './implementation/xhriopool';\nimport { Reference } from './reference';\nimport { Provider } from '@firebase/component';\nimport { FirebaseAuthInternalName } from '@firebase/auth-interop-types';\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(\n app: FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>,\n pool: XhrIoPool,\n url?: string\n ) {\n function maker(authWrapper: AuthWrapper, loc: Location): Reference {\n return new Reference(authWrapper, loc);\n }\n this.authWrapper_ = new AuthWrapper(\n app,\n authProvider,\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: unknown): void {\n if (typeof path !== 'string') {\n throw 'Path is not a string.';\n }\n if (/^[A-Za-z]+:\\/\\//.test(path as string)) {\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 const 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: unknown): void {\n if (typeof p !== 'string') {\n throw 'Path is not a string.';\n }\n if (!/^[A-Za-z]+:\\/\\//.test(p as string)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n try {\n Location.makeFromUrl(p as string);\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): void {\n args.validate(\n 'setMaxUploadRetryTime',\n [args.nonNegativeNumberSpec()],\n arguments\n );\n this.authWrapper_.setMaxUploadRetryTime(time);\n }\n\n setMaxOperationRetryTime(time: number): void {\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<void> {\n this.service_.authWrapper_.deleteApp();\n return Promise.resolve();\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { StringFormat } from './src/implementation/string';\nimport { TaskEvent, TaskState } from './src/implementation/taskenums';\n\nimport { XhrIoPool } from './src/implementation/xhriopool';\nimport { Reference } from './src/reference';\nimport { Service } from './src/service';\nimport * as types from '@firebase/storage-types';\nimport {\n Component,\n ComponentType,\n ComponentContainer\n} from '@firebase/component';\n\nimport { name, version } from './package.json';\n\n/**\n * Type constant for Firebase Storage.\n */\nconst STORAGE_TYPE = 'storage';\n\nfunction factory(\n container: ComponentContainer,\n url?: string\n): types.FirebaseStorage {\n // Dependencies\n const app = container.getProvider('app').getImmediate();\n const authProvider = container.getProvider('auth-internal');\n\n return (new Service(\n app,\n authProvider,\n new XhrIoPool(),\n url\n ) as unknown) as types.FirebaseStorage;\n}\n\nexport function registerStorage(instance: _FirebaseNamespace): void {\n const namespaceExports = {\n // no-inline\n TaskState,\n TaskEvent,\n StringFormat,\n Storage: Service,\n Reference\n };\n instance.INTERNAL.registerComponent(\n new Component(STORAGE_TYPE, factory, ComponentType.PUBLIC)\n .setServiceProps(namespaceExports)\n .setMultipleInstances(true)\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterStorage(firebase as _FirebaseNamespace);\n\n/**\n * Define extension behavior for `registerStorage`\n */\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n storage?: {\n (app?: FirebaseApp): types.FirebaseStorage;\n Storage: typeof types.FirebaseStorage;\n\n StringFormat: {\n BASE64: types.StringFormat;\n BASE64URL: types.StringFormat;\n DATA_URL: types.StringFormat;\n RAW: types.StringFormat;\n };\n TaskEvent: {\n STATE_CHANGED: types.TaskEvent;\n };\n TaskState: {\n CANCELED: types.TaskState;\n ERROR: types.TaskState;\n PAUSED: types.TaskState;\n RUNNING: types.TaskState;\n SUCCESS: types.TaskState;\n };\n };\n }\n interface FirebaseApp {\n storage?(storageBucket?: string): types.FirebaseStorage;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ERROR_FACTORY, ErrorCode } from '../utils/errors';\n\ndeclare global {\n interface Window {\n PerformanceObserver: typeof PerformanceObserver;\n perfMetrics?: { onFirstInputDelay: Function };\n }\n}\n\nlet apiInstance: Api | undefined;\nlet windowInstance: Window | undefined;\n\nexport type EntryType =\n | 'mark'\n | 'measure'\n | 'paint'\n | 'resource'\n | 'frame'\n | 'navigation';\n\n/**\n * This class holds a reference to various browser related objects injected by\n * set methods.\n */\nexport class Api {\n private readonly performance: Performance;\n /** PreformanceObserver constructor function. */\n private readonly PerformanceObserver: typeof PerformanceObserver;\n private readonly windowLocation: Location;\n readonly onFirstInputDelay?: Function;\n readonly localStorage?: Storage;\n readonly document: Document;\n readonly navigator: Navigator;\n\n constructor(readonly window?: Window) {\n if (!window) {\n throw ERROR_FACTORY.create(ErrorCode.NO_WINDOW);\n }\n this.performance = window.performance;\n this.PerformanceObserver = window.PerformanceObserver;\n this.windowLocation = window.location;\n this.navigator = window.navigator;\n this.document = window.document;\n if (this.navigator && this.navigator.cookieEnabled) {\n // If user blocks cookies on the browser, accessing localStorage will\n // throw an exception.\n this.localStorage = window.localStorage;\n }\n if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) {\n this.onFirstInputDelay = window.perfMetrics.onFirstInputDelay;\n }\n }\n\n getUrl(): string {\n // Do not capture the string query part of url.\n return this.windowLocation.href.split('?')[0];\n }\n\n mark(name: string): void {\n if (!this.performance || !this.performance.mark) {\n return;\n }\n this.performance.mark(name);\n }\n\n measure(measureName: string, mark1: string, mark2: string): void {\n if (!this.performance || !this.performance.measure) {\n return;\n }\n this.performance.measure(measureName, mark1, mark2);\n }\n\n getEntriesByType(type: EntryType): PerformanceEntry[] {\n if (!this.performance || !this.performance.getEntriesByType) {\n return [];\n }\n return this.performance.getEntriesByType(type);\n }\n\n getEntriesByName(name: string): PerformanceEntry[] {\n if (!this.performance || !this.performance.getEntriesByName) {\n return [];\n }\n return this.performance.getEntriesByName(name);\n }\n\n getTimeOrigin(): number {\n // Polyfill the time origin with performance.timing.navigationStart.\n return (\n this.performance &&\n (this.performance.timeOrigin || this.performance.timing.navigationStart)\n );\n }\n\n requiredApisAvailable(): boolean {\n if (fetch && Promise && this.navigator && this.navigator.cookieEnabled) {\n return true;\n }\n return false;\n }\n\n setupObserver(\n entryType: EntryType,\n callback: (entry: PerformanceEntry) => void\n ): void {\n if (!this.PerformanceObserver) {\n return;\n }\n const observer = new this.PerformanceObserver(list => {\n for (const entry of list.getEntries()) {\n // `entry` is a PerformanceEntry instance.\n callback(entry);\n }\n });\n\n // Start observing the entry types you care about.\n observer.observe({ entryTypes: [entryType] });\n }\n\n static getInstance(): Api {\n if (apiInstance === undefined) {\n apiInstance = new Api(windowInstance);\n }\n return apiInstance;\n }\n}\n\nexport function setupApi(window: Window): void {\n windowInstance = window;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app-types';\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\nimport { FirebaseInstallations } from '@firebase/installations-types';\n\nlet settingsServiceInstance: SettingsService | undefined;\n\nexport class SettingsService {\n // The variable which controls logging of automatic traces and HTTP/S network monitoring.\n instrumentationEnabled = true;\n\n // The variable which controls logging of custom traces.\n dataCollectionEnabled = true;\n\n // Configuration flags set through remote config.\n loggingEnabled = false;\n // Sampling rate between 0 and 1.\n tracesSamplingRate = 1;\n networkRequestsSamplingRate = 1;\n // Address of logging service.\n logEndPointUrl =\n 'https://firebaselogging.googleapis.com/v0cc/log?format=json_proto';\n logSource = 462;\n\n // Flags which control per session logging of traces and network requests.\n logTraceAfterSampling = false;\n logNetworkAfterSampling = false;\n\n // TTL of config retrieved from remote config in hours.\n configTimeToLive = 12;\n\n firebaseAppInstance!: FirebaseApp;\n\n installationsService!: FirebaseInstallations;\n\n getAppId(): string {\n const appId =\n this.firebaseAppInstance &&\n this.firebaseAppInstance.options &&\n this.firebaseAppInstance.options.appId;\n if (!appId) {\n throw ERROR_FACTORY.create(ErrorCode.NO_APP_ID);\n }\n return appId;\n }\n\n getProjectId(): string {\n const projectId =\n this.firebaseAppInstance &&\n this.firebaseAppInstance.options &&\n this.firebaseAppInstance.options.projectId;\n if (!projectId) {\n throw ERROR_FACTORY.create(ErrorCode.NO_PROJECT_ID);\n }\n return projectId;\n }\n\n getApiKey(): string {\n const apiKey =\n this.firebaseAppInstance &&\n this.firebaseAppInstance.options &&\n this.firebaseAppInstance.options.apiKey;\n if (!apiKey) {\n throw ERROR_FACTORY.create(ErrorCode.NO_API_KEY);\n }\n return apiKey;\n }\n\n static getInstance(): SettingsService {\n if (settingsServiceInstance === undefined) {\n settingsServiceInstance = new SettingsService();\n }\n return settingsServiceInstance;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { version } from '../package.json';\n\nexport const SDK_VERSION = version;\n/** The prefix for start User Timing marks used for creating Traces. */\nexport const TRACE_START_MARK_PREFIX = 'FB-PERF-TRACE-START';\n/** The prefix for stop User Timing marks used for creating Traces. */\nexport const TRACE_STOP_MARK_PREFIX = 'FB-PERF-TRACE-STOP';\n/** The prefix for User Timing measure used for creating Traces. */\nexport const TRACE_MEASURE_PREFIX = 'FB-PERF-TRACE-MEASURE';\n/** The prefix for out of the box page load Trace name. */\nexport const OOB_TRACE_PAGE_LOAD_PREFIX = '_wt_';\n\nexport const FIRST_PAINT_COUNTER_NAME = '_fp';\n\nexport const FIRST_CONTENTFUL_PAINT_COUNTER_NAME = '_fcp';\n\nexport const FIRST_INPUT_DELAY_COUNTER_NAME = '_fid';\n\nexport const CONFIG_LOCAL_STORAGE_KEY = '@firebase/performance/config';\n\nexport const CONFIG_EXPIRY_LOCAL_STORAGE_KEY =\n '@firebase/performance/configexpire';\n\nexport const SERVICE = 'performance';\nexport const SERVICE_NAME = 'Performance';\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ErrorFactory } from '@firebase/util';\nimport { SERVICE, SERVICE_NAME } from '../constants';\n\nexport const enum ErrorCode {\n TRACE_STARTED_BEFORE = 'trace started',\n TRACE_STOPPED_BEFORE = 'trace stopped',\n NO_WINDOW = 'no window',\n NO_APP_ID = 'no app id',\n NO_PROJECT_ID = 'no project id',\n NO_API_KEY = 'no api key',\n INVALID_CC_LOG = 'invalid cc log',\n FB_NOT_DEFAULT = 'FB not default',\n RC_NOT_OK = 'RC response not ok',\n INVALID_ATTRIBUTE_NAME = 'invalid attribute name',\n INVALID_ATTRIBUTE_VALUE = 'invalid attribute value',\n INVALID_CUSTOM_METRIC_NAME = 'invalide custom metric name'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.TRACE_STARTED_BEFORE]: 'Trace {$traceName} was started before.',\n [ErrorCode.TRACE_STOPPED_BEFORE]: 'Trace {$traceName} is not running.',\n [ErrorCode.NO_WINDOW]: 'Window is not available.',\n [ErrorCode.NO_APP_ID]: 'App id is not available.',\n [ErrorCode.NO_PROJECT_ID]: 'Project id is not available.',\n [ErrorCode.NO_API_KEY]: 'Api key is not available.',\n [ErrorCode.INVALID_CC_LOG]: 'Attempted to queue invalid cc event',\n [ErrorCode.FB_NOT_DEFAULT]:\n 'Performance can only start when Firebase app instance is the default one.',\n [ErrorCode.RC_NOT_OK]: 'RC response is not ok',\n [ErrorCode.INVALID_ATTRIBUTE_NAME]:\n 'Attribute name {$attributeName} is invalid.',\n [ErrorCode.INVALID_ATTRIBUTE_VALUE]:\n 'Attribute value {$attributeValue} is invalid.',\n [ErrorCode.INVALID_CUSTOM_METRIC_NAME]:\n 'Custom metric name {$customMetricName} is invalid'\n};\n\ninterface ErrorParams {\n [ErrorCode.TRACE_STARTED_BEFORE]: { traceName: string };\n [ErrorCode.TRACE_STOPPED_BEFORE]: { traceName: string };\n [ErrorCode.INVALID_ATTRIBUTE_NAME]: { attributeName: string };\n [ErrorCode.INVALID_ATTRIBUTE_VALUE]: { attributeValue: string };\n [ErrorCode.INVALID_CUSTOM_METRIC_NAME]: { customMetricName: string };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n SERVICE,\n SERVICE_NAME,\n ERROR_DESCRIPTION_MAP\n);\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SettingsService } from './settings_service';\n\nlet iid: string | undefined;\nlet authToken: string | undefined;\n\nexport function getIidPromise(): Promise<string> {\n const iidPromise = SettingsService.getInstance().installationsService.getId();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n iidPromise.then((iidVal: string) => {\n iid = iidVal;\n });\n return iidPromise;\n}\n\n// This method should be used after the iid is retrieved by getIidPromise method.\nexport function getIid(): string | undefined {\n return iid;\n}\n\nexport function getAuthTokenPromise(): Promise<string> {\n const authTokenPromise = SettingsService.getInstance().installationsService.getToken();\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n authTokenPromise.then((authTokenVal: string) => {\n authToken = authTokenVal;\n });\n return authTokenPromise;\n}\n\nexport function getAuthenticationToken(): string | undefined {\n return authToken;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Api } from '../services/api_service';\n\n// The values and orders of the following enums should not be changed.\nconst enum ServiceWorkerStatus {\n UNKNOWN = 0,\n UNSUPPORTED = 1,\n CONTROLLED = 2,\n UNCONTROLLED = 3\n}\n\nexport enum VisibilityState {\n UNKNOWN = 0,\n VISIBLE = 1,\n HIDDEN = 2\n}\n\nconst enum EffectiveConnectionType {\n UNKNOWN = 0,\n CONNECTION_SLOW_2G = 1,\n CONNECTION_2G = 2,\n CONNECTION_3G = 3,\n CONNECTION_4G = 4\n}\n\n/**\n * NetworkInformation\n *\n * ref: https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation\n */\ninterface NetworkInformation {\n readonly effectiveType?: 'slow-2g' | '2g' | '3g' | '4g';\n}\n\ninterface NavigatorWithConnection extends Navigator {\n readonly connection: NetworkInformation;\n}\n\nconst RESERVED_ATTRIBUTE_PREFIXES = ['firebase_', 'google_', 'ga_'];\nconst ATTRIBUTE_FORMAT_REGEX = new RegExp('^[a-zA-Z]\\\\w*$');\nconst MAX_ATTRIBUTE_NAME_LENGTH = 40;\nconst MAX_ATTRIBUTE_VALUE_LENGTH = 100;\n\nexport function getServiceWorkerStatus(): ServiceWorkerStatus {\n const navigator = Api.getInstance().navigator;\n if ('serviceWorker' in navigator) {\n if (navigator.serviceWorker.controller) {\n return ServiceWorkerStatus.CONTROLLED;\n } else {\n return ServiceWorkerStatus.UNCONTROLLED;\n }\n } else {\n return ServiceWorkerStatus.UNSUPPORTED;\n }\n}\n\nexport function getVisibilityState(): VisibilityState {\n const document = Api.getInstance().document;\n const visibilityState = document.visibilityState;\n switch (visibilityState) {\n case 'visible':\n return VisibilityState.VISIBLE;\n case 'hidden':\n return VisibilityState.HIDDEN;\n default:\n return VisibilityState.UNKNOWN;\n }\n}\n\nexport function getEffectiveConnectionType(): EffectiveConnectionType {\n const navigator = Api.getInstance().navigator;\n const navigatorConnection = (navigator as NavigatorWithConnection).connection;\n const effectiveType =\n navigatorConnection && navigatorConnection.effectiveType;\n switch (effectiveType) {\n case 'slow-2g':\n return EffectiveConnectionType.CONNECTION_SLOW_2G;\n case '2g':\n return EffectiveConnectionType.CONNECTION_2G;\n case '3g':\n return EffectiveConnectionType.CONNECTION_3G;\n case '4g':\n return EffectiveConnectionType.CONNECTION_4G;\n default:\n return EffectiveConnectionType.UNKNOWN;\n }\n}\n\nexport function isValidCustomAttributeName(name: string): boolean {\n if (name.length === 0 || name.length > MAX_ATTRIBUTE_NAME_LENGTH) {\n return false;\n }\n const matchesReservedPrefix = RESERVED_ATTRIBUTE_PREFIXES.some(prefix =>\n name.startsWith(prefix)\n );\n return !matchesReservedPrefix && !!name.match(ATTRIBUTE_FORMAT_REGEX);\n}\n\nexport function isValidCustomAttributeValue(value: string): boolean {\n return value.length !== 0 && value.length <= MAX_ATTRIBUTE_VALUE_LENGTH;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Logger, LogLevel } from '@firebase/logger';\nimport { SERVICE_NAME } from '../constants';\n\nexport const consoleLogger = new Logger(SERVICE_NAME);\nconsoleLogger.logLevel = LogLevel.INFO;\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 CONFIG_EXPIRY_LOCAL_STORAGE_KEY,\n CONFIG_LOCAL_STORAGE_KEY,\n SDK_VERSION\n} from '../constants';\nimport { consoleLogger } from '../utils/console_logger';\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\n\nimport { Api } from './api_service';\nimport { getAuthTokenPromise } from './iid_service';\nimport { SettingsService } from './settings_service';\n\nconst REMOTE_CONFIG_SDK_VERSION = '0.0.1';\n\ninterface SecondaryConfig {\n loggingEnabled?: boolean;\n logEndPointUrl?: string;\n logSource?: number;\n tracesSamplingRate?: number;\n networkRequestsSamplingRate?: number;\n}\n\n// These values will be used if the remote config object is successfully\n// retrieved, but the template does not have these fields.\nconst SECONDARY_CONFIGS: SecondaryConfig = {\n loggingEnabled: true\n};\n\n/* eslint-disable camelcase */\ninterface RemoteConfigTemplate {\n fpr_enabled?: string;\n fpr_log_source?: string;\n fpr_log_endpoint_url?: string;\n fpr_vc_network_request_sampling_rate?: string;\n fpr_vc_trace_sampling_rate?: string;\n fpr_vc_session_sampling_rate?: string;\n}\n/* eslint-enable camelcase */\n\ninterface RemoteConfigResponse {\n entries?: RemoteConfigTemplate;\n state?: string;\n}\n\nconst FIS_AUTH_PREFIX = 'FIREBASE_INSTALLATIONS_AUTH';\n\nexport function getConfig(iid: string): Promise<void> {\n const config = getStoredConfig();\n if (config) {\n processConfig(config);\n return Promise.resolve();\n }\n\n return getRemoteConfig(iid)\n .then(config => processConfig(config))\n .then(\n config => storeConfig(config),\n /** Do nothing for error, use defaults set in settings service. */\n () => {}\n );\n}\n\nfunction getStoredConfig(): RemoteConfigResponse | undefined {\n const localStorage = Api.getInstance().localStorage;\n if (!localStorage) {\n return;\n }\n const expiryString = localStorage.getItem(CONFIG_EXPIRY_LOCAL_STORAGE_KEY);\n if (!expiryString || !configValid(expiryString)) {\n return;\n }\n\n const configStringified = localStorage.getItem(CONFIG_LOCAL_STORAGE_KEY);\n if (!configStringified) {\n return;\n }\n try {\n const configResponse: RemoteConfigResponse = JSON.parse(configStringified);\n return configResponse;\n } catch {\n return;\n }\n}\n\nfunction storeConfig(config: RemoteConfigResponse | undefined): void {\n const localStorage = Api.getInstance().localStorage;\n if (!config || !localStorage) {\n return;\n }\n\n localStorage.setItem(CONFIG_LOCAL_STORAGE_KEY, JSON.stringify(config));\n localStorage.setItem(\n CONFIG_EXPIRY_LOCAL_STORAGE_KEY,\n String(\n Date.now() +\n SettingsService.getInstance().configTimeToLive * 60 * 60 * 1000\n )\n );\n}\n\nconst COULD_NOT_GET_CONFIG_MSG =\n 'Could not fetch config, will use default configs';\n\nfunction getRemoteConfig(\n iid: string\n): Promise<RemoteConfigResponse | undefined> {\n // Perf needs auth token only to retrieve remote config.\n return getAuthTokenPromise()\n .then(authToken => {\n const projectId = SettingsService.getInstance().getProjectId();\n const configEndPoint = `https://firebaseremoteconfig.googleapis.com/v1/projects/${projectId}/namespaces/fireperf:fetch?key=${SettingsService.getInstance().getApiKey()}`;\n const request = new Request(configEndPoint, {\n method: 'POST',\n headers: { Authorization: `${FIS_AUTH_PREFIX} ${authToken}` },\n /* eslint-disable camelcase */\n body: JSON.stringify({\n app_instance_id: iid,\n app_instance_id_token: authToken,\n app_id: SettingsService.getInstance().getAppId(),\n app_version: SDK_VERSION,\n sdk_version: REMOTE_CONFIG_SDK_VERSION\n })\n /* eslint-enable camelcase */\n });\n return fetch(request).then(response => {\n if (response.ok) {\n return response.json() as RemoteConfigResponse;\n }\n // In case response is not ok. This will be caught by catch.\n throw ERROR_FACTORY.create(ErrorCode.RC_NOT_OK);\n });\n })\n .catch(() => {\n consoleLogger.info(COULD_NOT_GET_CONFIG_MSG);\n return undefined;\n });\n}\n\n/**\n * Processes config coming either from calling RC or from local storage.\n * This method only runs if call is successful or config in storage\n * is valie.\n */\nfunction processConfig(\n config: RemoteConfigResponse | undefined\n): RemoteConfigResponse | undefined {\n if (!config) {\n return config;\n }\n const settingsServiceInstance = SettingsService.getInstance();\n const entries = config.entries || {};\n if (entries.fpr_enabled !== undefined) {\n // TODO: Change the assignment of loggingEnabled once the received type is\n // known.\n settingsServiceInstance.loggingEnabled =\n String(entries.fpr_enabled) === 'true';\n } else if (SECONDARY_CONFIGS.loggingEnabled !== undefined) {\n // Config retrieved successfully, but there is no fpr_enabled in template.\n // Use secondary configs value.\n settingsServiceInstance.loggingEnabled = SECONDARY_CONFIGS.loggingEnabled;\n }\n if (entries.fpr_log_source) {\n settingsServiceInstance.logSource = Number(entries.fpr_log_source);\n } else if (SECONDARY_CONFIGS.logSource) {\n settingsServiceInstance.logSource = SECONDARY_CONFIGS.logSource;\n }\n if (entries.fpr_log_endpoint_url) {\n settingsServiceInstance.logEndPointUrl = entries.fpr_log_endpoint_url;\n } else if (SECONDARY_CONFIGS.logEndPointUrl) {\n settingsServiceInstance.logEndPointUrl = SECONDARY_CONFIGS.logEndPointUrl;\n }\n if (entries.fpr_vc_network_request_sampling_rate !== undefined) {\n settingsServiceInstance.networkRequestsSamplingRate = Number(\n entries.fpr_vc_network_request_sampling_rate\n );\n } else if (SECONDARY_CONFIGS.networkRequestsSamplingRate !== undefined) {\n settingsServiceInstance.networkRequestsSamplingRate =\n SECONDARY_CONFIGS.networkRequestsSamplingRate;\n }\n if (entries.fpr_vc_trace_sampling_rate !== undefined) {\n settingsServiceInstance.tracesSamplingRate = Number(\n entries.fpr_vc_trace_sampling_rate\n );\n } else if (SECONDARY_CONFIGS.tracesSamplingRate !== undefined) {\n settingsServiceInstance.tracesSamplingRate =\n SECONDARY_CONFIGS.tracesSamplingRate;\n }\n // Set the per session trace and network logging flags.\n settingsServiceInstance.logTraceAfterSampling = shouldLogAfterSampling(\n settingsServiceInstance.tracesSamplingRate\n );\n settingsServiceInstance.logNetworkAfterSampling = shouldLogAfterSampling(\n settingsServiceInstance.networkRequestsSamplingRate\n );\n return config;\n}\n\nfunction configValid(expiry: string): boolean {\n return Number(expiry) > Date.now();\n}\n\nfunction shouldLogAfterSampling(samplingRate: number): boolean {\n return Math.random() <= samplingRate;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { getIidPromise } from './iid_service';\nimport { getConfig } from './remote_config_service';\nimport { Api } from './api_service';\n\nconst enum InitializationStatus {\n notInitialized = 1,\n initializationPending,\n initialized\n}\n\nlet initializationStatus = InitializationStatus.notInitialized;\n\nlet initializationPromise: Promise<void> | undefined;\n\nexport function getInitializationPromise(): Promise<void> {\n initializationStatus = InitializationStatus.initializationPending;\n\n initializationPromise = initializationPromise || initializePerf();\n\n return initializationPromise;\n}\n\nexport function isPerfInitialized(): boolean {\n return initializationStatus === InitializationStatus.initialized;\n}\n\nfunction initializePerf(): Promise<void> {\n return getDocumentReadyComplete()\n .then(() => getIidPromise())\n .then(iid => getConfig(iid))\n .then(\n () => changeInitializationStatus(),\n () => changeInitializationStatus()\n );\n}\n\n/**\n * Returns a promise which resolves whenever the document readystate is complete or\n * immediately if it is called after page load complete.\n */\nfunction getDocumentReadyComplete(): Promise<void> {\n const document = Api.getInstance().document;\n return new Promise(resolve => {\n if (document && document.readyState !== 'complete') {\n const handler = (): void => {\n if (document.readyState === 'complete') {\n document.removeEventListener('readystatechange', handler);\n resolve();\n }\n };\n document.addEventListener('readystatechange', handler);\n } else {\n resolve();\n }\n });\n}\n\nfunction changeInitializationStatus(): void {\n initializationStatus = InitializationStatus.initialized;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { SettingsService } from './settings_service';\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\nimport { consoleLogger } from '../utils/console_logger';\n\nconst DEFAULT_SEND_INTERVAL_MS = 10 * 1000;\nconst INITIAL_SEND_TIME_DELAY_MS = 5.5 * 1000;\n// If end point does not work, the call will be tried for these many times.\nconst DEFAULT_REMAINING_TRIES = 3;\nlet remainingTries = DEFAULT_REMAINING_TRIES;\n\ninterface BatchEvent {\n message: string;\n eventTime: number;\n}\n\n/* eslint-disable camelcase */\n// CC accepted log format.\ninterface CcBatchLogFormat {\n request_time_ms: string;\n client_info: ClientInfo;\n log_source: number;\n log_event: Log[];\n}\n\ninterface ClientInfo {\n client_type: number;\n js_client_info: {};\n}\n\ninterface Log {\n source_extension_json_proto3: string;\n event_time_ms: string;\n}\n/* eslint-enable camelcase */\n\nlet queue: BatchEvent[] = [];\n\nlet isTransportSetup: boolean = false;\n\nexport function setupTransportService(): void {\n if (!isTransportSetup) {\n processQueue(INITIAL_SEND_TIME_DELAY_MS);\n isTransportSetup = true;\n }\n}\n\nfunction processQueue(timeOffset: number): void {\n setTimeout(() => {\n // If there is no remainingTries left, stop retrying.\n if (remainingTries === 0) {\n return;\n }\n\n // If there are no events to process, wait for DEFAULT_SEND_INTERVAL_MS and try again.\n if (!queue.length) {\n return processQueue(DEFAULT_SEND_INTERVAL_MS);\n }\n\n // Capture a snapshot of the queue and empty the \"official queue\".\n const staged = [...queue];\n queue = [];\n\n /* eslint-disable camelcase */\n // We will pass the JSON serialized event to the backend.\n const log_event: Log[] = staged.map(evt => ({\n source_extension_json_proto3: evt.message,\n event_time_ms: String(evt.eventTime)\n }));\n\n const data: CcBatchLogFormat = {\n request_time_ms: String(Date.now()),\n client_info: {\n client_type: 1, // 1 is JS\n js_client_info: {}\n },\n log_source: SettingsService.getInstance().logSource,\n log_event\n };\n /* eslint-enable camelcase */\n\n fetch(SettingsService.getInstance().logEndPointUrl, {\n method: 'POST',\n body: JSON.stringify(data)\n })\n .then(res => {\n if (!res.ok) {\n consoleLogger.info('Call to Firebase backend failed.');\n }\n return res.json();\n })\n .then(res => {\n const wait = Number(res.next_request_wait_millis);\n\n // Find the next call wait time from the response.\n const requestOffset = isNaN(wait)\n ? DEFAULT_SEND_INTERVAL_MS\n : Math.max(DEFAULT_SEND_INTERVAL_MS, wait);\n remainingTries = DEFAULT_REMAINING_TRIES;\n // Schedule the next process.\n processQueue(requestOffset);\n })\n .catch(() => {\n /**\n * If the request fails for some reason, add the events that were attempted\n * back to the primary queue to retry later.\n */\n queue = [...staged, ...queue];\n remainingTries--;\n consoleLogger.info(`Tries left: ${remainingTries}.`);\n processQueue(DEFAULT_SEND_INTERVAL_MS);\n });\n }, timeOffset);\n}\n\nfunction addToQueue(evt: BatchEvent): void {\n if (!evt.eventTime || !evt.message) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_CC_LOG);\n }\n // Add the new event to the queue.\n queue = [...queue, evt];\n}\n\n/** Log handler for cc service to send the performance logs to the server. */\nexport function transportHandler(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n serializer: (...args: any[]) => string\n): (...args: unknown[]) => void {\n return (...args) => {\n const message = serializer(...args);\n addToQueue({\n message,\n eventTime: Date.now()\n });\n };\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { getIid } from './iid_service';\nimport { NetworkRequest } from '../resources/network_request';\nimport { Trace } from '../resources/trace';\nimport { Api } from './api_service';\nimport { SettingsService } from './settings_service';\nimport {\n getServiceWorkerStatus,\n getVisibilityState,\n VisibilityState,\n getEffectiveConnectionType\n} from '../utils/attributes_utils';\nimport {\n isPerfInitialized,\n getInitializationPromise\n} from './initialization_service';\nimport { transportHandler } from './transport_service';\nimport { SDK_VERSION } from '../constants';\n\nconst enum ResourceType {\n NetworkRequest,\n Trace\n}\n\n/* eslint-disable camelcase */\ninterface ApplicationInfo {\n google_app_id: string;\n app_instance_id?: string;\n web_app_info: WebAppInfo;\n application_process_state: number;\n}\n\ninterface WebAppInfo {\n sdk_version: string;\n page_url: string;\n service_worker_status: number;\n visibility_state: number;\n effective_connection_type: number;\n}\n\ninterface PerfNetworkLog {\n application_info: ApplicationInfo;\n network_request_metric: NetworkRequestMetric;\n}\n\ninterface PerfTraceLog {\n application_info: ApplicationInfo;\n trace_metric: TraceMetric;\n}\n\ninterface NetworkRequestMetric {\n url: string;\n http_method: number;\n http_response_code: number;\n response_payload_bytes?: number;\n client_start_time_us?: number;\n time_to_response_initiated_us?: number;\n time_to_response_completed_us?: number;\n}\n\ninterface TraceMetric {\n name: string;\n is_auto: boolean;\n client_start_time_us: number;\n duration_us: number;\n counters?: { [key: string]: number };\n custom_attributes?: { [key: string]: string };\n}\n\n/* eslint-enble camelcase */\n\nlet logger: (\n resource: NetworkRequest | Trace,\n resourceType: ResourceType\n) => void | undefined;\n// This method is not called before initialization.\nfunction sendLog(\n resource: NetworkRequest | Trace,\n resourceType: ResourceType\n): void {\n if (!logger) {\n logger = transportHandler(serializer);\n }\n logger(resource, resourceType);\n}\n\nexport function logTrace(trace: Trace): void {\n const settingsService = SettingsService.getInstance();\n // Do not log if trace is auto generated and instrumentation is disabled.\n if (!settingsService.instrumentationEnabled && trace.isAuto) {\n return;\n }\n // Do not log if trace is custom and data collection is disabled.\n if (!settingsService.dataCollectionEnabled && !trace.isAuto) {\n return;\n }\n // Do not log if required apis are not available.\n if (!Api.getInstance().requiredApisAvailable()) {\n return;\n }\n // Only log the page load auto traces if page is visible.\n if (trace.isAuto && getVisibilityState() !== VisibilityState.VISIBLE) {\n return;\n }\n\n if (\n !settingsService.loggingEnabled ||\n !settingsService.logTraceAfterSampling\n ) {\n return;\n }\n\n if (isPerfInitialized()) {\n sendTraceLog(trace);\n } else {\n // Custom traces can be used before the initialization but logging\n // should wait until after.\n getInitializationPromise().then(\n () => sendTraceLog(trace),\n () => sendTraceLog(trace)\n );\n }\n}\n\nfunction sendTraceLog(trace: Trace): void {\n if (getIid()) {\n setTimeout(() => sendLog(trace, ResourceType.Trace), 0);\n }\n}\n\nexport function logNetworkRequest(networkRequest: NetworkRequest): void {\n const settingsService = SettingsService.getInstance();\n // Do not log network requests if instrumentation is disabled.\n if (!settingsService.instrumentationEnabled) {\n return;\n }\n // Do not log the js sdk's call to cc service to avoid unnecessary cycle.\n if (networkRequest.url === settingsService.logEndPointUrl.split('?')[0]) {\n return;\n }\n\n if (\n !settingsService.loggingEnabled ||\n !settingsService.logNetworkAfterSampling\n ) {\n return;\n }\n\n setTimeout(() => sendLog(networkRequest, ResourceType.NetworkRequest), 0);\n}\n\nfunction serializer(\n resource: NetworkRequest | Trace,\n resourceType: ResourceType\n): string {\n if (resourceType === ResourceType.NetworkRequest) {\n return serializeNetworkRequest(resource as NetworkRequest);\n }\n return serializeTrace(resource as Trace);\n}\n\nfunction serializeNetworkRequest(networkRequest: NetworkRequest): string {\n const networkRequestMetric: NetworkRequestMetric = {\n url: networkRequest.url,\n http_method: networkRequest.httpMethod || 0,\n http_response_code: 200,\n response_payload_bytes: networkRequest.responsePayloadBytes,\n client_start_time_us: networkRequest.startTimeUs,\n time_to_response_initiated_us: networkRequest.timeToResponseInitiatedUs,\n time_to_response_completed_us: networkRequest.timeToResponseCompletedUs\n };\n const perfMetric: PerfNetworkLog = {\n application_info: getApplicationInfo(),\n network_request_metric: networkRequestMetric\n };\n return JSON.stringify(perfMetric);\n}\n\nfunction serializeTrace(trace: Trace): string {\n const traceMetric: TraceMetric = {\n name: trace.name,\n is_auto: trace.isAuto,\n client_start_time_us: trace.startTimeUs,\n duration_us: trace.durationUs\n };\n\n if (Object.keys(trace.counters).length !== 0) {\n traceMetric.counters = trace.counters;\n }\n const customAttributes = trace.getAttributes();\n if (Object.keys(customAttributes).length !== 0) {\n traceMetric.custom_attributes = customAttributes;\n }\n\n const perfMetric: PerfTraceLog = {\n application_info: getApplicationInfo(),\n trace_metric: traceMetric\n };\n return JSON.stringify(perfMetric);\n}\n\nfunction getApplicationInfo(): ApplicationInfo {\n return {\n google_app_id: SettingsService.getInstance().getAppId(),\n app_instance_id: getIid(),\n web_app_info: {\n sdk_version: SDK_VERSION,\n page_url: Api.getInstance().getUrl(),\n service_worker_status: getServiceWorkerStatus(),\n visibility_state: getVisibilityState(),\n effective_connection_type: getEffectiveConnectionType()\n },\n application_process_state: 0\n };\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 FIRST_PAINT_COUNTER_NAME,\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n FIRST_INPUT_DELAY_COUNTER_NAME,\n OOB_TRACE_PAGE_LOAD_PREFIX\n} from '../constants';\n\nconst MAX_METRIC_NAME_LENGTH = 100;\nconst RESERVED_AUTO_PREFIX = '_';\nconst oobMetrics = [\n FIRST_PAINT_COUNTER_NAME,\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n FIRST_INPUT_DELAY_COUNTER_NAME\n];\n\n/**\n * Returns true if the metric is custom and does not start with reserved prefix, or if\n * the metric is one of out of the box page load trace metrics.\n */\nexport function isValidMetricName(name: string, traceName?: string): boolean {\n if (name.length === 0 || name.length > MAX_METRIC_NAME_LENGTH) {\n return false;\n }\n return (\n (traceName &&\n traceName.startsWith(OOB_TRACE_PAGE_LOAD_PREFIX) &&\n oobMetrics.indexOf(name) > -1) ||\n !name.startsWith(RESERVED_AUTO_PREFIX)\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 TRACE_START_MARK_PREFIX,\n TRACE_STOP_MARK_PREFIX,\n TRACE_MEASURE_PREFIX,\n OOB_TRACE_PAGE_LOAD_PREFIX,\n FIRST_PAINT_COUNTER_NAME,\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n FIRST_INPUT_DELAY_COUNTER_NAME\n} from '../constants';\nimport { Api } from '../services/api_service';\nimport { logTrace } from '../services/perf_logger';\nimport { ERROR_FACTORY, ErrorCode } from '../utils/errors';\nimport {\n isValidCustomAttributeName,\n isValidCustomAttributeValue\n} from '../utils/attributes_utils';\nimport { isValidMetricName } from '../utils/metric_utils';\nimport { PerformanceTrace } from '@firebase/performance-types';\n\nconst enum TraceState {\n UNINITIALIZED = 1,\n RUNNING,\n TERMINATED\n}\n\nexport class Trace implements PerformanceTrace {\n private state: TraceState = TraceState.UNINITIALIZED;\n startTimeUs!: number;\n durationUs!: number;\n private customAttributes: { [key: string]: string } = {};\n counters: { [counterName: string]: number } = {};\n private api = Api.getInstance();\n private randomId = Math.floor(Math.random() * 1000000);\n private traceStartMark!: string;\n private traceStopMark!: string;\n private traceMeasure!: string;\n\n /**\n * @param name The name of the trace.\n * @param isAuto If the trace is auto-instrumented.\n * @param traceMeasureName The name of the measure marker in user timing specification. This field\n * is only set when the trace is built for logging when the user directly uses the user timing\n * api (performance.mark and performance.measure).\n */\n constructor(\n readonly name: string,\n readonly isAuto = false,\n traceMeasureName?: string\n ) {\n if (!this.isAuto) {\n this.traceStartMark = `${TRACE_START_MARK_PREFIX}-${this.randomId}-${this.name}`;\n this.traceStopMark = `${TRACE_STOP_MARK_PREFIX}-${this.randomId}-${this.name}`;\n this.traceMeasure =\n traceMeasureName ||\n `${TRACE_MEASURE_PREFIX}-${this.randomId}-${this.name}`;\n\n if (traceMeasureName) {\n // For the case of direct user timing traces, no start stop will happen. The measure object\n // is already available.\n this.calculateTraceMetrics();\n }\n }\n }\n\n /**\n * Starts a trace. The measurement of the duration starts at this point.\n */\n start(): void {\n if (this.state !== TraceState.UNINITIALIZED) {\n throw ERROR_FACTORY.create(ErrorCode.TRACE_STARTED_BEFORE, {\n traceName: this.name\n });\n }\n this.api.mark(this.traceStartMark);\n this.state = TraceState.RUNNING;\n }\n\n /**\n * Stops the trace. The measurement of the duration of the trace stops at this point and trace\n * is logged.\n */\n stop(): void {\n if (this.state !== TraceState.RUNNING) {\n throw ERROR_FACTORY.create(ErrorCode.TRACE_STOPPED_BEFORE, {\n traceName: this.name\n });\n }\n this.state = TraceState.TERMINATED;\n this.api.mark(this.traceStopMark);\n this.api.measure(\n this.traceMeasure,\n this.traceStartMark,\n this.traceStopMark\n );\n this.calculateTraceMetrics();\n logTrace(this);\n }\n\n /**\n * Records a trace with predetermined values. If this method is used a trace is created and logged\n * directly. No need to use start and stop methods.\n * @param startTime Trace start time since epoch in millisec\n * @param duration The duraction of the trace in millisec\n * @param options An object which can optionally hold maps of custom metrics and custom attributes\n */\n record(\n startTime: number,\n duration: number,\n options?: {\n metrics?: { [key: string]: number };\n attributes?: { [key: string]: string };\n }\n ): void {\n this.durationUs = Math.floor(duration * 1000);\n this.startTimeUs = Math.floor(startTime * 1000);\n if (options && options.attributes) {\n this.customAttributes = { ...options.attributes };\n }\n if (options && options.metrics) {\n for (const metric of Object.keys(options.metrics)) {\n if (!isNaN(Number(options.metrics[metric]))) {\n this.counters[metric] = Number(Math.floor(options.metrics[metric]));\n }\n }\n }\n logTrace(this);\n }\n\n /**\n * Increments a custom metric by a certain number or 1 if number not specified. Will create a new\n * custom metric if one with the given name does not exist.\n * @param counter Name of the custom metric\n * @param num Increment by value\n */\n incrementMetric(counter: string, num = 1): void {\n if (this.counters[counter] === undefined) {\n this.putMetric(counter, 0);\n }\n this.counters[counter] += num;\n }\n\n /**\n * Sets a custom metric to a specified value. Will create a new custom metric if one with the\n * given name does not exist.\n * @param counter Name of the custom metric\n * @param num Set custom metric to this value\n */\n putMetric(counter: string, num: number): void {\n if (isValidMetricName(counter, this.name)) {\n this.counters[counter] = num;\n } else {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_CUSTOM_METRIC_NAME, {\n customMetricName: counter\n });\n }\n }\n\n /**\n * Returns the value of the custom metric by that name. If a custom metric with that name does\n * not exist will return zero.\n * @param counter\n */\n getMetric(counter: string): number {\n return this.counters[counter] || 0;\n }\n\n /**\n * Sets a custom attribute of a trace to a certain value.\n * @param attr\n * @param value\n */\n putAttribute(attr: string, value: string): void {\n const isValidName = isValidCustomAttributeName(attr);\n const isValidValue = isValidCustomAttributeValue(value);\n if (isValidName && isValidValue) {\n this.customAttributes[attr] = value;\n return;\n }\n // Throw appropriate error when the attribute name or value is invalid.\n if (!isValidName) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_ATTRIBUTE_NAME, {\n attributeName: attr\n });\n }\n if (!isValidValue) {\n throw ERROR_FACTORY.create(ErrorCode.INVALID_ATTRIBUTE_VALUE, {\n attributeValue: value\n });\n }\n }\n\n /**\n * Retrieves the value a custom attribute of a trace is set to.\n * @param attr\n */\n getAttribute(attr: string): string | undefined {\n return this.customAttributes[attr];\n }\n\n removeAttribute(attr: string): void {\n if (this.customAttributes[attr] === undefined) {\n return;\n }\n delete this.customAttributes[attr];\n }\n\n getAttributes(): { [key: string]: string } {\n return { ...this.customAttributes };\n }\n\n private setStartTime(startTime: number): void {\n this.startTimeUs = startTime;\n }\n\n private setDuration(duration: number): void {\n this.durationUs = duration;\n }\n\n /**\n * Calculates and assigns the duration and start time of the trace using the measure performance\n * entry.\n */\n private calculateTraceMetrics(): void {\n const perfMeasureEntries = this.api.getEntriesByName(this.traceMeasure);\n const perfMeasureEntry = perfMeasureEntries && perfMeasureEntries[0];\n if (perfMeasureEntry) {\n this.durationUs = Math.floor(perfMeasureEntry.duration * 1000);\n this.startTimeUs = Math.floor(\n (perfMeasureEntry.startTime + this.api.getTimeOrigin()) * 1000\n );\n }\n }\n\n /**\n * @param navigationTimings A single element array which contains the navigationTIming object of\n * the page load\n * @param paintTimings A array which contains paintTiming object of the page load\n * @param firstInputDelay First input delay in millisec\n */\n static createOobTrace(\n navigationTimings: PerformanceNavigationTiming[],\n paintTimings: PerformanceEntry[],\n firstInputDelay?: number\n ): void {\n const route = Api.getInstance().getUrl();\n if (!route) {\n return;\n }\n const trace = new Trace(OOB_TRACE_PAGE_LOAD_PREFIX + route, true);\n const timeOriginUs = Math.floor(Api.getInstance().getTimeOrigin() * 1000);\n trace.setStartTime(timeOriginUs);\n\n // navigationTimings includes only one element.\n if (navigationTimings && navigationTimings[0]) {\n trace.setDuration(Math.floor(navigationTimings[0].duration * 1000));\n trace.putMetric(\n 'domInteractive',\n Math.floor(navigationTimings[0].domInteractive * 1000)\n );\n trace.putMetric(\n 'domContentLoadedEventEnd',\n Math.floor(navigationTimings[0].domContentLoadedEventEnd * 1000)\n );\n trace.putMetric(\n 'loadEventEnd',\n Math.floor(navigationTimings[0].loadEventEnd * 1000)\n );\n }\n\n const FIRST_PAINT = 'first-paint';\n const FIRST_CONTENTFUL_PAINT = 'first-contentful-paint';\n if (paintTimings) {\n const firstPaint = paintTimings.find(\n paintObject => paintObject.name === FIRST_PAINT\n );\n if (firstPaint && firstPaint.startTime) {\n trace.putMetric(\n FIRST_PAINT_COUNTER_NAME,\n Math.floor(firstPaint.startTime * 1000)\n );\n }\n const firstContentfulPaint = paintTimings.find(\n paintObject => paintObject.name === FIRST_CONTENTFUL_PAINT\n );\n if (firstContentfulPaint && firstContentfulPaint.startTime) {\n trace.putMetric(\n FIRST_CONTENTFUL_PAINT_COUNTER_NAME,\n Math.floor(firstContentfulPaint.startTime * 1000)\n );\n }\n\n if (firstInputDelay) {\n trace.putMetric(\n FIRST_INPUT_DELAY_COUNTER_NAME,\n Math.floor(firstInputDelay * 1000)\n );\n }\n }\n\n logTrace(trace);\n }\n\n static createUserTimingTrace(measureName: string): void {\n const trace = new Trace(measureName, false, measureName);\n logTrace(trace);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Api } from '../services/api_service';\nimport { logNetworkRequest } from '../services/perf_logger';\n\n// The order of values of this enum should not be changed.\nexport const enum HttpMethod {\n HTTP_METHOD_UNKNOWN = 0,\n GET = 1,\n PUT = 2,\n POST = 3,\n DELETE = 4,\n HEAD = 5,\n PATCH = 6,\n OPTIONS = 7,\n TRACE = 8,\n CONNECT = 9\n}\n\n// Durations are in microseconds.\nexport interface NetworkRequest {\n url: string;\n httpMethod?: HttpMethod;\n requestPayloadBytes?: number;\n responsePayloadBytes?: number;\n httpResponseCode?: number;\n responseContentType?: string;\n startTimeUs?: number;\n timeToRequestCompletedUs?: number;\n timeToResponseInitiatedUs?: number;\n timeToResponseCompletedUs?: number;\n}\n\nexport function createNetworkRequestEntry(entry: PerformanceEntry): void {\n const performanceEntry = entry as PerformanceResourceTiming;\n if (!performanceEntry || performanceEntry.responseStart === undefined) {\n return;\n }\n const timeOrigin = Api.getInstance().getTimeOrigin();\n const startTimeUs = Math.floor(\n (performanceEntry.startTime + timeOrigin) * 1000\n );\n const timeToResponseInitiatedUs = performanceEntry.responseStart\n ? Math.floor(\n (performanceEntry.responseStart - performanceEntry.startTime) * 1000\n )\n : undefined;\n const timeToResponseCompletedUs = Math.floor(\n (performanceEntry.responseEnd - performanceEntry.startTime) * 1000\n );\n // Remove the query params from logged network request url.\n const url = performanceEntry.name && performanceEntry.name.split('?')[0];\n const networkRequest: NetworkRequest = {\n url,\n responsePayloadBytes: performanceEntry.transferSize,\n startTimeUs,\n timeToResponseInitiatedUs,\n timeToResponseCompletedUs\n };\n\n logNetworkRequest(networkRequest);\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Api } from './api_service';\nimport { Trace } from '../resources/trace';\nimport { createNetworkRequestEntry } from '../resources/network_request';\nimport { TRACE_MEASURE_PREFIX } from '../constants';\nimport { getIid } from './iid_service';\n\nconst FID_WAIT_TIME_MS = 5000;\n\nexport function setupOobResources(): void {\n // Do not initialize unless iid is available.\n if (!getIid()) {\n return;\n }\n // The load event might not have fired yet, and that means performance navigation timing\n // object has a duration of 0. The setup should run after all current tasks in js queue.\n setTimeout(() => setupOobTraces(), 0);\n setTimeout(() => setupNetworkRequests(), 0);\n setTimeout(() => setupUserTimingTraces(), 0);\n}\n\nfunction setupNetworkRequests(): void {\n const api = Api.getInstance();\n const resources = api.getEntriesByType('resource');\n for (const resource of resources) {\n createNetworkRequestEntry(resource);\n }\n api.setupObserver('resource', createNetworkRequestEntry);\n}\n\nfunction setupOobTraces(): void {\n const api = Api.getInstance();\n const navigationTimings = api.getEntriesByType(\n 'navigation'\n ) as PerformanceNavigationTiming[];\n const paintTimings = api.getEntriesByType('paint');\n // If First Input Desly polyfill is added to the page, report the fid value.\n // https://github.com/GoogleChromeLabs/first-input-delay\n if (api.onFirstInputDelay) {\n // If the fid call back is not called for certain time, continue without it.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let timeoutId: any = setTimeout(() => {\n Trace.createOobTrace(navigationTimings, paintTimings);\n timeoutId = undefined;\n }, FID_WAIT_TIME_MS);\n api.onFirstInputDelay((fid: number) => {\n if (timeoutId) {\n clearTimeout(timeoutId);\n Trace.createOobTrace(navigationTimings, paintTimings, fid);\n }\n });\n } else {\n Trace.createOobTrace(navigationTimings, paintTimings);\n }\n}\n\nfunction setupUserTimingTraces(): void {\n const api = Api.getInstance();\n // Run through the measure performance entries collected up to this point.\n const measures = api.getEntriesByType('measure');\n for (const measure of measures) {\n createUserTimingTrace(measure);\n }\n // Setup an observer to capture the measures from this point on.\n api.setupObserver('measure', createUserTimingTrace);\n}\n\nfunction createUserTimingTrace(measure: PerformanceEntry): void {\n const measureName = measure.name;\n // Do not create a trace, if the user timing marks and measures are created by the sdk itself.\n if (\n measureName.substring(0, TRACE_MEASURE_PREFIX.length) ===\n TRACE_MEASURE_PREFIX\n ) {\n return;\n }\n Trace.createUserTimingTrace(measureName);\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Trace } from '../resources/trace';\nimport { setupOobResources } from '../services/oob_resources_service';\nimport { SettingsService } from '../services/settings_service';\nimport { getInitializationPromise } from '../services/initialization_service';\nimport { Api } from '../services/api_service';\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebasePerformance } from '@firebase/performance-types';\nimport { consoleLogger } from '../utils/console_logger';\nimport { setupTransportService } from '../services/transport_service';\n\nexport class PerformanceController implements FirebasePerformance {\n constructor(readonly app: FirebaseApp) {\n if (Api.getInstance().requiredApisAvailable()) {\n setupTransportService();\n getInitializationPromise().then(setupOobResources, setupOobResources);\n } else {\n consoleLogger.info(\n 'Firebase Performance cannot start if browser does not support fetch and Promise or cookie is disabled.'\n );\n }\n }\n\n trace(name: string): Trace {\n return new Trace(name);\n }\n\n set instrumentationEnabled(val: boolean) {\n SettingsService.getInstance().instrumentationEnabled = val;\n }\n get instrumentationEnabled(): boolean {\n return SettingsService.getInstance().instrumentationEnabled;\n }\n\n set dataCollectionEnabled(val: boolean) {\n SettingsService.getInstance().dataCollectionEnabled = val;\n }\n get dataCollectionEnabled(): boolean {\n return SettingsService.getInstance().dataCollectionEnabled;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\nimport '@firebase/installations';\nimport { FirebaseApp, FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { PerformanceController } from './src/controllers/perf';\nimport { setupApi } from './src/services/api_service';\nimport { SettingsService } from './src/services/settings_service';\nimport { ERROR_FACTORY, ErrorCode } from './src/utils/errors';\nimport { FirebasePerformance } from '@firebase/performance-types';\nimport { Component, ComponentType } from '@firebase/component';\nimport { FirebaseInstallations } from '@firebase/installations-types';\n\nimport { name, version } from './package.json';\n\nconst DEFAULT_ENTRY_NAME = '[DEFAULT]';\n\nexport function registerPerformance(instance: FirebaseNamespace): void {\n const factoryMethod = (\n app: FirebaseApp,\n installations: FirebaseInstallations\n ): PerformanceController => {\n if (app.name !== DEFAULT_ENTRY_NAME) {\n throw ERROR_FACTORY.create(ErrorCode.FB_NOT_DEFAULT);\n }\n if (typeof window === 'undefined') {\n throw ERROR_FACTORY.create(ErrorCode.NO_WINDOW);\n }\n setupApi(window);\n SettingsService.getInstance().firebaseAppInstance = app;\n SettingsService.getInstance().installationsService = installations;\n return new PerformanceController(app);\n };\n\n // Register performance with firebase-app.\n (instance as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'performance',\n container => {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n // The following call will always succeed because perf has `import '@firebase/installations'`\n const installations = container\n .getProvider('installations')\n .getImmediate();\n\n return factoryMethod(app, installations);\n },\n ComponentType.PUBLIC\n )\n );\n\n instance.registerVersion(name, version);\n}\n\nregisterPerformance(firebase);\n\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n performance?: {\n (app?: FirebaseApp): FirebasePerformance;\n };\n }\n interface FirebaseApp {\n performance?(): FirebasePerformance;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 ANALYTICS_ID_FIELD = 'measurementId';\n\n// Key to attach FID to in gtag params.\nexport const GA_FID_KEY = 'firebase_id';\nexport const ORIGIN_KEY = 'origin';\n\nexport const GTAG_URL = 'https://www.googletagmanager.com/gtag/js';\n\nexport enum GtagCommand {\n EVENT = 'event',\n SET = 'set',\n CONFIG = 'config'\n}\n\n/*\n * Officially recommended event names for gtag.js\n * Any other string is also allowed.\n */\nexport enum EventName {\n ADD_SHIPPING_INFO = 'add_shipping_info',\n ADD_PAYMENT_INFO = 'add_payment_info',\n ADD_TO_CART = 'add_to_cart',\n ADD_TO_WISHLIST = 'add_to_wishlist',\n BEGIN_CHECKOUT = 'begin_checkout',\n /** @deprecated */\n CHECKOUT_PROGRESS = 'checkout_progress',\n EXCEPTION = 'exception',\n GENERATE_LEAD = 'generate_lead',\n LOGIN = 'login',\n PAGE_VIEW = 'page_view',\n PURCHASE = 'purchase',\n REFUND = 'refund',\n REMOVE_FROM_CART = 'remove_from_cart',\n SCREEN_VIEW = 'screen_view',\n SEARCH = 'search',\n SELECT_CONTENT = 'select_content',\n SELECT_ITEM = 'select_item',\n SELECT_PROMOTION = 'select_promotion',\n /** @deprecated */\n SET_CHECKOUT_OPTION = 'set_checkout_option',\n SHARE = 'share',\n SIGN_UP = 'sign_up',\n TIMING_COMPLETE = 'timing_complete',\n VIEW_CART = 'view_cart',\n VIEW_ITEM = 'view_item',\n VIEW_ITEM_LIST = 'view_item_list',\n VIEW_PROMOTION = 'view_promotion',\n VIEW_SEARCH_RESULTS = 'view_search_results'\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Logger } from '@firebase/logger';\n\nexport const logger = new Logger('@firebase/analytics');\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app-types';\nimport {\n DataLayer,\n Gtag,\n CustomParams,\n ControlParams,\n EventParams\n} from '@firebase/analytics-types';\nimport {\n GtagCommand,\n ANALYTICS_ID_FIELD,\n GA_FID_KEY,\n ORIGIN_KEY,\n GTAG_URL\n} from './constants';\nimport { FirebaseInstallations } from '@firebase/installations-types';\nimport { logger } from './logger';\n\n/**\n * Initialize the analytics instance in gtag.js by calling config command with fid.\n *\n * NOTE: We combine analytics initialization and setting fid together because we want fid to be\n * part of the `page_view` event that's sent during the initialization\n * @param app Firebase app\n * @param gtagCore The gtag function that's not wrapped.\n */\nexport async function initializeGAId(\n app: FirebaseApp,\n installations: FirebaseInstallations,\n gtagCore: Gtag\n): Promise<void> {\n const fid = await installations.getId();\n\n // This command initializes gtag.js and only needs to be called once for the entire web app,\n // but since it is idempotent, we can call it multiple times.\n // We keep it together with other initialization logic for better code structure.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n gtagCore('js' as any, new Date());\n\n // It should be the first config command called on this GA-ID\n // Initialize this GA-ID and set FID on it using the gtag config API.\n gtagCore(GtagCommand.CONFIG, app.options[ANALYTICS_ID_FIELD]!, {\n [GA_FID_KEY]: fid,\n // guard against developers accidentally setting properties with prefix `firebase_`\n [ORIGIN_KEY]: 'firebase',\n update: true\n });\n}\n\nexport function insertScriptTag(dataLayerName: string): void {\n const script = document.createElement('script');\n // We are not providing an analyticsId in the URL because it would trigger a `page_view`\n // without fid. We will initialize ga-id using gtag (config) command together with fid.\n script.src = `${GTAG_URL}?l=${dataLayerName}`;\n script.async = true;\n document.head.appendChild(script);\n}\n\n/** Get reference to, or create, global datalayer.\n * @param dataLayerName Name of datalayer (most often the default, \"_dataLayer\")\n */\nexport function getOrCreateDataLayer(dataLayerName: string): DataLayer {\n // Check for existing dataLayer and create if needed.\n let dataLayer: DataLayer = [];\n if (Array.isArray(window[dataLayerName])) {\n dataLayer = window[dataLayerName] as DataLayer;\n } else {\n window[dataLayerName] = dataLayer;\n }\n return dataLayer;\n}\n/**\n * Wraps a standard gtag function with extra code to wait for completion of\n * relevant initialization promises before sending requests.\n *\n * @param gtagCore Basic gtag function that just appends to dataLayer\n * @param initializedIdPromisesMap Map of gaIds to their initialization promises\n */\nfunction wrapGtag(\n gtagCore: Gtag,\n initializedIdPromisesMap: { [gaId: string]: Promise<void> }\n): Function {\n return (\n command: 'config' | 'set' | 'event',\n idOrNameOrParams: string | ControlParams,\n gtagParams?: ControlParams & EventParams & CustomParams\n ) => {\n // If event, check that relevant initialization promises have completed.\n if (command === GtagCommand.EVENT) {\n let initializationPromisesToWaitFor: Array<Promise<void>> = [];\n // If there's a 'send_to' param, check if any ID specified matches\n // a FID we have begun a fetch on.\n if (gtagParams && gtagParams['send_to']) {\n let gaSendToList: string | string[] = gtagParams['send_to'];\n // Make it an array if is isn't, so it can be dealt with the same way.\n if (!Array.isArray(gaSendToList)) {\n gaSendToList = [gaSendToList];\n }\n for (const sendToId of gaSendToList) {\n const initializationPromise = initializedIdPromisesMap[sendToId];\n // Groups will not be in the map.\n if (initializationPromise) {\n initializationPromisesToWaitFor.push(initializationPromise);\n } else {\n // There is an item in 'send_to' that is not associated\n // directly with an FID, possibly a group. Empty this array\n // and let it get populated below.\n initializationPromisesToWaitFor = [];\n break;\n }\n }\n }\n\n // This will be unpopulated if there was no 'send_to' field , or\n // if not all entries in the 'send_to' field could be mapped to\n // a FID. In these cases, wait on all pending initialization promises.\n if (initializationPromisesToWaitFor.length === 0) {\n for (const idPromise of Object.values(initializedIdPromisesMap)) {\n initializationPromisesToWaitFor.push(idPromise);\n }\n }\n // Run core gtag function with args after all relevant initialization\n // promises have been resolved.\n Promise.all(initializationPromisesToWaitFor)\n // Workaround for http://b/141370449 - third argument cannot be undefined.\n .then(() =>\n gtagCore(\n GtagCommand.EVENT,\n idOrNameOrParams as string,\n gtagParams || {}\n )\n )\n .catch(e => logger.error(e));\n } else if (command === GtagCommand.CONFIG) {\n const initializationPromiseToWait =\n initializedIdPromisesMap[idOrNameOrParams as string] ||\n Promise.resolve();\n initializationPromiseToWait\n .then(() => {\n gtagCore(GtagCommand.CONFIG, idOrNameOrParams as string, gtagParams);\n })\n .catch(e => logger.error(e));\n } else {\n // SET command.\n // Splitting calls for CONFIG and SET to make it clear which signature\n // Typescript is checking.\n gtagCore(GtagCommand.SET, idOrNameOrParams as CustomParams);\n }\n };\n}\n\n/**\n * Creates global gtag function or wraps existing one if found.\n * This wrapped function attaches Firebase instance ID (FID) to gtag 'config' and\n * 'event' calls that belong to the GAID associated with this Firebase instance.\n *\n * @param initializedIdPromisesMap Map of gaId to initialization promises.\n * @param dataLayerName Name of global GA datalayer array.\n * @param gtagFunctionName Name of global gtag function (\"gtag\" if not user-specified)\n */\nexport function wrapOrCreateGtag(\n initializedIdPromisesMap: { [gaId: string]: Promise<void> },\n dataLayerName: string,\n gtagFunctionName: string\n): {\n gtagCore: Gtag;\n wrappedGtag: Gtag;\n} {\n // Create a basic core gtag function\n let gtagCore: Gtag = function(..._args: unknown[]) {\n // Must push IArguments object, not an array.\n (window[dataLayerName] as DataLayer).push(arguments);\n };\n\n // Replace it with existing one if found\n if (\n window[gtagFunctionName] &&\n typeof window[gtagFunctionName] === 'function'\n ) {\n // @ts-ignore\n gtagCore = window[gtagFunctionName];\n }\n\n window[gtagFunctionName] = wrapGtag(gtagCore, initializedIdPromisesMap);\n\n return {\n gtagCore,\n wrappedGtag: window[gtagFunctionName] as Gtag\n };\n}\n\n/**\n * Returns first script tag in DOM matching our gtag url pattern.\n */\nexport function findGtagScriptOnPage(): HTMLScriptElement | null {\n const scriptTags = window.document.getElementsByTagName('script');\n for (const tag of Object.values(scriptTags)) {\n if (tag.src && tag.src.includes(GTAG_URL)) {\n return tag;\n }\n }\n return null;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ErrorFactory, ErrorMap } from '@firebase/util';\nimport { ANALYTICS_ID_FIELD } from './constants';\n\nexport const enum AnalyticsError {\n NO_GA_ID = 'no-ga-id',\n ALREADY_EXISTS = 'already-exists',\n ALREADY_INITIALIZED = 'already-initialized',\n INTEROP_COMPONENT_REG_FAILED = 'interop-component-reg-failed'\n}\n\nconst ERRORS: ErrorMap<AnalyticsError> = {\n [AnalyticsError.NO_GA_ID]:\n `\"${ANALYTICS_ID_FIELD}\" field is empty in ` +\n 'Firebase config. Firebase Analytics ' +\n 'requires this field to contain a valid measurement ID.',\n [AnalyticsError.ALREADY_EXISTS]:\n 'A Firebase Analytics instance with the measurement ID ${id} ' +\n ' already exists. ' +\n 'Only one Firebase Analytics instance can be created for each measurement ID.',\n [AnalyticsError.ALREADY_INITIALIZED]:\n 'Firebase Analytics has already been initialized.' +\n 'settings() must be called before initializing any Analytics instance' +\n 'or it will have no effect.',\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]:\n 'Firebase Analytics Interop Component failed to instantiate'\n};\n\ninterface ErrorParams {\n [AnalyticsError.ALREADY_EXISTS]: { id: string };\n [AnalyticsError.INTEROP_COMPONENT_REG_FAILED]: { reason: Error };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<AnalyticsError, ErrorParams>(\n 'analytics',\n 'Analytics',\n ERRORS\n);\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 FirebaseAnalytics,\n Gtag,\n SettingsOptions\n} from '@firebase/analytics-types';\nimport {\n logEvent,\n setCurrentScreen,\n setUserId,\n setUserProperties,\n setAnalyticsCollectionEnabled\n} from './functions';\nimport {\n initializeGAId,\n insertScriptTag,\n getOrCreateDataLayer,\n wrapOrCreateGtag,\n findGtagScriptOnPage\n} from './helpers';\nimport { ANALYTICS_ID_FIELD } from './constants';\nimport { AnalyticsError, ERROR_FACTORY } from './errors';\nimport { FirebaseApp } from '@firebase/app-types';\nimport { FirebaseInstallations } from '@firebase/installations-types';\n\n/**\n * Maps gaId to FID fetch promises.\n */\nlet initializedIdPromisesMap: { [gaId: string]: Promise<void> } = {};\n\n/**\n * Name for window global data layer array used by GA: defaults to 'dataLayer'.\n */\nlet dataLayerName: string = 'dataLayer';\n\n/**\n * Name for window global gtag function used by GA: defaults to 'gtag'.\n */\nlet gtagName: string = 'gtag';\n\n/**\n * Reproduction of standard gtag function or reference to existing\n * gtag function on window object.\n */\nlet gtagCoreFunction: Gtag;\n\n/**\n * Wrapper around gtag function that ensures FID is sent with all\n * relevant event and config calls.\n */\nlet wrappedGtagFunction: Gtag;\n\n/**\n * Flag to ensure page initialization steps (creation or wrapping of\n * dataLayer and gtag script) are only run once per page load.\n */\nlet globalInitDone: boolean = false;\n\n/**\n * For testing\n */\nexport function resetGlobalVars(\n newGlobalInitDone = false,\n newGaInitializedPromise = {}\n): void {\n globalInitDone = newGlobalInitDone;\n initializedIdPromisesMap = newGaInitializedPromise;\n dataLayerName = 'dataLayer';\n gtagName = 'gtag';\n}\n\n/**\n * For testing\n */\nexport function getGlobalVars(): { initializedIdPromisesMap: { [gaId: string]: Promise<void> }} {\n return {\n initializedIdPromisesMap\n };\n}\n\n/**\n * This must be run before calling firebase.analytics() or it won't\n * have any effect.\n * @param options Custom gtag and dataLayer names.\n */\nexport function settings(options: SettingsOptions): void {\n if (globalInitDone) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_INITIALIZED);\n }\n if (options.dataLayerName) {\n dataLayerName = options.dataLayerName;\n }\n if (options.gtagName) {\n gtagName = options.gtagName;\n }\n}\n\nexport function factory(\n app: FirebaseApp,\n installations: FirebaseInstallations\n): FirebaseAnalytics {\n const analyticsId = app.options[ANALYTICS_ID_FIELD];\n if (!analyticsId) {\n throw ERROR_FACTORY.create(AnalyticsError.NO_GA_ID);\n }\n\n if (initializedIdPromisesMap[analyticsId] != null) {\n throw ERROR_FACTORY.create(AnalyticsError.ALREADY_EXISTS, {\n id: analyticsId\n });\n }\n\n if (!globalInitDone) {\n // Steps here should only be done once per page: creation or wrapping\n // of dataLayer and global gtag function.\n\n // Detect if user has already put the gtag <script> tag on this page.\n if (!findGtagScriptOnPage()) {\n insertScriptTag(dataLayerName);\n }\n getOrCreateDataLayer(dataLayerName);\n\n const { wrappedGtag, gtagCore } = wrapOrCreateGtag(\n initializedIdPromisesMap,\n dataLayerName,\n gtagName\n );\n wrappedGtagFunction = wrappedGtag;\n gtagCoreFunction = gtagCore;\n\n globalInitDone = true;\n }\n // Async but non-blocking.\n initializedIdPromisesMap[analyticsId] = initializeGAId(\n app,\n installations,\n gtagCoreFunction\n );\n\n const analyticsInstance: FirebaseAnalytics = {\n app,\n logEvent: (eventName, eventParams, options) =>\n logEvent(\n wrappedGtagFunction,\n analyticsId,\n eventName,\n eventParams,\n options\n ),\n setCurrentScreen: (screenName, options) =>\n setCurrentScreen(wrappedGtagFunction, analyticsId, screenName, options),\n setUserId: (id, options) =>\n setUserId(wrappedGtagFunction, analyticsId, id, options),\n setUserProperties: (properties, options) =>\n setUserProperties(wrappedGtagFunction, analyticsId, properties, options),\n setAnalyticsCollectionEnabled: enabled =>\n setAnalyticsCollectionEnabled(analyticsId, enabled)\n };\n\n return analyticsInstance;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 AnalyticsCallOptions,\n Gtag,\n CustomParams,\n ControlParams,\n EventParams\n} from '@firebase/analytics-types';\nimport { GtagCommand } from './constants';\n/**\n * Logs an analytics event through the Firebase SDK.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param eventName Google Analytics event name, choose from standard list or use a custom string.\n * @param eventParams Analytics event parameters.\n */\nexport function logEvent(\n gtagFunction: Gtag,\n analyticsId: string,\n eventName: string,\n eventParams?: EventParams,\n options?: AnalyticsCallOptions\n): void {\n let params: EventParams | ControlParams = eventParams || {};\n if (!options || !options.global) {\n params = { ...eventParams, 'send_to': analyticsId };\n }\n // Workaround for http://b/141370449 - third argument cannot be undefined.\n gtagFunction(GtagCommand.EVENT, eventName, params || {});\n}\n\n// TODO: Brad is going to add `screen_name` to GA Gold config parameter schema\n\n/**\n * Set screen_name parameter for this Google Analytics ID.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param screenName Screen name string to set.\n */\nexport function setCurrentScreen(\n gtagFunction: Gtag,\n analyticsId: string,\n screenName: string | null,\n options?: AnalyticsCallOptions\n): void {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'screen_name': screenName });\n } else {\n gtagFunction(GtagCommand.CONFIG, analyticsId, {\n update: true,\n 'screen_name': screenName\n });\n }\n}\n\n/**\n * Set user_id parameter for this Google Analytics ID.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param id User ID string to set\n */\nexport function setUserId(\n gtagFunction: Gtag,\n analyticsId: string,\n id: string | null,\n options?: AnalyticsCallOptions\n): void {\n if (options && options.global) {\n gtagFunction(GtagCommand.SET, { 'user_id': id });\n } else {\n gtagFunction(GtagCommand.CONFIG, analyticsId, {\n update: true,\n 'user_id': id\n });\n }\n}\n\n/**\n * Set all other user properties other than user_id and screen_name.\n *\n * @param gtagFunction Wrapped gtag function that waits for fid to be set before sending an event\n * @param properties Map of user properties to set\n */\nexport function setUserProperties(\n gtagFunction: Gtag,\n analyticsId: string,\n properties: CustomParams,\n options?: AnalyticsCallOptions\n): void {\n if (options && options.global) {\n const flatProperties: { [key: string]: unknown } = {};\n for (const key of Object.keys(properties)) {\n // use dot notation for merge behavior in gtag.js\n flatProperties[`user_properties.${key}`] = properties[key];\n }\n gtagFunction(GtagCommand.SET, flatProperties);\n } else {\n gtagFunction(GtagCommand.CONFIG, analyticsId, {\n update: true,\n 'user_properties': properties\n });\n }\n}\n\n/**\n * Set whether collection is enabled for this ID.\n *\n * @param enabled If true, collection is enabled for this ID.\n */\nexport function setAnalyticsCollectionEnabled(\n analyticsId: string,\n enabled: boolean\n): void {\n window[`ga-disable-${analyticsId}`] = !enabled;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 firebase from '@firebase/app';\nimport '@firebase/installations';\nimport { FirebaseAnalytics } from '@firebase/analytics-types';\nimport { FirebaseAnalyticsInternal } from '@firebase/analytics-interop-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { factory, settings, resetGlobalVars, getGlobalVars } from './src/factory';\nimport { EventName } from './src/constants';\nimport {\n Component,\n ComponentType,\n ComponentContainer\n} from '@firebase/component';\nimport { ERROR_FACTORY, AnalyticsError } from './src/errors';\n\nimport { name, version } from './package.json';\n\ndeclare global {\n interface Window {\n [key: string]: unknown;\n }\n}\n\n/**\n * Type constant for Firebase Analytics.\n */\nconst ANALYTICS_TYPE = 'analytics';\nexport function registerAnalytics(instance: _FirebaseNamespace): void {\n instance.INTERNAL.registerComponent(\n new Component(\n ANALYTICS_TYPE,\n container => {\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n const installations = container\n .getProvider('installations')\n .getImmediate();\n\n return factory(app, installations);\n },\n ComponentType.PUBLIC\n ).setServiceProps({\n settings,\n EventName\n })\n );\n\n instance.INTERNAL.registerComponent(\n new Component('analytics-internal', internalFactory, ComponentType.PRIVATE)\n );\n\n instance.registerVersion(name, version);\n\n function internalFactory(\n container: ComponentContainer\n ): FirebaseAnalyticsInternal {\n try {\n const analytics = container.getProvider(ANALYTICS_TYPE).getImmediate();\n return {\n logEvent: analytics.logEvent\n };\n } catch (e) {\n throw ERROR_FACTORY.create(AnalyticsError.INTEROP_COMPONENT_REG_FAILED, {\n reason: e\n });\n }\n }\n}\n\nexport { factory, settings, resetGlobalVars, getGlobalVars };\n\nregisterAnalytics(firebase as _FirebaseNamespace);\n\n/**\n * Define extension behavior of `registerAnalytics`\n */\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n analytics(app?: FirebaseApp): FirebaseAnalytics;\n }\n interface FirebaseApp {\n analytics(): FirebaseAnalytics;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { StorageCache } from '../storage/storage_cache';\nimport {\n FetchResponse,\n RemoteConfigFetchClient,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { Storage } from '../storage/storage';\nimport { Logger } from '@firebase/logger';\n\n/**\n * Implements the {@link RemoteConfigClient} abstraction with success response caching.\n *\n * <p>Comparable to the browser's Cache API for responses, but the Cache API requires a Service\n * Worker, which requires HTTPS, which would significantly complicate SDK installation. Also, the\n * Cache API doesn't support matching entries by time.\n */\nexport class CachingClient implements RemoteConfigFetchClient {\n constructor(\n private readonly client: RemoteConfigFetchClient,\n private readonly storage: Storage,\n private readonly storageCache: StorageCache,\n private readonly logger: Logger\n ) {}\n\n /**\n * Returns true if the age of the cached fetched configs is less than or equal to\n * {@link Settings#minimumFetchIntervalInSeconds}.\n *\n * <p>This is comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the\n * native Fetch API.\n *\n * <p>Visible for testing.\n */\n isCachedDataFresh(\n cacheMaxAgeMillis: number,\n lastSuccessfulFetchTimestampMillis: number | undefined\n ): boolean {\n // Cache can only be fresh if it's populated.\n if (!lastSuccessfulFetchTimestampMillis) {\n this.logger.debug('Config fetch cache check. Cache unpopulated.');\n return false;\n }\n\n // Calculates age of cache entry.\n const cacheAgeMillis = Date.now() - lastSuccessfulFetchTimestampMillis;\n\n const isCachedDataFresh = cacheAgeMillis <= cacheMaxAgeMillis;\n\n this.logger.debug(\n 'Config fetch cache check.' +\n ` Cache age millis: ${cacheAgeMillis}.` +\n ` Cache max age millis (minimumFetchIntervalMillis setting): ${cacheMaxAgeMillis}.` +\n ` Is cache hit: ${isCachedDataFresh}.`\n );\n\n return isCachedDataFresh;\n }\n\n async fetch(request: FetchRequest): Promise<FetchResponse> {\n // Reads from persisted storage to avoid cache miss if callers don't wait on initialization.\n const [\n lastSuccessfulFetchTimestampMillis,\n lastSuccessfulFetchResponse\n ] = await Promise.all([\n this.storage.getLastSuccessfulFetchTimestampMillis(),\n this.storage.getLastSuccessfulFetchResponse()\n ]);\n\n // Exits early on cache hit.\n if (\n lastSuccessfulFetchResponse &&\n this.isCachedDataFresh(\n request.cacheMaxAgeMillis,\n lastSuccessfulFetchTimestampMillis\n )\n ) {\n return lastSuccessfulFetchResponse;\n }\n\n // Deviates from pure decorator by not honoring a passed ETag since we don't have a public API\n // that allows the caller to pass an ETag.\n request.eTag =\n lastSuccessfulFetchResponse && lastSuccessfulFetchResponse.eTag;\n\n // Falls back to service on cache miss.\n const response = await this.client.fetch(request);\n\n // Fetch throws for non-success responses, so success is guaranteed here.\n\n const storageOperations = [\n // Uses write-through cache for consistency with synchronous public API.\n this.storageCache.setLastSuccessfulFetchTimestampMillis(Date.now())\n ];\n\n if (response.status === 200) {\n // Caches response only if it has changed, ie non-304 responses.\n storageOperations.push(\n this.storage.setLastSuccessfulFetchResponse(response)\n );\n }\n\n await Promise.all(storageOperations);\n\n return response;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { ErrorFactory, FirebaseError } from '@firebase/util';\n\nexport const enum ErrorCode {\n REGISTRATION_WINDOW = 'registration-window',\n REGISTRATION_PROJECT_ID = 'registration-project-id',\n REGISTRATION_API_KEY = 'registration-api-key',\n REGISTRATION_APP_ID = 'registration-app-id',\n STORAGE_OPEN = 'storage-open',\n STORAGE_GET = 'storage-get',\n STORAGE_SET = 'storage-set',\n STORAGE_DELETE = 'storage-delete',\n FETCH_NETWORK = 'fetch-client-network',\n FETCH_TIMEOUT = 'fetch-timeout',\n FETCH_THROTTLE = 'fetch-throttle',\n FETCH_PARSE = 'fetch-client-parse',\n FETCH_STATUS = 'fetch-status'\n}\n\nconst ERROR_DESCRIPTION_MAP: { readonly [key in ErrorCode]: string } = {\n [ErrorCode.REGISTRATION_WINDOW]:\n 'Undefined window object. This SDK only supports usage in a browser environment.',\n [ErrorCode.REGISTRATION_PROJECT_ID]:\n 'Undefined project identifier. Check Firebase app initialization.',\n [ErrorCode.REGISTRATION_API_KEY]:\n 'Undefined API key. Check Firebase app initialization.',\n [ErrorCode.REGISTRATION_APP_ID]:\n 'Undefined app identifier. Check Firebase app initialization.',\n [ErrorCode.STORAGE_OPEN]:\n 'Error thrown when opening storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.STORAGE_GET]:\n 'Error thrown when reading from storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.STORAGE_SET]:\n 'Error thrown when writing to storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.STORAGE_DELETE]:\n 'Error thrown when deleting from storage. Original error: {$originalErrorMessage}.',\n [ErrorCode.FETCH_NETWORK]:\n 'Fetch client failed to connect to a network. Check Internet connection.' +\n ' Original error: {$originalErrorMessage}.',\n [ErrorCode.FETCH_TIMEOUT]:\n 'The config fetch request timed out. ' +\n ' Configure timeout using \"fetchTimeoutMillis\" SDK setting.',\n [ErrorCode.FETCH_THROTTLE]:\n 'The config fetch request timed out while in an exponential backoff state.' +\n ' Configure timeout using \"fetchTimeoutMillis\" SDK setting.' +\n ' Unix timestamp in milliseconds when fetch request throttling ends: {$throttleEndTimeMillis}.',\n [ErrorCode.FETCH_PARSE]:\n 'Fetch client could not parse response.' +\n ' Original error: {$originalErrorMessage}.',\n [ErrorCode.FETCH_STATUS]:\n 'Fetch server returned an HTTP error status. HTTP status: {$httpStatus}.'\n};\n\n// Note this is effectively a type system binding a code to params. This approach overlaps with the\n// role of TS interfaces, but works well for a few reasons:\n// 1) JS is unaware of TS interfaces, eg we can't test for interface implementation in JS\n// 2) callers should have access to a human-readable summary of the error and this interpolates\n// params into an error message;\n// 3) callers should be able to programmatically access data associated with an error, which\n// ErrorData provides.\ninterface ErrorParams {\n [ErrorCode.STORAGE_OPEN]: { originalErrorMessage: string | undefined };\n [ErrorCode.STORAGE_GET]: { originalErrorMessage: string | undefined };\n [ErrorCode.STORAGE_SET]: { originalErrorMessage: string | undefined };\n [ErrorCode.STORAGE_DELETE]: { originalErrorMessage: string | undefined };\n [ErrorCode.FETCH_NETWORK]: { originalErrorMessage: string };\n [ErrorCode.FETCH_THROTTLE]: { throttleEndTimeMillis: number };\n [ErrorCode.FETCH_PARSE]: { originalErrorMessage: string };\n [ErrorCode.FETCH_STATUS]: { httpStatus: number };\n}\n\nexport const ERROR_FACTORY = new ErrorFactory<ErrorCode, ErrorParams>(\n 'remoteconfig' /* service */,\n 'Remote Config' /* service name */,\n ERROR_DESCRIPTION_MAP\n);\n\n// Note how this is like typeof/instanceof, but for ErrorCode.\nexport function hasErrorCode(e: Error, errorCode: ErrorCode): boolean {\n return e instanceof FirebaseError && e.code.indexOf(errorCode) !== -1;\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FirebaseInstallations } from '@firebase/installations-types';\nimport {\n FetchResponse,\n RemoteConfigFetchClient,\n FirebaseRemoteConfigObject,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { getUserLanguage } from '../language';\n\n/**\n * Defines request body parameters required to call the fetch API:\n * https://firebase.google.com/docs/reference/remote-config/rest\n *\n * <p>Not exported because this file encapsulates REST API specifics.\n *\n * <p>Not passing User Properties because Analytics' source of truth on Web is server-side.\n */\ninterface FetchRequestBody {\n // Disables camelcase linting for request body params.\n /* eslint-disable camelcase*/\n sdk_version: string;\n app_instance_id: string;\n app_instance_id_token: string;\n app_id: string;\n language_code: string;\n /* eslint-enable camelcase */\n}\n\n/**\n * Implements the Client abstraction for the Remote Config REST API.\n */\nexport class RestClient implements RemoteConfigFetchClient {\n constructor(\n private readonly firebaseInstallations: FirebaseInstallations,\n private readonly sdkVersion: string,\n private readonly namespace: string,\n private readonly projectId: string,\n private readonly apiKey: string,\n private readonly appId: string\n ) {}\n\n /**\n * Fetches from the Remote Config REST API.\n *\n * @throws a {@link ErrorCode.FETCH_NETWORK} error if {@link GlobalFetch#fetch} can't\n * connect to the network.\n * @throws a {@link ErrorCode.FETCH_PARSE} error if {@link Response#json} can't parse the\n * fetch response.\n * @throws a {@link ErrorCode.FETCH_STATUS} error if the service returns an HTTP error status.\n */\n async fetch(request: FetchRequest): Promise<FetchResponse> {\n const [installationId, installationToken] = await Promise.all([\n this.firebaseInstallations.getId(),\n this.firebaseInstallations.getToken()\n ]);\n\n const urlBase =\n window.FIREBASE_REMOTE_CONFIG_URL_BASE ||\n 'https://firebaseremoteconfig.googleapis.com';\n\n const url = `${urlBase}/v1/projects/${this.projectId}/namespaces/${this.namespace}:fetch?key=${this.apiKey}`;\n\n const headers = {\n 'Content-Type': 'application/json',\n 'Content-Encoding': 'gzip',\n // Deviates from pure decorator by not passing max-age header since we don't currently have\n // service behavior using that header.\n 'If-None-Match': request.eTag || '*'\n };\n\n const requestBody: FetchRequestBody = {\n /* eslint-disable camelcase */\n sdk_version: this.sdkVersion,\n app_instance_id: installationId,\n app_instance_id_token: installationToken,\n app_id: this.appId,\n language_code: getUserLanguage()\n /* eslint-enable camelcase */\n };\n\n const options = {\n method: 'POST',\n headers,\n body: JSON.stringify(requestBody)\n };\n\n // This logic isn't REST-specific, but shimming abort logic isn't worth another decorator.\n const fetchPromise = fetch(url, options);\n const timeoutPromise = new Promise((_resolve, reject) => {\n // Maps async event listener to Promise API.\n request.signal.addEventListener(() => {\n // Emulates https://heycam.github.io/webidl/#aborterror\n const error = new Error('The operation was aborted.');\n error.name = 'AbortError';\n reject(error);\n });\n });\n\n let response;\n try {\n await Promise.race([fetchPromise, timeoutPromise]);\n response = await fetchPromise;\n } catch (originalError) {\n let errorCode = ErrorCode.FETCH_NETWORK;\n if (originalError.name === 'AbortError') {\n errorCode = ErrorCode.FETCH_TIMEOUT;\n }\n throw ERROR_FACTORY.create(errorCode, {\n originalErrorMessage: originalError.message\n });\n }\n\n let status = response.status;\n\n // Normalizes nullable header to optional.\n const responseEtag = response.headers.get('ETag') || undefined;\n\n let config: FirebaseRemoteConfigObject | undefined;\n let state: string | undefined;\n\n // JSON parsing throws SyntaxError if the response body isn't a JSON string.\n // Requesting application/json and checking for a 200 ensures there's JSON data.\n if (response.status === 200) {\n let responseBody;\n try {\n responseBody = await response.json();\n } catch (originalError) {\n throw ERROR_FACTORY.create(ErrorCode.FETCH_PARSE, {\n originalErrorMessage: originalError.message\n });\n }\n config = responseBody['entries'];\n state = responseBody['state'];\n }\n\n // Normalizes based on legacy state.\n if (state === 'INSTANCE_STATE_UNSPECIFIED') {\n status = 500;\n } else if (state === 'NO_CHANGE') {\n status = 304;\n } else if (state === 'NO_TEMPLATE' || state === 'EMPTY_CONFIG') {\n // These cases can be fixed remotely, so normalize to safe value.\n config = {};\n }\n\n // Normalize to exception-based control flow for non-success cases.\n // Encapsulates HTTP specifics in this class as much as possible. Status is still the best for\n // differentiating success states (200 from 304; the state body param is undefined in a\n // standard 304).\n if (status !== 304 && status !== 200) {\n throw ERROR_FACTORY.create(ErrorCode.FETCH_STATUS, {\n httpStatus: status\n });\n }\n\n return { status, eTag: responseEtag, config };\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * Attempts to get the most accurate browser language setting.\n *\n * <p>Adapted from getUserLanguage in packages/auth/src/utils.js for TypeScript.\n *\n * <p>Defers default language specification to server logic for consistency.\n *\n * @param navigatorLanguage Enables tests to override read-only {@link NavigatorLanguage}.\n */\nexport function getUserLanguage(\n navigatorLanguage: NavigatorLanguage = navigator\n): string {\n return (\n // Most reliable, but only supported in Chrome/Firefox.\n (navigatorLanguage.languages && navigatorLanguage.languages[0]) ||\n // Supported in most browsers, but returns the language of the browser\n // UI, not the language set in browser settings.\n navigatorLanguage.language\n // Polyfill otherwise.\n );\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * Defines a client, as in https://en.wikipedia.org/wiki/Client%E2%80%93server_model, for the\n * Remote Config server (https://firebase.google.com/docs/reference/remote-config/rest).\n *\n * <p>Abstracts throttle, response cache and network implementation details.\n *\n * <p>Modeled after the native {@link GlobalFetch} interface, which is relatively modern and\n * convenient, but simplified for Remote Config's use case.\n *\n * Disambiguation: {@link GlobalFetch} interface and the Remote Config service define \"fetch\"\n * methods. The RestClient uses the former to make HTTP calls. This interface abstracts the latter.\n */\nexport interface RemoteConfigFetchClient {\n /**\n * @throws if response status is not 200 or 304.\n */\n fetch(request: FetchRequest): Promise<FetchResponse>;\n}\n\n/**\n * Defines a self-descriptive reference for config key-value pairs.\n */\nexport interface FirebaseRemoteConfigObject {\n [key: string]: string;\n}\n\n/**\n * Shims a minimal AbortSignal.\n *\n * <p>AbortController's AbortSignal conveniently decouples fetch timeout logic from other aspects\n * of networking, such as retries. Firebase doesn't use AbortController enough to justify a\n * polyfill recommendation, like we do with the Fetch API, but this minimal shim can easily be\n * swapped out if/when we do.\n */\nexport class RemoteConfigAbortSignal {\n listeners: Array<() => void> = [];\n addEventListener(listener: () => void): void {\n this.listeners.push(listener);\n }\n abort(): void {\n this.listeners.forEach(listener => listener());\n }\n}\n\n/**\n * Defines per-request inputs for the Remote Config fetch request.\n *\n * <p>Modeled after the native {@link Request} interface, but simplified for Remote Config's\n * use case.\n */\nexport interface FetchRequest {\n /**\n * Uses cached config if it is younger than this age.\n *\n * <p>Required because it's defined by settings, which always have a value.\n *\n * <p>Comparable to passing `headers = { 'Cache-Control': max-age <maxAge> }` to the native\n * Fetch API.\n */\n cacheMaxAgeMillis: number;\n\n /**\n * An event bus for the signal to abort a request.\n *\n * <p>Required because all requests should be abortable.\n *\n * <p>Comparable to the native\n * Fetch API's \"signal\" field on its request configuration object\n * https://fetch.spec.whatwg.org/#dom-requestinit-signal.\n *\n * <p>Disambiguation: Remote Config commonly refers to API inputs as\n * \"signals\". See the private ConfigFetchRequestBody interface for those:\n * http://google3/firebase/remote_config/web/src/core/rest_client.ts?l=14&rcl=255515243.\n */\n signal: RemoteConfigAbortSignal;\n\n /**\n * The ETag header value from the last response.\n *\n * <p>Optional in case this is the first request.\n *\n * <p>Comparable to passing `headers = { 'If-None-Match': <eTag> }` to the native Fetch API.\n */\n eTag?: string;\n}\n\n/**\n * Defines a successful response (200 or 304).\n *\n * <p>Modeled after the native {@link Response} interface, but simplified for Remote Config's\n * use case.\n */\nexport interface FetchResponse {\n /**\n * The HTTP status, which is useful for differentiating success responses with data from\n * those without.\n *\n * <p>{@link RemoteConfigClient} is modeled after the native {@link GlobalFetch} interface, so\n * HTTP status is first-class.\n *\n * <p>Disambiguation: the fetch response returns a legacy \"state\" value that is redundant with the\n * HTTP status code. The former is normalized into the latter.\n */\n status: number;\n\n /**\n * Defines the ETag response header value.\n *\n * <p>Only defined for 200 and 304 responses.\n */\n eTag?: string;\n\n /**\n * Defines the map of parameters returned as \"entries\" in the fetch response body.\n *\n * <p>Only defined for 200 responses.\n */\n config?: FirebaseRemoteConfigObject;\n\n // Note: we're not extracting experiment metadata until\n // ABT and Analytics have Web SDKs.\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { Value as ValueType, ValueSource } from '@firebase/remote-config-types';\n\nconst DEFAULT_VALUE_FOR_BOOLEAN = false;\nconst DEFAULT_VALUE_FOR_STRING = '';\nconst DEFAULT_VALUE_FOR_NUMBER = 0;\n\nconst BOOLEAN_TRUTHY_VALUES = ['1', 'true', 't', 'yes', 'y', 'on'];\n\nexport class Value implements ValueType {\n constructor(\n private readonly _source: ValueSource,\n private readonly _value: string = DEFAULT_VALUE_FOR_STRING\n ) {}\n\n asString(): string {\n return this._value;\n }\n\n asBoolean(): boolean {\n if (this._source === 'static') {\n return DEFAULT_VALUE_FOR_BOOLEAN;\n }\n return BOOLEAN_TRUTHY_VALUES.indexOf(this._value.toLowerCase()) >= 0;\n }\n\n asNumber(): number {\n if (this._source === 'static') {\n return DEFAULT_VALUE_FOR_NUMBER;\n }\n let num = Number(this._value);\n if (isNaN(num)) {\n num = DEFAULT_VALUE_FOR_NUMBER;\n }\n return num;\n }\n\n getSource(): ValueSource {\n return this._source;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app-types';\nimport {\n RemoteConfig as RemoteConfigType,\n FetchStatus,\n Settings,\n Value as ValueType,\n LogLevel as RemoteConfigLogLevel\n} from '@firebase/remote-config-types';\nimport { StorageCache } from './storage/storage_cache';\nimport {\n RemoteConfigFetchClient,\n RemoteConfigAbortSignal\n} from './client/remote_config_fetch_client';\nimport { Value } from './value';\nimport { ErrorCode, hasErrorCode } from './errors';\nimport { Storage } from './storage/storage';\nimport { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\n\nconst DEFAULT_FETCH_TIMEOUT_MILLIS = 60 * 1000; // One minute\nconst DEFAULT_CACHE_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; // Twelve hours.\n\n/**\n * Encapsulates business logic mapping network and storage dependencies to the public SDK API.\n *\n * See {@link https://github.com/FirebasePrivate/firebase-js-sdk/blob/master/packages/firebase/index.d.ts|interface documentation} for method descriptions.\n */\nexport class RemoteConfig implements RemoteConfigType {\n // Tracks completion of initialization promise.\n private _isInitializationComplete = false;\n\n // De-duplicates initialization calls.\n private _initializePromise?: Promise<void>;\n\n settings: Settings = {\n fetchTimeoutMillis: DEFAULT_FETCH_TIMEOUT_MILLIS,\n minimumFetchIntervalMillis: DEFAULT_CACHE_MAX_AGE_MILLIS\n };\n\n defaultConfig: { [key: string]: string | number | boolean } = {};\n\n // Based on packages/firestore/src/util/log.ts but not static because we need per-instance levels\n // to differentiate 2p and 3p use-cases.\n setLogLevel(logLevel: RemoteConfigLogLevel): void {\n switch (logLevel) {\n case 'debug':\n this._logger.logLevel = FirebaseLogLevel.DEBUG;\n break;\n case 'silent':\n this._logger.logLevel = FirebaseLogLevel.SILENT;\n break;\n default:\n this._logger.logLevel = FirebaseLogLevel.ERROR;\n }\n }\n\n get fetchTimeMillis(): number {\n return this._storageCache.getLastSuccessfulFetchTimestampMillis() || -1;\n }\n\n get lastFetchStatus(): FetchStatus {\n return this._storageCache.getLastFetchStatus() || 'no-fetch-yet';\n }\n\n constructor(\n // Required by FirebaseServiceFactory interface.\n readonly app: FirebaseApp,\n // JS doesn't support private yet\n // (https://github.com/tc39/proposal-class-fields#private-fields), so we hint using an\n // underscore prefix.\n private readonly _client: RemoteConfigFetchClient,\n private readonly _storageCache: StorageCache,\n private readonly _storage: Storage,\n private readonly _logger: Logger\n ) {}\n\n async activate(): Promise<boolean> {\n const [lastSuccessfulFetchResponse, activeConfigEtag] = await Promise.all([\n this._storage.getLastSuccessfulFetchResponse(),\n this._storage.getActiveConfigEtag()\n ]);\n if (\n !lastSuccessfulFetchResponse ||\n !lastSuccessfulFetchResponse.config ||\n !lastSuccessfulFetchResponse.eTag ||\n lastSuccessfulFetchResponse.eTag === activeConfigEtag\n ) {\n // Either there is no successful fetched config, or is the same as current active\n // config.\n return false;\n }\n await Promise.all([\n this._storageCache.setActiveConfig(lastSuccessfulFetchResponse.config),\n this._storage.setActiveConfigEtag(lastSuccessfulFetchResponse.eTag)\n ]);\n return true;\n }\n\n ensureInitialized(): Promise<void> {\n if (!this._initializePromise) {\n this._initializePromise = this._storageCache\n .loadFromStorage()\n .then(() => {\n this._isInitializationComplete = true;\n });\n }\n return this._initializePromise;\n }\n\n /**\n * @throws a {@link ErrorCode.FETCH_CLIENT_TIMEOUT} if the request takes longer than\n * {@link Settings.fetchTimeoutInSeconds} or\n * {@link DEFAULT_FETCH_TIMEOUT_SECONDS}.\n */\n async fetch(): Promise<void> {\n // Aborts the request after the given timeout, causing the fetch call to\n // reject with an AbortError.\n //\n // <p>Aborting after the request completes is a no-op, so we don't need a\n // corresponding clearTimeout.\n //\n // Locating abort logic here because:\n // * it uses a developer setting (timeout)\n // * it applies to all retries (like curl's max-time arg)\n // * it is consistent with the Fetch API's signal input\n const abortSignal = new RemoteConfigAbortSignal();\n\n setTimeout(async () => {\n // Note a very low delay, eg < 10ms, can elapse before listeners are initialized.\n abortSignal.abort();\n }, this.settings.fetchTimeoutMillis);\n\n // Catches *all* errors thrown by client so status can be set consistently.\n try {\n await this._client.fetch({\n cacheMaxAgeMillis: this.settings.minimumFetchIntervalMillis,\n signal: abortSignal\n });\n\n await this._storageCache.setLastFetchStatus('success');\n } catch (e) {\n const lastFetchStatus = hasErrorCode(e, ErrorCode.FETCH_THROTTLE)\n ? 'throttle'\n : 'failure';\n await this._storageCache.setLastFetchStatus(lastFetchStatus);\n throw e;\n }\n }\n\n async fetchAndActivate(): Promise<boolean> {\n await this.fetch();\n return this.activate();\n }\n\n getAll(): { [key: string]: ValueType } {\n return getAllKeys(\n this._storageCache.getActiveConfig(),\n this.defaultConfig\n ).reduce((allConfigs, key) => {\n allConfigs[key] = this.getValue(key);\n return allConfigs;\n }, {} as { [key: string]: ValueType });\n }\n\n getBoolean(key: string): boolean {\n return this.getValue(key).asBoolean();\n }\n\n getNumber(key: string): number {\n return this.getValue(key).asNumber();\n }\n\n getString(key: string): string {\n return this.getValue(key).asString();\n }\n\n getValue(key: string): ValueType {\n if (!this._isInitializationComplete) {\n this._logger.debug(\n `A value was requested for key \"${key}\" before SDK initialization completed.` +\n ' Await on ensureInitialized if the intent was to get a previously activated value.'\n );\n }\n const activeConfig = this._storageCache.getActiveConfig();\n if (activeConfig && activeConfig[key] !== undefined) {\n return new Value('remote', activeConfig[key]);\n } else if (this.defaultConfig && this.defaultConfig[key] !== undefined) {\n return new Value('default', String(this.defaultConfig[key]));\n }\n this._logger.debug(\n `Returning static value for key \"${key}\".` +\n ' Define a default or remote value if this is unintentional.'\n );\n return new Value('static');\n }\n}\n\n/**\n * Dedupes and returns an array of all the keys of the received objects.\n */\nfunction getAllKeys(obj1: {} = {}, obj2: {} = {}): string[] {\n return Object.keys({ ...obj1, ...obj2 });\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FetchStatus } from '@firebase/remote-config-types';\nimport {\n FetchResponse,\n FirebaseRemoteConfigObject\n} from '../client/remote_config_fetch_client';\nimport { ERROR_FACTORY, ErrorCode } from '../errors';\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * Converts an error event associated with a {@link IDBRequest} to a {@link FirebaseError}.\n */\nfunction toFirebaseError(event: Event, errorCode: ErrorCode): FirebaseError {\n const originalError = (event.target as IDBRequest).error || undefined;\n return ERROR_FACTORY.create(errorCode, {\n originalErrorMessage: originalError && originalError.message\n });\n}\n\n/**\n * A general-purpose store keyed by app + namespace + {@link\n * ProjectNamespaceKeyFieldValue}.\n *\n * <p>The Remote Config SDK can be used with multiple app installations, and each app can interact\n * with multiple namespaces, so this store uses app (ID + name) and namespace as common parent keys\n * for a set of key-value pairs. See {@link Storage#createCompositeKey}.\n *\n * <p>Visible for testing.\n */\nexport const APP_NAMESPACE_STORE = 'app_namespace_store';\n\nconst DB_NAME = 'firebase_remote_config';\nconst DB_VERSION = 1;\n\n/**\n * Encapsulates metadata concerning throttled fetch requests.\n */\nexport interface ThrottleMetadata {\n // The number of times fetch has backed off. Used for resuming backoff after a timeout.\n backoffCount: number;\n // The Unix timestamp in milliseconds when callers can retry a request.\n throttleEndTimeMillis: number;\n}\n\n/**\n * Provides type-safety for the \"key\" field used by {@link APP_NAMESPACE_STORE}.\n *\n * <p>This seems like a small price to avoid potentially subtle bugs caused by a typo.\n */\ntype ProjectNamespaceKeyFieldValue =\n | 'active_config'\n | 'active_config_etag'\n | 'last_fetch_status'\n | 'last_successful_fetch_timestamp_millis'\n | 'last_successful_fetch_response'\n | 'settings'\n | 'throttle_metadata';\n\n// Visible for testing.\nexport function openDatabase(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(DB_NAME, DB_VERSION);\n request.onerror = event => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_OPEN));\n };\n request.onsuccess = event => {\n resolve((event.target as IDBOpenDBRequest).result);\n };\n request.onupgradeneeded = event => {\n const db = (event.target as IDBOpenDBRequest).result;\n\n // We don't use 'break' in this switch statement, the fall-through\n // behavior is what we want, because if there are multiple versions between\n // the old version and the current version, we want ALL the migrations\n // that correspond to those versions to run, not only the last one.\n // eslint-disable-next-line default-case\n switch (event.oldVersion) {\n case 0:\n db.createObjectStore(APP_NAMESPACE_STORE, {\n keyPath: 'compositeKey'\n });\n }\n };\n });\n}\n\n/**\n * Abstracts data persistence.\n */\nexport class Storage {\n /**\n * @param appId enables storage segmentation by app (ID + name).\n * @param appName enables storage segmentation by app (ID + name).\n * @param namespace enables storage segmentation by namespace.\n */\n constructor(\n private readonly appId: string,\n private readonly appName: string,\n private readonly namespace: string,\n private readonly openDbPromise = openDatabase()\n ) {}\n\n getLastFetchStatus(): Promise<FetchStatus | undefined> {\n return this.get<FetchStatus>('last_fetch_status');\n }\n\n setLastFetchStatus(status: FetchStatus): Promise<void> {\n return this.set<FetchStatus>('last_fetch_status', status);\n }\n\n // This is comparable to a cache entry timestamp. If we need to expire other data, we could\n // consider adding timestamp to all storage records and an optional max age arg to getters.\n getLastSuccessfulFetchTimestampMillis(): Promise<number | undefined> {\n return this.get<number>('last_successful_fetch_timestamp_millis');\n }\n\n setLastSuccessfulFetchTimestampMillis(timestamp: number): Promise<void> {\n return this.set<number>(\n 'last_successful_fetch_timestamp_millis',\n timestamp\n );\n }\n\n getLastSuccessfulFetchResponse(): Promise<FetchResponse | undefined> {\n return this.get<FetchResponse>('last_successful_fetch_response');\n }\n\n setLastSuccessfulFetchResponse(response: FetchResponse): Promise<void> {\n return this.set<FetchResponse>('last_successful_fetch_response', response);\n }\n\n getActiveConfig(): Promise<FirebaseRemoteConfigObject | undefined> {\n return this.get<FirebaseRemoteConfigObject>('active_config');\n }\n\n setActiveConfig(config: FirebaseRemoteConfigObject): Promise<void> {\n return this.set<FirebaseRemoteConfigObject>('active_config', config);\n }\n\n getActiveConfigEtag(): Promise<string | undefined> {\n return this.get<string>('active_config_etag');\n }\n\n setActiveConfigEtag(etag: string): Promise<void> {\n return this.set<string>('active_config_etag', etag);\n }\n\n getThrottleMetadata(): Promise<ThrottleMetadata | undefined> {\n return this.get<ThrottleMetadata>('throttle_metadata');\n }\n\n setThrottleMetadata(metadata: ThrottleMetadata): Promise<void> {\n return this.set<ThrottleMetadata>('throttle_metadata', metadata);\n }\n\n deleteThrottleMetadata(): Promise<void> {\n return this.delete('throttle_metadata');\n }\n\n async get<T>(key: ProjectNamespaceKeyFieldValue): Promise<T | undefined> {\n const db = await this.openDbPromise;\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([APP_NAMESPACE_STORE], 'readonly');\n const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n const compositeKey = this.createCompositeKey(key);\n try {\n const request = objectStore.get(compositeKey);\n request.onerror = event => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_GET));\n };\n request.onsuccess = event => {\n const result = (event.target as IDBRequest).result;\n if (result) {\n resolve(result.value);\n } else {\n resolve(undefined);\n }\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_GET, {\n originalErrorMessage: e && e.message\n })\n );\n }\n });\n }\n\n async set<T>(key: ProjectNamespaceKeyFieldValue, value: T): Promise<void> {\n const db = await this.openDbPromise;\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');\n const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n const compositeKey = this.createCompositeKey(key);\n try {\n const request = objectStore.put({\n compositeKey,\n value\n });\n request.onerror = (event: Event) => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_SET));\n };\n request.onsuccess = () => {\n resolve();\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_SET, {\n originalErrorMessage: e && e.message\n })\n );\n }\n });\n }\n\n async delete(key: ProjectNamespaceKeyFieldValue): Promise<void> {\n const db = await this.openDbPromise;\n return new Promise((resolve, reject) => {\n const transaction = db.transaction([APP_NAMESPACE_STORE], 'readwrite');\n const objectStore = transaction.objectStore(APP_NAMESPACE_STORE);\n const compositeKey = this.createCompositeKey(key);\n try {\n const request = objectStore.delete(compositeKey);\n request.onerror = (event: Event) => {\n reject(toFirebaseError(event, ErrorCode.STORAGE_DELETE));\n };\n request.onsuccess = () => {\n resolve();\n };\n } catch (e) {\n reject(\n ERROR_FACTORY.create(ErrorCode.STORAGE_DELETE, {\n originalErrorMessage: e && e.message\n })\n );\n }\n });\n }\n\n // Facilitates composite key functionality (which is unsupported in IE).\n createCompositeKey(key: ProjectNamespaceKeyFieldValue): string {\n return [this.appId, this.appName, this.namespace, key].join();\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 { FetchStatus } from '@firebase/remote-config-types';\nimport { FirebaseRemoteConfigObject } from '../client/remote_config_fetch_client';\nimport { Storage } from './storage';\n\n/**\n * A memory cache layer over storage to support the SDK's synchronous read requirements.\n */\nexport class StorageCache {\n constructor(private readonly storage: Storage) {}\n\n /**\n * Memory caches.\n */\n private lastFetchStatus?: FetchStatus;\n private lastSuccessfulFetchTimestampMillis?: number;\n private activeConfig?: FirebaseRemoteConfigObject;\n\n /**\n * Memory-only getters\n */\n getLastFetchStatus(): FetchStatus | undefined {\n return this.lastFetchStatus;\n }\n\n getLastSuccessfulFetchTimestampMillis(): number | undefined {\n return this.lastSuccessfulFetchTimestampMillis;\n }\n\n getActiveConfig(): FirebaseRemoteConfigObject | undefined {\n return this.activeConfig;\n }\n\n /**\n * Read-ahead getter\n */\n async loadFromStorage(): Promise<void> {\n const lastFetchStatusPromise = this.storage.getLastFetchStatus();\n const lastSuccessfulFetchTimestampMillisPromise = this.storage.getLastSuccessfulFetchTimestampMillis();\n const activeConfigPromise = this.storage.getActiveConfig();\n\n // Note:\n // 1. we consistently check for undefined to avoid clobbering defined values\n // in memory\n // 2. we defer awaiting to improve readability, as opposed to destructuring\n // a Promise.all result, for example\n\n const lastFetchStatus = await lastFetchStatusPromise;\n if (lastFetchStatus) {\n this.lastFetchStatus = lastFetchStatus;\n }\n\n const lastSuccessfulFetchTimestampMillis = await lastSuccessfulFetchTimestampMillisPromise;\n if (lastSuccessfulFetchTimestampMillis) {\n this.lastSuccessfulFetchTimestampMillis = lastSuccessfulFetchTimestampMillis;\n }\n\n const activeConfig = await activeConfigPromise;\n if (activeConfig) {\n this.activeConfig = activeConfig;\n }\n }\n\n /**\n * Write-through setters\n */\n setLastFetchStatus(status: FetchStatus): Promise<void> {\n this.lastFetchStatus = status;\n return this.storage.setLastFetchStatus(status);\n }\n\n setLastSuccessfulFetchTimestampMillis(\n timestampMillis: number\n ): Promise<void> {\n this.lastSuccessfulFetchTimestampMillis = timestampMillis;\n return this.storage.setLastSuccessfulFetchTimestampMillis(timestampMillis);\n }\n\n setActiveConfig(activeConfig: FirebaseRemoteConfigObject): Promise<void> {\n this.activeConfig = activeConfig;\n return this.storage.setActiveConfig(activeConfig);\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 RemoteConfigAbortSignal,\n RemoteConfigFetchClient,\n FetchResponse,\n FetchRequest\n} from './remote_config_fetch_client';\nimport { ThrottleMetadata, Storage } from '../storage/storage';\nimport { calculateBackoffMillis } from './exponential_backoff';\nimport { ErrorCode, ERROR_FACTORY } from '../errors';\nimport { FirebaseError } from '@firebase/util';\n\n/**\n * Supports waiting on a backoff by:\n *\n * <ul>\n * <li>Promisifying setTimeout, so we can set a timeout in our Promise chain</li>\n * <li>Listening on a signal bus for abort events, just like the Fetch API</li>\n * <li>Failing in the same way the Fetch API fails, so timing out a live request and a throttled\n * request appear the same.</li>\n * </ul>\n *\n * <p>Visible for testing.\n */\nexport function setAbortableTimeout(\n signal: RemoteConfigAbortSignal,\n throttleEndTimeMillis: number\n): Promise<void> {\n return new Promise((resolve, reject) => {\n // Derives backoff from given end time, normalizing negative numbers to zero.\n const backoffMillis = Math.max(throttleEndTimeMillis - Date.now(), 0);\n\n const timeout = setTimeout(resolve, backoffMillis);\n\n // Adds listener, rather than sets onabort, because signal is a shared object.\n signal.addEventListener(() => {\n clearTimeout(timeout);\n\n // If the request completes before this timeout, the rejection has no effect.\n reject(\n ERROR_FACTORY.create(ErrorCode.FETCH_THROTTLE, {\n throttleEndTimeMillis\n })\n );\n });\n });\n}\n\n/**\n * Returns true if the {@link Error} indicates a fetch request may succeed later.\n */\nfunction isRetriableError(e: Error): boolean {\n if (!(e instanceof FirebaseError)) {\n return false;\n }\n\n // Uses string index defined by ErrorData, which FirebaseError implements.\n const httpStatus = Number(e['httpStatus']);\n\n return (\n httpStatus === 429 ||\n httpStatus === 500 ||\n httpStatus === 503 ||\n httpStatus === 504\n );\n}\n\n/**\n * Decorates a Client with retry logic.\n *\n * <p>Comparable to CachingClient, but uses backoff logic instead of cache max age and doesn't cache\n * responses (because the SDK has no use for error responses).\n */\nexport class RetryingClient implements RemoteConfigFetchClient {\n constructor(\n private readonly client: RemoteConfigFetchClient,\n private readonly storage: Storage\n ) {}\n\n async fetch(request: FetchRequest): Promise<FetchResponse> {\n const throttleMetadata = (await this.storage.getThrottleMetadata()) || {\n backoffCount: 0,\n throttleEndTimeMillis: Date.now()\n };\n\n return this.attemptFetch(request, throttleMetadata);\n }\n\n /**\n * A recursive helper for attempting a fetch request repeatedly.\n *\n * @throws any non-retriable errors.\n */\n async attemptFetch(\n request: FetchRequest,\n { throttleEndTimeMillis, backoffCount }: ThrottleMetadata\n ): Promise<FetchResponse> {\n // Starts with a (potentially zero) timeout to support resumption from stored state.\n // Ensures the throttle end time is honored if the last attempt timed out.\n // Note the SDK will never make a request if the fetch timeout expires at this point.\n await setAbortableTimeout(request.signal, throttleEndTimeMillis);\n\n try {\n const response = await this.client.fetch(request);\n\n // Note the SDK only clears throttle state if response is success or non-retriable.\n await this.storage.deleteThrottleMetadata();\n\n return response;\n } catch (e) {\n if (!isRetriableError(e)) {\n throw e;\n }\n\n // Increments backoff state.\n const throttleMetadata = {\n throttleEndTimeMillis:\n Date.now() + calculateBackoffMillis(backoffCount),\n backoffCount: backoffCount + 1\n };\n\n // Persists state.\n await this.storage.setThrottleMetadata(throttleMetadata);\n\n return this.attemptFetch(request, throttleMetadata);\n }\n }\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 * The amount of milliseconds to exponentially increase.\n */\nconst INTERVAL_MILLIS = 1000;\n\n/**\n * The factor to backoff by.\n * Should be a number greater than 1.\n */\nconst BACKOFF_FACTOR = 2;\n\n/**\n * The maximum milliseconds to increase to.\n *\n * <p>Visible for testing\n */\nexport const MAX_VALUE_MILLIS = 4 * 60 * 60 * 1000; // Four hours, like iOS and Android.\n\n/**\n * The percentage of backoff time to randomize by.\n * See\n * http://go/safe-client-behavior#step-1-determine-the-appropriate-retry-interval-to-handle-spike-traffic\n * for context.\n *\n * <p>Visible for testing\n */\nexport const RANDOM_FACTOR = 0.5;\n\n/**\n * Based on the backoff method from\n * https://github.com/google/closure-library/blob/master/closure/goog/math/exponentialbackoff.js.\n * Extracted here so we don't need to pass metadata and a stateful ExponentialBackoff object around.\n */\nexport function calculateBackoffMillis(backoffCount: number): number {\n // Calculates an exponentially increasing value.\n // Deviation: calculates value from count and a constant interval, so we only need to save value\n // and count to restore state.\n const currBaseValue =\n INTERVAL_MILLIS * Math.pow(BACKOFF_FACTOR, backoffCount);\n\n // A random \"fuzz\" to avoid waves of retries.\n // Deviation: randomFactor is required.\n const randomWait = Math.round(\n // A fraction of the backoff value to add/subtract.\n // Deviation: changes multiplication order to improve readability.\n RANDOM_FACTOR *\n currBaseValue *\n // A random float (rounded to int by Math.round above) in the range [-1, 1]. Determines\n // if we add or subtract.\n (Math.random() - 0.5) *\n 2\n );\n\n // Limits backoff to max to avoid effectively permanent backoff.\n return Math.min(MAX_VALUE_MILLIS, currBaseValue + randomWait);\n}\n","/**\n * @license\n * Copyright 2019 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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 '@firebase/app';\nimport '@firebase/installations';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { RemoteConfig as RemoteConfigType } from '@firebase/remote-config-types';\nimport { CachingClient } from './src/client/caching_client';\nimport { RestClient } from './src/client/rest_client';\nimport { RemoteConfig } from './src/remote_config';\nimport { Storage } from './src/storage/storage';\nimport { StorageCache } from './src/storage/storage_cache';\nimport { ERROR_FACTORY, ErrorCode } from './src/errors';\nimport { RetryingClient } from './src/client/retrying_client';\nimport { Logger, LogLevel as FirebaseLogLevel } from '@firebase/logger';\nimport { name as packageName, version } from './package.json';\nimport {\n Component,\n ComponentType,\n ComponentContainer\n} from '@firebase/component';\n\n// Facilitates debugging by enabling settings changes without rebuilding asset.\n// Note these debug options are not part of a documented, supported API and can change at any time.\n// Consolidates debug options for easier discovery.\n// Uses transient variables on window to avoid lingering state causing panic.\ndeclare global {\n interface Window {\n FIREBASE_REMOTE_CONFIG_URL_BASE: string;\n }\n}\n\nexport function registerRemoteConfig(\n firebaseInstance: _FirebaseNamespace\n): void {\n firebaseInstance.INTERNAL.registerComponent(\n new Component(\n 'remoteConfig',\n remoteConfigFactory,\n ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n\n firebaseInstance.registerVersion(packageName, version);\n\n function remoteConfigFactory(\n container: ComponentContainer,\n namespace?: string\n ): RemoteConfig {\n /* Dependencies */\n // getImmediate for FirebaseApp will always succeed\n const app = container.getProvider('app').getImmediate();\n // The following call will always succeed because rc has `import '@firebase/installations'`\n const installations = container.getProvider('installations').getImmediate();\n\n // Guards against the SDK being used in non-browser environments.\n if (typeof window === 'undefined') {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_WINDOW);\n }\n\n // Normalizes optional inputs.\n const { projectId, apiKey, appId } = app.options;\n if (!projectId) {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_PROJECT_ID);\n }\n if (!apiKey) {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_API_KEY);\n }\n if (!appId) {\n throw ERROR_FACTORY.create(ErrorCode.REGISTRATION_APP_ID);\n }\n namespace = namespace || 'firebase';\n\n const storage = new Storage(appId, app.name, namespace);\n const storageCache = new StorageCache(storage);\n\n const logger = new Logger(packageName);\n\n // Sets ERROR as the default log level.\n // See RemoteConfig#setLogLevel for corresponding normalization to ERROR log level.\n logger.logLevel = FirebaseLogLevel.ERROR;\n\n const restClient = new RestClient(\n installations,\n // Uses the JS SDK version, by which the RC package version can be deduced, if necessary.\n firebaseInstance.SDK_VERSION,\n namespace,\n projectId,\n apiKey,\n appId\n );\n const retryingClient = new RetryingClient(restClient, storage);\n const cachingClient = new CachingClient(\n retryingClient,\n storage,\n storageCache,\n logger\n );\n\n const remoteConfigInstance = new RemoteConfig(\n app,\n cachingClient,\n storageCache,\n storage,\n logger\n );\n\n // Starts warming cache.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n remoteConfigInstance.ensureInitialized();\n\n return remoteConfigInstance;\n }\n}\n\nregisterRemoteConfig(firebase as _FirebaseNamespace);\n\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n remoteConfig?: {\n (app?: FirebaseApp): RemoteConfigType;\n };\n }\n interface FirebaseApp {\n remoteConfig(): RemoteConfigType;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS 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\nconsole.warn(`\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the CDN builds, these are available in the following manner\n(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):\n\nhttps://www.gstatic.com/firebasejs/5.0.0/firebase-<PACKAGE>.js\n`);\n\nimport '@firebase/polyfill';\nimport firebase from '../app';\nimport { name, version } from '../package.json';\n\nimport '../auth';\nimport '../database';\nimport '../firestore';\nimport '../functions';\nimport '../messaging';\nimport '../storage';\nimport '../performance';\nimport '../analytics';\nimport '../remote-config';\n\nfirebase.registerVersion(name, version, 'cdn');\n\nexport default firebase;\n"],"names":["self","fetch","support","Symbol","Blob","e","viewClasses","isDataView","obj","DataView","prototype","isPrototypeOf","isArrayBufferView","ArrayBuffer","isView","indexOf","Object","toString","call","Headers","append","name","value","normalizeName","normalizeValue","oldValue","this","map","get","has","hasOwnProperty","set","forEach","callback","thisArg","keys","items","push","iteratorFor","values","entries","iterator","methods","Request","clone","body","_bodyInit","Body","Response","status","statusText","headers","url","error","response","type","redirectStatuses","redirect","RangeError","location","input","init","Promise","resolve","reject","request","xhr","XMLHttpRequest","onload","options","rawHeaders","replace","split","line","parts","key","shift","trim","join","parseHeaders","getAllResponseHeaders","responseURL","responseText","onerror","TypeError","ontimeout","open","method","credentials","withCredentials","responseType","setRequestHeader","send","polyfill","String","test","toLowerCase","next","done","undefined","Array","isArray","header","getOwnPropertyNames","consumed","bodyUsed","fileReaderReady","reader","result","readBlobAsArrayBuffer","blob","FileReader","promise","readAsArrayBuffer","bufferClone","buf","slice","view","Uint8Array","byteLength","buffer","_initBody","_bodyText","_bodyBlob","FormData","_bodyFormData","URLSearchParams","_bodyArrayBuffer","Error","rejected","arrayBuffer","then","text","readAsText","readBlobAsText","chars","length","i","fromCharCode","readArrayBufferAsText","formData","decode","json","JSON","parse","mode","upcased","toUpperCase","normalizeMethod","referrer","form","bytes","decodeURIComponent","bodyInit","ok","check","it","Math","exec","EXISTS","document","createElement","isObject","PREFERRED_STRING","fn","val","valueOf","bitmap","enumerable","configurable","writable","createNonEnumerableProperty","global","id","postfix","WellKnownSymbolsStore","NATIVE_SYMBOL","createWellKnownSymbol","globalThis","window","Function","fails","defineProperty","DESCRIPTORS","a","nativeDefineProperty","O","P","Attributes","anObject","toPrimitive","IE8_DOM_DEFINE","object","definePropertyModule","f","createPropertyDescriptor","SHARED","setGlobal","module","store","version","copyright","random","getOwnPropertySymbols","sham","shared","USE_SYMBOL_AS_UID","withoutSetter","uid","wellKnownSymbol","functionToString","inspectSource","WeakMap","NATIVE_WEAK_MAP","wmget","wmhas","wmset","metadata","STATE","sharedKey","hiddenKeys","objectHas","enforce","getterFor","TYPE","state","getInternalState","InternalStateModule","enforceInternalState","TEMPLATE","unsafe","simple","noTargetGet","source","TO_STRING_TAG","CORRECT_ARGUMENTS","classofRaw","arguments","TO_STRING_TAG_SUPPORT","tag","tryGet","callee","classof","redefine","argument","isNaN","floor","ceil","createMethod","CONVERT_TO_STRING","$this","pos","first","second","S","requireObjectCoercible","position","toInteger","size","charCodeAt","charAt","IndexedObject","aFunction","variable","namespace","path","min","IS_INCLUDES","el","fromIndex","toIndexedObject","toLength","index","integer","max","toAbsoluteIndex","names","target","ownKeys","getOwnPropertyDescriptor","getOwnPropertyDescriptorModule","isForced","feature","detection","data","normalize","POLYFILL","NATIVE","targetProperty","sourceProperty","descriptor","TARGET","GLOBAL","STATIC","stat","forced","copyConstructorProperties","IteratorPrototype","PrototypeOfArrayIteratorPrototype","arrayIterator","codeAt","nativePropertyIsEnumerable","propertyIsEnumerable","1","V","nativeGetOwnPropertyDescriptor","propertyIsEnumerableModule","includes","enumBugKeys","concat","internalObjectKeys","getBuiltIn","getOwnPropertyNamesModule","getOwnPropertySymbolsModule","replacement","string","require$$0","F","constructor","getPrototypeOf","IE_PROTO","ObjectPrototype","CORRECT_PROTOTYPE_GETTER","toObject","ITERATOR","BUGGY_SAFARI_ITERATORS","EmptyConstructor","scriptTag","content","LT","SCRIPT","activeXDocument","defineProperties","Properties","objectKeys","PROTOTYPE","NullProtoObject","domain","ActiveXObject","write","close","temp","parentWindow","NullProtoObjectViaActiveX","iframeDocument","iframe","documentCreateElement","style","display","html","appendChild","src","contentWindow","NullProtoObjectViaIFrame","TAG","returnThis","Iterable","NAME","IteratorConstructor","DEFAULT","IS_SET","FORCED","getIterationMethod","KIND","defaultIterator","IterablePrototype","VALUES","ENTRIES","create","setToStringTag","Iterators","createIteratorConstructor","CurrentIteratorPrototype","KEY","INCORRECT_VALUES_NAME","nativeIterator","anyNativeIterator","setPrototypeOf","$","proto","setter","CORRECT_SETTER","aPossiblePrototype","__proto__","IteratorsCore","STRING_ITERATOR","setInternalState","defineIterator","iterated","point","CSSRuleList","CSSStyleDeclaration","CSSValueList","ClientRectList","DOMRectList","DOMStringList","DOMTokenList","DataTransferItemList","FileList","HTMLAllCollection","HTMLCollection","HTMLFormElement","HTMLSelectElement","MediaList","MimeTypeArray","NamedNodeMap","NodeList","PaintRequestList","Plugin","PluginArray","SVGLengthList","SVGNumberList","SVGPathSegList","SVGPointList","SVGStringList","SVGTransformList","SourceBufferList","StyleSheetList","TextTrackCueList","TextTrackList","TouchList","UNSCOPABLES","ArrayPrototype","ARRAY_ITERATOR","kind","Arguments","addToUnscopables","ArrayValues","ArrayIteratorMethods","COLLECTION_NAME","DOMIterables","Collection","CollectionPrototype","METHOD_NAME","CONSTRUCTOR_NAME","Constructor","SPECIES","that","b","c","apply","returnMethod","Result","stopped","iterable","AS_ENTRIES","IS_ITERATOR","iterFn","step","boundFunction","bind","getIteratorMethod","isArrayIteratorMethod","callWithSafeIterationClosing","stop","SAFE_CLOSING","called","iteratorWithReturn","return","from","SKIP_CLOSING","ITERATION_SUPPORT","defaultConstructor","C","run","queue","runner","listener","event","post","postMessage","protocol","host","defer","channel","port","userAgent","setImmediate","clear","clearImmediate","process","MessageChannel","Dispatch","counter","ONREADYSTATECHANGE","args","nextTick","now","IS_IOS","port2","port1","onmessage","addEventListener","importScripts","removeChild","setTimeout","flush","head","last","notify","toggle","node","macrotask","require$$1","MutationObserver","WebKitMutationObserver","IS_NODE","queueMicrotaskDescriptor","queueMicrotask","parent","exit","enter","createTextNode","observe","characterData","PromiseCapability","$$resolve","$$reject","x","promiseCapability","newPromiseCapability","match","task","versions","v8","isThenable","isReject","notified","chain","reactions","microtask","exited","reaction","handler","fail","rejection","onHandleUnhandled","onUnhandled","dispatchEvent","reason","DISPATCH_EVENT","createEvent","initEvent","UNHANDLED_REJECTION","console","hostReportErrors","unwrap","internalReject","Internal","OwnPromiseCapability","PromiseWrapper","nativeThen","PROMISE","getInternalPromiseState","PromiseConstructor","NativePromise","$fetch","newPromiseCapabilityModule","newGenericPromiseCapability","V8_VERSION","PromiseRejectionEvent","FakePromise","INCORRECT_ITERATION","checkCorrectnessOfIteration","all","isUnhandled","perform","emit","internalResolve","wrapper","executor","anInstance","redefineAll","onFulfilled","onRejected","speciesConstructor","catch","promiseResolve","wrap","setSpecies","r","capability","$promiseResolve","remaining","iterate","alreadyCalled","race","allSettled","NON_GENERIC","real","finally","onFinally","isFunction","getInternalAggregateErrorState","$AggregateError","errors","message","errorsArray","AggregateError","try","callbackfn","PROMISE_ANY_ERROR","any","alreadyResolved","alreadyRejected","originalArray","IS_MAP","IS_FILTER","IS_SOME","IS_EVERY","IS_FIND_INDEX","NO_HOLES","specificCreate","arraySpeciesCreate","thrower","cache","ACCESSORS","argument0","argument1","arg","filter","some","every","find","findIndex","$find","FIND","SKIPS_HOLES","USES_TO_LENGTH","arrayMethodUsesToLength","CONSTRUCTOR","METHOD","$findIndex","entryUnbind","FIND_INDEX","propertyKey","arrayLike","argumentsLength","mapfn","mapping","iteratorMethod","createProperty","$some","STRICT_METHOD","isTypedArray","TypedArrayConstructorsList","Int8Array","Int8ArrayPrototype","Uint8ClampedArray","Uint8ClampedArrayPrototype","TypedArray","TypedArrayPrototype","TYPED_ARRAY_TAG","NATIVE_ARRAY_BUFFER_VIEWS","NATIVE_ARRAY_BUFFER","opera","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","typedArrayValues","arrayValues","aTypedArray","property","ARRAY","TypedArrayConstructor","ArrayIterators","arrayKeys","arrayEntries","ArrayBufferViewCore","exportTypedArrayMethod","nativeTypedArrayIterator","CORRECT_ITER_NAME","nativeAssign","assign","A","B","symbol","alphabet","chr","T","j","TO_ENTRIES","$entries","$values","isRegExp","MATCH","regexp","correctIsRegExpLogic","searchString","notARegExp","nativeStartsWith","startsWith","CORRECT_IS_REGEXP_LOGIC","MDN_POLYFILL_BUG","search","repeat","count","str","n","Infinity","isConcatSpreadable","spreadable","IS_CONCAT_SPREADABLE","MAX_SAFE_INTEGER","MAXIMUM_ALLOWED_INDEX_EXCEEDED","IS_CONCAT_SPREADABLE_SUPPORT","array","SPECIES_SUPPORT","foo","Boolean","k","len","E","wrappedWellKnownSymbolModule","description","AllSymbols","nativeObjectCreate","$Symbol","SYMBOL","$defineProperties","properties","$getOwnPropertySymbols","$forEach","$propertyIsEnumerable","$defineProperty","$getOwnPropertyDescriptor","ObjectPrototypeSymbols","HIDDEN","$getOwnPropertyNames","nativeGetOwnPropertyNames","windowNames","getWindowNames","TO_PRIMITIVE","$stringify","getOwnPropertyNamesExternal","StringToSymbolRegistry","SymbolToStringRegistry","QObject","USE_SETTER","findChild","setSymbolDescriptor","ObjectPrototypeDescriptor","isSymbol","IS_OBJECT_PROTOTYPE","defineWellKnownSymbol","for","keyFor","sym","useSetter","useSimple","FORCED_JSON_STRINGIFY","stringify","replacer","space","$replacer","NativeSymbol","EmptyStringDescriptionStore","SymbolWrapper","symbolPrototype","symbolToString","native","desc","WrappedWellKnownSymbolModule","common","fixMethod","nativeMethod","NativePrototype","IS_WEAK","ADDER","NativeConstructor","exported","getConstructor","InternalMetadataModule","REQUIRED","instance","HASNT_CHAINING","THROWS_ON_PRIMITIVES","ACCEPT_ITERABLES","BUGGY_ZERO","$instance","dummy","Wrapper","NewTarget","NewTargetPrototype","inheritIfRequired","setStrong","mapFn","nextItem","isExtensible","preventExtensions","setMetadata","METADATA","objectID","weakData","meta","fastKey","getWeakData","onFreeze","FREEZING","internalStateGetterFor","define","previous","entry","getEntry","removed","delete","prev","add","ITERATOR_NAME","getInternalCollectionState","getInternalIteratorState","collection","collectionStrong","Map","of","wasDeleted","remover","allDeleted","IS_PURE","deleteAll","collectionDeleteAll","getMapIterator","newMap","findKey","groupBy","keyDerivative","element","derivedKey","searchElement","y","sameValueZero","keyBy","keyOf","mapKeys","mapValues","merge","reduce","noInitial","accumulator","update","isPresentInMap","updateFn","insertFn","upsert","$upsert","updateOrInsert","Set","addAll","adder","getSetIterator","difference","newSet","intersection","hasCheck","isDisjointFrom","isSubsetOf","getIterator","otherSet","isSupersetOf","separator","sep","symmetricDifference","union","isInteger","isFinite","Number","extendStatics","d","p","__extends","__","__assign","t","s","__awaiter","_arguments","generator","fulfilled","adopt","__generator","g","_","label","sent","trys","ops","verb","throw","v","op","pop","__values","o","m","__read","ar","__spread","__spreadArrays","il","jl","stringToByteArray","out","base64Decode","base64","decodeString","CONSTANTS","NODE_CLIENT","NODE_ADMIN","SDK_VERSION","assert","assertion","assertionError","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","webSafe","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte1","outByte2","outByte3","outByte4","encodeString","btoa","c1","c2","u","c3","byteArrayToString","decodeStringToByteArray","charToByteMap","byte4","deepCopy","deepExtend","Date","getTime","prop","Deferred","_this","getUA","navigator","isMobileCordova","isReactNative","isNodeSdk","code","_super","FirebaseError","captureStackTrace","ErrorFactory","_i","customData","fullCode","service","template","PATTERN","replaceTemplate","fullMessage","serviceName","_b","_a","warn","jsonEval","token","claims","signature","contains","safeGet","isEmpty","contextObj","res","Sha1","chain_","inbuf_","total_","offset","W","W_","lengthMinusBlock","blockSize","buf_","inbuf","compress_","digest","totalBits","pad_","reset","createSubscribe","onNoObservers","proxy","ObserverProxy","subscribe","forEachObserver","observer","complete","nextOrObserver","methods_1","implementsAnyMethods","noop","unsub","unsubscribeOne","observers","finalized","finalError","observerCount","sendOne","err","validateArgCount","fnName","minCount","maxCount","argCount","argError","errorPrefix","argumentNumber","optional","argName","validateCallback","validateContextObject","context","stringLength","Component","instantiationMode","multipleInstances","props","serviceProps","instanceFactory","DEFAULT_ENTRY_NAME","Provider","identifier","normalizedIdentifier","normalizeInstanceIdentifier","instancesDeferred","deferred","getOrInitializeService","component","isComponentEager","_d","instanceIdentifier","instanceDeferred","instances","services","INTERNAL","container","normalizeIdentifierForFactory","ComponentContainer","provider","getProvider","isComponentSet","setComponent","providers","addComponent","LogLevel","defaultLogHandler","logType","logLevel","toISOString","ConsoleMethod","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","info","INFO","WARN","ERROR","silent","SILENT","defaultLogLevel","Logger","_logLevel","_logHandler","_userLogHandler","setLogLevel","level","newLevel","inst","ERRORS","ERROR_FACTORY","PLATFORM_LOG_STRING","appName","logger","FirebaseAppImpl","checkDestroyed_","automaticDataCollectionEnabled_","name_","options_","firebase_","removeApp","getProviders","isDeleted_","getImmediate","clearInstance","addOrOverwriteComponent","config","automaticDataCollectionEnabled","_addComponent","components","log","createFirebaseNamespaceCore","firebaseAppImpl","apps","__esModule","initializeApp","rawConfig","app","registerVersion","libraryKeyOrName","variant","library","libraryMismatch","versionMismatch","warning","registerComponent","onLog","logCallback","customLogLevel","userLogHandler","ignored","instances_1","setUserLogHandler","useAsService","componentName","serviceNamespace","appArg","_getService","firebase","createFirebaseNamespace","extendNamespace","PlatformLoggerService","getComponent","isVersionServiceProvider","logString","sdkVersion","firebaseNamespace","isNode","$jscomp.defineProperty","$jscomp.global","$jscomp.getGlobal","$jscomp.arrayIteratorImpl","$jscomp.polyfill","h","Q","xa","ud","$jscomp.makeIterator","goog","goog.global","goog.NONCE_PATTERN_","goog.cspNonce_","goog.typeOf","className","goog.isArrayLike","goog.isFunction","goog.isObject","goog.UID_PROPERTY_","goog.uidCounter_","selfObj","var_args","goog.bindJs_","boundArgs","newArgs","goog.bind","goog.bindNative_","goog.partial","goog.now","childCtor","parentCtor","tempCtor","fireauth.AuthError","serverResponse","fireauth.AuthError.ERROR_CODE_PREFIX","fireauth.AuthError.MESSAGES_","fireauth.AuthError.ERROR_CODE_PREFIX.length","goog.inherits","fireauth.AuthError.prototype.toPlainObject","fireauth.AuthError.prototype.toJSON","Aa","ADMIN_ONLY_OPERATION","ARGUMENT_ERROR","APP_NOT_AUTHORIZED","APP_NOT_INSTALLED","CAPTCHA_CHECK_FAILED","CODE_EXPIRED","CORDOVA_NOT_READY","CORS_UNSUPPORTED","CREDENTIAL_ALREADY_IN_USE","CREDENTIAL_MISMATCH","CREDENTIAL_TOO_OLD_LOGIN_AGAIN","DYNAMIC_LINK_NOT_ACTIVATED","EMAIL_CHANGE_NEEDS_VERIFICATION","EMAIL_EXISTS","EXPIRED_OOB_CODE","EXPIRED_POPUP_REQUEST","INTERNAL_ERROR","INVALID_APP_CREDENTIAL","INVALID_APP_ID","INVALID_AUTH","INVALID_AUTH_EVENT","INVALID_CODE","INVALID_CONTINUE_URI","INVALID_CORDOVA_CONFIGURATION","INVALID_CUSTOM_TOKEN","INVALID_DYNAMIC_LINK_DOMAIN","INVALID_EMAIL","INVALID_API_KEY","INVALID_CERT_HASH","INVALID_IDP_RESPONSE","INVALID_MESSAGE_PAYLOAD","INVALID_MFA_PENDING_CREDENTIAL","INVALID_OAUTH_PROVIDER","INVALID_OAUTH_CLIENT_ID","INVALID_ORIGIN","INVALID_OOB_CODE","INVALID_PASSWORD","INVALID_PERSISTENCE","INVALID_PHONE_NUMBER","INVALID_PROVIDER_ID","INVALID_RECIPIENT_EMAIL","INVALID_SENDER","INVALID_SESSION_INFO","INVALID_TENANT_ID","MFA_ENROLLMENT_NOT_FOUND","MFA_REQUIRED","MISSING_ANDROID_PACKAGE_NAME","MISSING_AUTH_DOMAIN","MISSING_APP_CREDENTIAL","MISSING_CODE","MISSING_CONTINUE_URI","MISSING_IFRAME_START","MISSING_IOS_BUNDLE_ID","MISSING_MFA_ENROLLMENT_ID","MISSING_MFA_PENDING_CREDENTIAL","MISSING_OR_INVALID_NONCE","MISSING_PHONE_NUMBER","MISSING_SESSION_INFO","MODULE_DESTROYED","NEED_CONFIRMATION","NETWORK_REQUEST_FAILED","NO_AUTH_EVENT","NO_SUCH_PROVIDER","NULL_USER","OPERATION_NOT_ALLOWED","OPERATION_NOT_SUPPORTED","POPUP_BLOCKED","POPUP_CLOSED_BY_USER","PROVIDER_ALREADY_LINKED","QUOTA_EXCEEDED","REDIRECT_CANCELLED_BY_USER","REDIRECT_OPERATION_PENDING","REJECTED_CREDENTIAL","SECOND_FACTOR_EXISTS","SECOND_FACTOR_LIMIT_EXCEEDED","TENANT_ID_MISMATCH","TIMEOUT","TOKEN_EXPIRED","TOO_MANY_ATTEMPTS_TRY_LATER","UNAUTHORIZED_DOMAIN","UNSUPPORTED_FIRST_FACTOR","UNSUPPORTED_PERSISTENCE","UNSUPPORTED_TENANT_OPERATION","UNVERIFIED_EMAIL","USER_CANCELLED","USER_DELETED","USER_DISABLED","USER_MISMATCH","USER_SIGNED_OUT","WEAK_PASSWORD","WEB_STORAGE_UNSUPPORTED","fireauth.constants.Endpoint","BOQ","firebaseAuthEndpoint","secureTokenEndpoint","identityPlatformEndpoint","PRODUCTION","STAGING","TEST","opt_id","endpointKey","firebaseEndpoint","endpoint","goog.Thenable.isImplementedBy","goog.debug.Error","opt_msg","stack","goog.asserts.AssertionError","messagePattern","messageArgs","returnString","subLast","splitParts","opt_message","put","item","goog.async.WorkQueue","fireauth.constants.getEndpointConfig","goog.async.FreeList","goog.async.WorkQueue.freelist_","goog.async.WorkItem","goog.async.WorkQueue.prototype.add","scope","goog.async.WorkQueue.freelist_.get","goog.async.WorkItem.prototype.set","goog.async.WorkItem.prototype.reset","goog.array.indexOf","arr","opt_fromIndex","goog.array.forEach","opt_obj","l","arr2","goog.array.filter","resLength","goog.array.map","goog.array.some","goog.array.contains","goog.array.remove","rv","goog.array.removeAllIf","removedCount","goog.array.concat","goog.array.toArray","goog.labs.userAgent.util.userAgent_","goog.string.internal.trim","goog.string.internal.AMP_RE_","goog.string.internal.LT_RE_","goog.string.internal.GT_RE_","goog.string.internal.QUOT_RE_","goog.string.internal.SINGLE_QUOTE_RE_","goog.string.internal.NULL_RE_","goog.string.internal.ALL_RE_","subString","goog.string.internal.compareElements_","left","right","goog.global.navigator","fb","goog.labs.userAgent.util.matchUserAgent","goog.object.forEach","goog.object.isEmpty","goog.object.clone","goog.object.PROTOTYPE_FIELDS_","goog.object.PROTOTYPE_FIELDS_.length","goog.dom.asserts.assertIsElementType_","typename","doc","win","ex","goog.string.Const","opt_token","opt_content","goog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_","goog.string.Const.TYPE_MARKER_","stringConst","goog.string.Const.prototype.getTypedStringValue","goog.string.Const.prototype.toString","goog.string.Const.EMPTY","goog.html.TrustedResourceUrl","goog.html.TrustedResourceUrl.CONSTRUCTOR_TOKEN_PRIVATE_","goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_","trustedResourceUrl","goog.html.TrustedResourceUrl.format","format","formatStr","goog.string.Const.unwrap","goog.html.TrustedResourceUrl.BASE_URL_.test","goog.html.TrustedResourceUrl.FORMAT_MARKER_","encodeURIComponent","goog.html.TrustedResourceUrl.prototype.getTypedStringValue","goog.html.TrustedResourceUrl.prototype.toString","goog.html.TrustedResourceUrl.BASE_URL_","goog.html.SafeUrl","goog.html.SafeUrl.CONSTRUCTOR_TOKEN_PRIVATE_","goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_","safeUrl","goog.html.SafeUrl.prototype.getTypedStringValue","goog.html.SafeUrl.prototype.toString","goog.html.SAFE_URL_PATTERN_","goog.html.SafeUrl.INNOCUOUS_STRING","goog.html.SafeHtml","goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_","safeHtml","goog.html.SafeHtml.prototype.getTypedStringValue","goog.html.SafeHtml.prototype.toString","goog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_","initSecurityPrivateDoNotAccessOrElse_","goog.html.SafeHtml.EMPTY","goog.string.subs","subsArguments","goog.string.htmlEscape","goog.string.internal.ALL_RE_.test","goog.reflect.sinkValue","goog.nullFunction","goog.userAgent.VERSION","goog.userAgent.OPERA","goog.userAgent.IE","goog.userAgent.EDGE","goog.userAgent.EDGE_OR_IE","goog.userAgent.GECKO","goog.string.internal.contains","goog.userAgent.WEBKIT","docMode","goog.userAgent.getDocumentMode_","parseFloat","Yb","cc","goog.userAgent.isVersionOrHigherCache_","valueFn","cacheObj","order","v1Subs","v2Subs","subCount","subIdx","v1Sub","v2Sub","v1Comp","v2Comp","parseInt","getContext","contextName","goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES","documentMode","goog.userAgent.DOCUMENT_MODE","goog.dom.getElementHelper_","goog.dom.setProperties","goog.dom.DIRECT_ATTRIBUTE_MAP_.hasOwnProperty","goog.dom.DIRECT_ATTRIBUTE_MAP_","prefix","mc","pc","cellpadding","cellspacing","colspan","frameborder","height","maxlength","nonce","role","rowspan","usemap","valign","width","tagName","opt_attributes","attributes","tagNameArr","goog.dom.createElement_","goog.dom.append_","childHandler","child","startIndex","goog.dom.isNodeList","goog.async.throwException","exception","goog.global.setTimeout","Channel","goog.dom.TagName.IFRAME","goog.dom.safe.setIframeSrc","goog.html.TrustedResourceUrl.unwrapTrustedScriptURL","goog.html.SafeHtml.unwrapTrustedHTML","origin","cb","tail","goog.async.run","opt_context","goog.async.run.schedule_","goog.global.Promise","goog.global.Promise.resolve","goog.async.run.processWorkQueue","goog.global.setImmediate","goog.global.Window","goog.async.nextTick.setImmediate_","goog.async.nextTick.getSetImmediateEmulator_","goog.async.run.initializeRunner_","goog.async.run.workQueueScheduled_","goog.async.run.workQueue_","goog.async.WorkQueue.prototype.remove","goog.async.run.workQueue_.remove","goog.async.WorkQueue.freelist_.put","goog.Promise","resolver","goog.Promise.State_.PENDING","resolve_","goog.Promise.State_.FULFILLED","goog.Promise.State_.REJECTED","PENDING","FULFILLED","REJECTED","goog.Promise.CallbackEntry_","goog.Promise.CallbackEntry_.prototype.reset","goog.Promise.freelist_","goog.Promise.freelist_.get","goog.Promise.resolve","opt_value","goog.Promise.reject","opt_reason","goog.Promise.resolveThen_","goog.Promise.maybeThen_","goog.Promise.allSettled","promises","toSettle","results","onSettled","goog.Promise.prototype.addCallbackEntry_","callbackEntry","hasEntry_","scheduleCallbacks_","queueEntry_","goog.Promise.prototype.addChildPromise_","goog.Promise.getCallbackEntry_","goog.Promise.prototype.resolve_","BLOCKED","goog.Promise.addUnhandledRejection_","goog.Promise.handleRejection_.call","goog.Promise.tryThen_","thenable","goog.Promise.prototype.scheduleCallbacks_","goog.Promise.prototype.popEntry_","goog.Promise.prototype.executeCallback_","goog.Promise.invokeCallback_","goog.Promise.freelist_.put","goog.Promise.prototype.then","opt_onFulfilled","opt_onRejected","addChildPromise_","D","goog.Promise.prototype.thenAlways","addCallbackEntry_","goog.Promise.prototype.thenCatch","goog.Promise.prototype.cancel","goog.Promise.CancellationError","goog.Promise.prototype.cancelInternal_","parent_","childCount","childEntry","beforeChildEntry","childPromise","cancelInternal_","removeEntryAfter_","popEntry_","executeCallback_","goog.Promise.prototype","goog.Promise.prototype.unblockAndFulfill_","goog.Promise.prototype.unblockAndReject_","goog.Promise.prototype.executeCallbacks_","goog.Promise.handleRejection_","goog.debug.Error.call","goog.Disposable","OFF","goog.Disposable.prototype.dispose","goog.Disposable.MONITORING_MODE","goog.Disposable.MonitoringMode.OFF","goog.getUid","goog.Disposable.prototype.disposeInternal","goog.debug.freezeInternal_","HAS_W3C_EVENT_SUPPORT","SET_KEY_CODE_TO_PREVENT_DEFAULT","goog.userAgent.isVersionOrHigher","PASSIVE_EVENTS","goog.global.addEventListener","passive","goog.global.removeEventListener","goog.events.Event","opt_target","goog.events.BrowserEvent","opt_e","opt_currentTarget","goog.events.Event.call","relevantTouch","relatedTarget","MOUSEOVER","MOUSEOUT","goog.events.BrowserEvent.IE_POINTER_TYPE_MAP","goog.events.Event.prototype.preventDefault","2","TOUCH","3","PEN","4","MOUSE","goog.events.BrowserEvent.prototype.preventDefault","goog.events.BrowserEvent.superClass_.preventDefault.call","be","goog.events.BrowserFeature.SET_KEY_CODE_TO_PREVENT_DEFAULT","VK_F1","VK_F12","goog.events.BrowserEvent.prototype.getBrowserEvent","goog.events.Listenable.IMPLEMENTED_BY_PROP","goog.events.ListenableKey.counter_","goog.events.Listener","capture","opt_handler","goog.events.Listener.prototype.markAsRemoved","goog.events.ListenerMap","goog.events.ListenerMap.prototype.removeByKey","markAsRemoved","goog.events.ListenerMap.findListenerIndex_","listenerArray","opt_useCapture","opt_listenerScope","listenerObj","goog.events.ListenerMap.prototype.add","callOnce","typeStr","goog.events.LISTENER_MAP_PROP_","goog.events.onStringMap_","opt_options","goog.events.listenOnce","goog.events.listen","goog.events.wrapListener","listen","goog.events.listen_","listenerMap","goog.events.getListenerMap_","goog.events.getProxy","proxyCallbackFunction","goog.events.handleBrowserEvent_","goog.events.BrowserFeature.HAS_W3C_EVENT_SUPPORT","eventObject","goog.events.BrowserFeature.PASSIVE_EVENTS","goog.events.getOnString_","listenOnce","goog.events.unlisten","eventTargetListeners_","goog.events.unlistenByKey","removeByKey","goog.events.onString_","goog.events.fireListeners_","retval","goog.events.fireListener","listenerFn","listenerHandler","opt_evt","cur","ieEvent","useReturnValue","ancestors","evt","goog.events.LISTENER_WRAPPER_PROP_","goog.events.EventTarget","goog.Disposable.call","goog.events.EventTarget.prototype.listen","goog.events.EventTarget.prototype.listenOnce","goog.events.EventTarget.prototype.fireListeners","unlistenByKey","goog.Timer.callOnce","opt_delay","goog.Timer.promise","delay","timerKey","thenCatch","opt_result","goog.global.clearTimeout","goog.structs.getValues","col","goog.structs.getKeys","goog.structs.Map","opt_map","argLength","goog.structs.Map.prototype.cleanupKeysArray_","srcIndex","destIndex","seen","goog.structs.Map.hasKey_","goog.events.EventTarget.prototype.addEventListener","opt_capture","opt_handlerScope","goog.events.EventTarget.prototype.removeEventListener","goog.events.EventTarget.prototype.dispatchEvent","ancestorsTree","ancestor","getParentEventTarget","actualEventTarget_","oldEvent","opt_ancestorsTree","currentTarget","fireListeners","goog.events.EventTarget.prototype.disposeInternal","goog.events.EventTarget.superClass_.disposeInternal.call","removeAllListeners","Fd","goog.structs.Map.prototype.getValues","cleanupKeysArray_","goog.structs.Map.prototype.getKeys","goog.structs.Map.prototype.clear","goog.structs.Map.prototype","goog.structs.Map.prototype.get","opt_val","goog.structs.Map.prototype.set","goog.structs.Map.prototype.forEach","goog.uri.utils.splitRe_","goog.Uri","opt_uri","opt_ignoreCase","setScheme","setUserInfo","setDomain","setPort","setPath","setQueryData","setFragment","SCHEME","goog.Uri.decodeOrEmpty_","USER_INFO","DOMAIN","PORT","PATH","QUERY_DATA","FRAGMENT","goog.Uri.QueryData","goog.Uri.prototype.setScheme","newScheme","opt_decode","goog.Uri.prototype.setPort","newPort","goog.Uri.prototype.setQueryData","queryData","goog.Uri.QueryData.prototype.setIgnoreCase","ignoreCase","ensureKeyMapInitialized_","invalidateCache_","lowerCase","remove","setValues","setIgnoreCase","goog.Uri.encodeSpecialChars_","goog.Uri.reDisallowedInQuery_","goog.Uri.prototype.setParameterValue","goog.Uri.prototype.getParameterValue","paramName","goog.Uri.parse","uri","goog.Uri.create","opt_domain","opt_path","fireauth.iframeclient.SCHEME","opt_preserveReserved","decodeURI","unescapedPart","extra","opt_removeDoubleEncoding","encoded","encodeURI","goog.Uri.encodeChar_","ch","goog.Uri.prototype.toString","scheme","getScheme","goog.Uri.reDisallowedInSchemeOrUserInfo_","getDomain","userInfo","getUserInfo","getPort","getPath","hasDomain","goog.Uri.reDisallowedInAbsolutePath_","goog.Uri.reDisallowedInRelativePath_","query","getEncodedQuery","fragment","getFragment","goog.Uri.reDisallowedInFragment_","goog.Uri.prototype.resolve","relativeUri","absoluteUri","overridden","hasPath","lastSlashIndex","leadingSlash","segments","segment","opt_query","goog.Uri.QueryData.prototype.ensureKeyMapInitialized_","encodedQuery","pairs","indexOfEquals","goog.uri.utils.parseQueryData","goog.Uri.QueryData.createFromMap","goog.Uri.QueryData.prototype.remove","getKeyName_","keyMap_","goog.Uri.QueryData.prototype.containsKey","goog.Uri.QueryData.prototype.setValues","goog.Uri.QueryData.prototype.clone","goog.Uri.QueryData.prototype.getKeyName_","keyName","sb","goog.json.Serializer.prototype.serializeInternal","serializeInternal","serializeArray","serializeString_","serializeObject_","serialize","goog.json.Serializer","Qd","goog.Uri.QueryData.prototype.add","goog.Uri.QueryData.prototype","goog.Uri.QueryData.prototype.clear","goog.Uri.QueryData.prototype.forEach","opt_scope","goog.Uri.QueryData.prototype.getKeys","vals","goog.Uri.QueryData.prototype.getValues","opt_key","containsKey","goog.Uri.QueryData.prototype.set","goog.Uri.QueryData.prototype.get","opt_default","goog.Uri.QueryData.prototype.toString","encodedKey","param","goog.json.Serializer.charToJsonCharCache_","\"","\\","/","\b","\f","\n","\r","\t","\u000b","goog.json.Serializer.charsToReplace_","fireauth.util.isLocalStorageNotSynchronized","ua","fireauth.util.getUserAgentString","fireauth.util.getCurrentUrl","fireauth.util.goTo","opt_window","finalUrl","goog.html.SafeUrl.unwrap","goog.html.SafeUrl.sanitize","fireauth.util.isMobileBrowser","opt_userAgent","uaLower","fireauth.util.closeWindow","fireauth.util.popup","opt_url","opt_width","opt_height","opt_name","top","option","resizable","statusbar","toolbar","fireauth.util.BrowserName.FIREFOX","linkRef","optionString","parentWin","goog.dom.TagName.A","safeLinkRef","goog.html.SAFE_URL_PATTERN_.test","click","newWin","sanitizedLinkRef","newDoc","fireauth.util.IP_ADDRESS_REGEXP_","fireauth.util.EMAIL_ADDRESS_REGEXP_","goog.global.document","LOAD","fireauth.util.isAndroidOrIosCordovaScheme","fireauth.util.getCurrentScheme","fireauth.util.isIframe","fireauth.util.isWorker","fireauth.util.getEnvironment","REACT_NATIVE","NODE","WORKER","BROWSER","fireauth.util.isNativeEnvironment","environment","FIREFOX","CHROME","OPERA","IEMOBILE","IE","EDGE","SILK","BLACKBERRY","WEBOS","ANDROID","matches","re","OTHER","SAFARI","fireauth.util.Framework","FIREBASEUI","clientVersion","opt_frameworkVersion","frameworkVersion","frameworkSet","providedFrameworks","reportedEnvironment","fireauth.util.getBrowserName","fireauth.util.getObjectRef","varStrName","pieces","fireauth.util.isWebStorageSupported","storage","fireauth.util.generateEventId","fireauth.util.isPopupRedirectSupported","fireauth.util.isHttpOrHttps","fireauth.util.runsInBackground","fireauth.util.stringifyJSON","goog.json.serialize","fireauth.util.copyWithoutNullsOrUndefined","trimmedObj","fireauth.util.parseJSON","opt_prefix","fireauth.util.iframeCanSyncWebStorage","fireauth.util.resetUnloadedGapiModules","beacon","hint","fireauth.util.Delay","shortDelay","longDelay","fireauth.util.utcTimestampToDateString","utcTimestamp","date","fireauth.util.isAuthHandlerOrIframe","fireauth.util.Delay.prototype.get","fireauth.util.Delay.OFFLINE_DELAY_MS_","fireauth.object.readonlyConfigurable_","fireauth.deprecation.shownMessages_","ef","fireauth.object.setReadonlyProperty","fireauth.object.setReadonlyProperties","fireauth.object.makeReadonlyCopy","fireauth.object.unsafeCreateReadOnlyCopy","copy","fireauth.MultiFactorInfo","resp","factorId","fireauth.MultiFactorInfo.MfaEnrollmentField.PHONE_INFO","PHONE","fireauth.MultiFactorInfo.MfaEnrollmentField.MFA_ENROLLMENT_ID","fireauth.MultiFactorInfo.MfaEnrollmentField.DISPLAY_NAME","enrollmentTime","fireauth.MultiFactorInfo.MfaEnrollmentField.ENROLLED_AT","toUTCString","multiFactorInfo","fireauth.PhoneMultiFactorInfo","fireauth.MultiFactorInfo.prototype.toPlainObject","displayName","DISPLAY_NAME","ENROLLED_AT","MFA_ENROLLMENT_ID","PHONE_INFO","fireauth.MultiFactorInfo.call","fireauth.ActionCodeInfo","email","fireauth.ActionCodeInfo.ServerFieldName.EMAIL","newEmail","fireauth.ActionCodeInfo.ServerFieldName.NEW_EMAIL","operation","fireauth.ActionCodeInfo.ServerFieldName.REQUEST_TYPE","fireauth.MultiFactorInfo.fromServerResponse","fireauth.ActionCodeInfo.ServerFieldName.MFA_INFO","fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN","fireauth.ActionCodeInfo.Operation.VERIFY_AND_CHANGE_EMAIL","fireauth.ActionCodeInfo.Operation.REVERT_SECOND_FACTOR_ADDITION","mfaInfo","fireauth.ActionCodeInfo.DataField.FROM_EMAIL","fireauth.ActionCodeInfo.DataField.PREVIOUS_EMAIL","fireauth.ActionCodeInfo.DataField.EMAIL","fireauth.ActionCodeInfo.DataField.MULTI_FACTOR_INFO","fireauth.ActionCodeInfo.PropertyName.OPERATION","fireauth.ActionCodeInfo.PropertyName.DATA","fireauth.PhoneMultiFactorInfo.prototype.toPlainObject","fireauth.PhoneMultiFactorInfo.superClass_.toPlainObject.call","REVERT_SECOND_FACTOR_ADDITION","EMAIL_SIGNIN","VERIFY_AND_CHANGE_EMAIL","EMAIL","MFA_INFO","NEW_EMAIL","REQUEST_TYPE","FROM_EMAIL","MULTI_FACTOR_INFO","PREVIOUS_EMAIL","DATA","OPERATION","fireauth.ActionCodeURL","actionLink","apiKey","getParameterValue","fireauth.ActionCodeURL.QueryField.API_KEY","fireauth.ActionCodeURL.QueryField.CODE","fireauth.ActionCodeURL.QueryField.MODE","fireauth.ActionCodeURL.ModeToOperationMap_","continueUrl","fireauth.ActionCodeURL.QueryField.CONTINUE_URL","languageCode","fireauth.ActionCodeURL.QueryField.LANGUAGE_CODE","tenantId","fireauth.ActionCodeURL.QueryField.TENANT_ID","API_KEY","CODE","CONTINUE_URL","LANGUAGE_CODE","MODE","TENANT_ID","recoverEmail","RECOVER_EMAIL","resetPassword","PASSWORD_RESET","revertSecondFactorAddition","signIn","verifyAndChangeEmail","verifyEmail","VERIFY_EMAIL","fireauth.ActionCodeSettings","settingsObj","fireauth.ActionCodeSettings.RawField.URL","initialize_","androidSettings","fireauth.ActionCodeSettings.RawField.ANDROID","apn","fireauth.ActionCodeSettings.AndroidRawField.PACKAGE_NAME","installApp","fireauth.ActionCodeSettings.AndroidRawField.INSTALL_APP","fireauth.ActionCodeSettings.AndroidRawField.MINIMUM_VERSION","amv","iosSettings","fireauth.ActionCodeSettings.RawField.IOS","ibi","fireauth.ActionCodeSettings.IosRawField.BUNDLE_ID","canHandleCodeInApp","fireauth.ActionCodeSettings.RawField.HANDLE_CODE_IN_APP","fireauth.ActionCodeSettings.RawField.DYNAMIC_LINK_DOMAIN","dynamicLinkDomain","DYNAMIC_LINK_DOMAIN","HANDLE_CODE_IN_APP","IOS","URL","INSTALL_APP","MINIMUM_VERSION","PACKAGE_NAME","BUNDLE_ID","fireauth.ActionCodeSettings.prototype.buildRequest","goog.crypt.base64.charToByteMap_","goog.crypt.base64.decodeStringInternal_","pushByte","getByte","default_val","nextCharIndex","goog.crypt.base64.init_","commonChars","specialChars","char","fireauth.IdToken","tokenString","fireauth.IdToken.parseIdTokenClaims","padLen","fields","jsonInfo","goog.crypt.base64.decodeString","fireauth.IdToken.prototype.getTenantId","fireauth.IdToken.prototype.isAnonymous","fireauth.IdToken.prototype.toString","fireauth.idp.RESERVED_OAUTH1_PARAMS","fireauth.idp.RESERVED_OAUTH2_PARAMS","fireauth.idp.Settings","FACEBOOK","languageParam","popupWidth","popupHeight","providerId","reservedOAuthParameters","GITHUB","GOOGLE","TWITTER","APPLE","fireauth.AdditionalUserInfo.fromPlainObject","factory","fireauth.FacebookAdditionalUserInfo","fireauth.GoogleAdditionalUserInfo","fireauth.GithubAdditionalUserInfo","fireauth.TwitterAdditionalUserInfo","fireauth.AdditionalUserInfo.VerifyAssertionField.PROVIDER_ID","fireauth.FederatedAdditionalUserInfo","fireauth.AdditionalUserInfo.VerifyAssertionField.ID_TOKEN","fireauth.GenericAdditionalUserInfo","ID_TOKEN","PROVIDER_ID","idToken","fireauth.IdToken.parse","ANONYMOUS","CUSTOM","isNewUser","fireauth.GenericAdditionalUserInfo.call","fireauth.FederatedAdditionalUserInfo.call","fireauth.DynamicLink.parseDeepLink","link","doubleDeepLink","iOSdeepLink","fireauth.MultiFactorSession","mfaPendingCredential","fireauth.MultiFactorSession.Type.ENROLL","fireauth.MultiFactorSession.Type.SIGN_IN","ENROLL","SIGN_IN","fireauth.AuthCredential","idTokenResolver","fireauth.RpcHandler.AuthServerField.ID_TOKEN","parsedIdToken","fireauth.SAMLAuthCredential","pendingToken","fireauth.SAMLAuthCredential.prototype.makeVerifyAssertionRequest_","requestUri","fireauth.constants.SAML_PREFIX","fireauth.OAuthCredential","oauthResponse","signInMethod","fireauth.OAuthCredential.prototype.makeVerifyAssertionRequest_","postBody","accessToken","oauthTokenSecret","oauthToken","fireauth.FederatedProvider","opt_reservedParams","isOAuthProvider","fireauth.idp.getIdpSettings","fireauth.FederatedProvider.call","fireauth.OAuthProvider.call","accessTokenOrObject","credential","fireauth.FacebookAuthProvider","fireauth.GithubAuthProvider","fireauth.GoogleAuthProvider","idTokenOrObject","fireauth.TwitterAuthProvider","tokenOrObject","secret","tokenObject","fireauth.EmailAuthCredential","password","opt_signInMethod","PASSWORD","fireauth.EmailAuthProvider","fireauth.EmailAuthProvider.credentialWithLink","emailLink","actionCodeUrl","fireauth.EmailAuthProvider.getActionCodeUrlFromSignInEmailLink","fireauth.ActionCodeURL.parseLink","params","allowedKeys","fireauth.PhoneAuthCredential","fireauth.PhoneAuthCredential.prototype.makeVerifyPhoneNumberRequest_","temporaryProof","phoneNumber","sessionInfo","fireauth.PhoneAuthProvider","opt_auth","verificationId","verificationCode","accessTokenSecret","rawNonce","fireauth.OAuthProvider","fireauth.AuthProvider.checkIfOAuthSupported","fireauth.AuthEvent","opt_eventId","opt_urlResponse","opt_sessionId","opt_error","opt_postBody","opt_tenantId","rawResponse","fireauth.AuthError.fromPlainObject","fireauth.UniversalLinkSubscriber","fireauth.MultiFactorSession.prototype.getRawSession","fireauth.MultiFactorSession.prototype.toPlainObject","multiFactorSession","pendingCredential","fireauth.AuthCredential.prototype.getIdTokenProvider","fireauth.AuthCredential.prototype.linkToIdToken","fireauth.AuthCredential.prototype.matchIdTokenWithUid","fireauth.AuthCredential.prototype.toPlainObject","fireauth.SAMLAuthCredential.prototype.getIdTokenProvider","rpcHandler","makeVerifyAssertionRequest_","fireauth.SAMLAuthCredential.prototype.linkToIdToken","fireauth.SAMLAuthCredential.prototype.matchIdTokenWithUid","verifyAssertionForExisting","fireauth.SAMLAuthCredential.prototype.toPlainObject","fireauth.OAuthCredential.prototype.getIdTokenProvider","fireauth.OAuthCredential.prototype.linkToIdToken","fireauth.OAuthCredential.prototype.matchIdTokenWithUid","fireauth.OAuthCredential.prototype.toPlainObject","fireauth.FederatedProvider.prototype.setCustomParameters","customParameters","fireauth.SAMLAuthProvider","fireauth.OAuthProvider.prototype.addScope","fireauth.OAuthProvider.prototype.getScopes","fireauth.OAuthProvider.prototype.credential","optionsOrIdToken","opt_accessToken","fireauth.EmailAuthCredential.prototype.getIdTokenProvider","invokeRpc","fireauth.RpcHandler.ApiMethod.EMAIL_LINK_SIGNIN","oobCode","fireauth.RpcHandler.ApiMethod.VERIFY_PASSWORD","fireauth.EmailAuthCredential.prototype.linkToIdToken","fireauth.RpcHandler.ApiMethod.EMAIL_LINK_SIGNIN_FOR_LINKING","fireauth.RpcHandler.ApiMethod.SET_ACCOUNT_INFO_SENSITIVE","fireauth.EmailAuthCredential.prototype.matchIdTokenWithUid","fireauth.EmailAuthCredential.prototype.toPlainObject","EMAIL_LINK_SIGN_IN_METHOD","EMAIL_LINK","EMAIL_PASSWORD_SIGN_IN_METHOD","EMAIL_PASSWORD","fireauth.PhoneAuthCredential.prototype.getIdTokenProvider","makeVerifyPhoneNumberRequest_","fireauth.PhoneAuthCredential.prototype.linkToIdToken","fireauth.RpcHandler.ApiMethod.VERIFY_PHONE_NUMBER_FOR_LINKING","fireauth.PhoneAuthCredential.prototype.matchIdTokenWithUid","fireauth.RpcHandler.ApiMethod.VERIFY_PHONE_NUMBER_FOR_EXISTING","fireauth.PhoneAuthCredential.prototype.toPlainObject","fireauth.PhoneAuthProvider.prototype.verifyPhoneNumber","phoneInfoOptions","applicationVerifier","session","rawSession","fireauth.RpcHandler.prototype.startPhoneMfaEnrollment","fireauth.RpcHandler.ApiMethod.START_PHONE_MFA_ENROLLMENT","phoneEnrollmentInfo","recaptchaToken","fireauth.RpcHandler.prototype.startPhoneMfaSignIn","fireauth.RpcHandler.ApiMethod.START_PHONE_MFA_SIGN_IN","mfaEnrollmentId","phoneSignInInfo","fireauth.RpcHandler.prototype.sendVerificationCode","fireauth.RpcHandler.ApiMethod.SEND_VERIFICATION_CODE","sendVerificationCode","PHONE_SIGN_IN_METHOD","fireauth.AuthEvent.prototype.getUid","fireauth.AuthEvent.prototype.getTenantId","fireauth.AuthEvent.prototype.toPlainObject","eventId","urlResponse","sessionId","yh","fireauth.UniversalLinkSubscriber.instance_","fireauth.InvalidOriginError","fireauth.InvalidOriginError.CHROME_EXTENSION_MESSAGE_TEMPLATE_","fireauth.InvalidOriginError.HTTP_MESSAGE_TEMPLATE_","fireauth.AuthErrorWithCredential","opt_credentialInfo","fireauth.AuthError.call","credentialInfo","fireauth.AuthProvider.getCredentialFromResponse","goog.net.XmlHttpFactory","goog.net.XmlHttpFactory.prototype.getOptions","goog.net.DefaultXmlHttpFactory.prototype.getProgId_","ACTIVE_X_IDENTS","candidate","goog.net.CorsXmlHttpFactory","XDomainRequest","UNINITIALIZED","goog.net.IeCorsXhrAdapter.prototype.setReadyState_","readyState","goog.debug.LogRecord","msg","loggerName","opt_time","opt_sequenceNumber","goog.debug.Logger","goog.debug.Logger.Level","fireauth.AuthErrorWithCredential.prototype.toPlainObject","goog.object.extend","fireauth.AuthErrorWithCredential.prototype.toJSON","goog.net.DefaultXmlHttpFactory","goog.net.DefaultXmlHttpFactory.prototype.createInstance","progId","getProgId_","goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions","USE_NULL_FUNCTION","LOCAL_REQUEST_ERROR","goog.net.XmlHttp.factory_","goog.net.CorsXmlHttpFactory.prototype.createInstance","goog.net.IeCorsXhrAdapter","goog.net.CorsXmlHttpFactory.prototype.internalGetOptions","Ch","goog.net.IeCorsXhrAdapter.prototype.open","opt_async","goog.net.IeCorsXhrAdapter.prototype.send","goog.net.IeCorsXhrAdapter.prototype.abort","goog.net.IeCorsXhrAdapter.prototype.setRequestHeader","goog.net.IeCorsXhrAdapter.prototype.getResponseHeader","goog.net.IeCorsXhrAdapter.prototype.handleLoad_","OK","setReadyState_","COMPLETE","goog.net.IeCorsXhrAdapter.prototype.handleError_","INTERNAL_SERVER_ERROR","goog.net.IeCorsXhrAdapter.prototype.handleTimeout_","goog.net.IeCorsXhrAdapter.prototype.handleProgress_","LOADING","goog.net.IeCorsXhrAdapter.prototype","goog.net.IeCorsXhrAdapter.prototype.getAllResponseHeaders","goog.debug.LogRecord.prototype.reset","goog.debug.Logger.Level.prototype.toString","goog.debug.Logger.Level.SEVERE","goog.debug.Logger.Level.WARNING","goog.debug.Logger.Level.CONFIG","goog.debug.Logger.Level.FINE","goog.debug.Logger.prototype.log","opt_exception","goog.debug.Logger.prototype.getEffectiveLevel","getEffectiveLevel","isLoggable","logRecord","Eh","doLogRecord_","retValue","goog.debug.LogManager.loggers_","goog.debug.LogManager.rootLogger_","goog.debug.Logger.ROOT_LOGGER_NAME","ret","lastDotIndex","leafName","goog.debug.LogManager.getLogger","parentLogger","goog.log.fine","goog.net.FetchXmlHttpFactory","worker","goog.events.EventTarget.call","goog.net.FetchXmlHttp.RequestState.UNSENT","goog.net.FetchXmlHttpFactory.prototype.createInstance","goog.net.FetchXmlHttp","UNSENT","goog.net.FetchXmlHttp.prototype.readInputFromFetch_","goog.net.FetchXmlHttp.prototype.requestDone_","setStatus","DONE","dispatchCallback_","goog.net.FetchXmlHttp.prototype.dispatchCallback_","goog.net.XhrIo","opt_xmlHttpFactory","goog.net.XhrIo.ResponseType.DEFAULT","Sh","goog.net.FetchXmlHttp.prototype.open","OPENED","goog.net.FetchXmlHttp.prototype.send","opt_data","requestInit","goog.net.FetchXmlHttp.prototype.abort","requestDone_","goog.net.FetchXmlHttp.prototype.handleResponse_","HEADER_RECEIVED","TextDecoder","readInputFromFetch_","goog.net.FetchXmlHttp.prototype","goog.net.FetchXmlHttp.prototype.handleDataFromStream_","newText","stream","goog.net.FetchXmlHttp.prototype.handleResponseText_","goog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_","responseArrayBuffer","goog.net.FetchXmlHttp.prototype.handleSendFailure_","logger_","goog.net.FetchXmlHttp.prototype.setRequestHeader","goog.net.FetchXmlHttp.prototype.getResponseHeader","goog.net.FetchXmlHttp.prototype.getAllResponseHeaders","lines","iter","pair","goog.net.XhrIo.HTTP_SCHEME_PATTERN","goog.net.XhrIo.METHODS_WITH_FORM_DATA","goog.net.XhrIo.prototype.send","opt_method","opt_headers","createXhr","goog.net.XmlHttp.factory_.createInstance","getOptions","goog.net.XmlHttp.factory_.getOptions","formatMsg_","error_","goog.structs.forEach","goog.net.XhrIo.isContentTypeHeader_","goog.array.find","contentTypeKey","contentIsFormData","goog.net.XhrIo.CONTENT_TYPE_HEADER","goog.net.XhrIo.FORM_CONTENT_TYPE","cleanUpTimeoutTimer_","goog.net.XhrIo.shouldUseXhr2Timeout_","goog.net.XhrIo.prototype.error_","dispatchErrors_","cleanUpXhr_","goog.net.XhrIo.prototype.dispatchErrors_","goog.net.XhrIo.prototype.onReadyStateChangeHelper_","getReadyState","getStatus","READY_STATE_CHANGE","isComplete","isSuccess","CREATED","ACCEPTED","NO_CONTENT","PARTIAL_CONTENT","NOT_MODIFIED","QUIRK_IE_NO_CONTENT","goog.global.self","goog.global.self.location","goog.global.self.location.protocol","goog.net.XhrIo.HTTP_SCHEME_PATTERN.test","SUCCESS","LOADED","getStatusText","goog.net.XhrIo.prototype.cleanUpXhr_","opt_fromDispose","clearedOnReadyStateChange","READY","goog.net.XhrIo.prototype.cleanUpTimeoutTimer_","goog.net.XhrIo.prototype.getReadyState","goog.net.XhrIo.prototype.getStatus","goog.net.XhrIo.prototype.formatMsg_","goog.async.Deferred","opt_defaultScope","opt_onCancelFunction","goog.net.jsloader.cancel_","goog.async.Deferred.prototype.updateResult_","fire_","goog.async.Deferred.prototype.check_","hasFired","goog.async.Deferred.AlreadyCalledError","goog.async.Deferred.prototype.addCallbacks","eb","goog.async.Deferred.prototype.hasErrback_","sequenceRow","goog.async.Deferred.prototype.fire_","hasErrback_","unhandledErrorId_","goog.async.Deferred.errorMap_","isNewlyBlocked","unhandledException","sequenceEntry","errback","onCallback","onErrback","addCallbacks","deferredError","goog.async.Deferred.Error_","Xh","goog.net.XhrIo.prototype.timeout_","goog.net.XhrIo.prototype","goog.net.XhrIo.prototype.abort","ABORT","goog.net.XhrIo.prototype.disposeInternal","goog.net.XhrIo.prototype.onReadyStateChange_","isDisposed","onReadyStateChangeHelper_","goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.getResponse","TEXT","ARRAY_BUFFER","goog.async.Deferred.prototype.cancel","opt_deepCancel","goog.async.Deferred.CanceledError","check_","updateResult_","goog.async.Deferred.prototype.continue_","goog.async.Deferred.prototype.then","rej","goog.async.Deferred.Error_.prototype.throwError","goog.net.jsloader.safeLoad","trustedUri","timeout","script","goog.dom.TagName.SCRIPT","script_","timeout_","goog.net.jsloader.cleanup_","goog.net.jsloader.Error","goog.net.jsloader.ErrorCode.TIMEOUT","goog.net.jsloader.DEFAULT_TIMEOUT","script.onreadystatechange","script.onerror","goog.net.jsloader.ErrorCode.LOAD_ERROR","charset","goog.dom.safe.setScriptSrc","ja","goog.NONCE_PATTERN_.test","goog.net.jsloader.getScriptParentElement_","headElements","scriptNode","removeScriptNode","opt_timeout","LOAD_ERROR","fireauth.XmlHttpFactory","xmlHttpRequest","opt_config","opt_firebaseClientVersion","fireauth.RpcHandler.SECURE_TOKEN_ENDPOINT_","fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_TIMEOUT_","fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_HEADERS_","fireauth.RpcHandler.FIREBASE_ENDPOINT_","fireauth.RpcHandler.IDENTITY_PLATFORM_ENDPOINT_","fireauth.RpcHandler.DEFAULT_FIREBASE_TIMEOUT_","fireauth.RpcHandler.DEFAULT_FIREBASE_HEADERS_","fireauth.XmlHttpFactory.prototype.createInstance","fireauth.XmlHttpFactory.prototype.internalGetOptions","Ji","Content-Type","fireauth.RpcHandler.prototype.updateCustomLocaleHeader","fireauth.RpcHandler.FIREBASE_LOCALE_KEY_","fireauth.RpcHandler.prototype.updateClientVersion","fireauth.RpcHandler.prototype.sendXhr_","opt_callback","opt_httpMethod","sendXhr","fireauth.util.supportsCors","fireauth.util.BrowserName.CHROME","chromeVersion","fireauth.RpcHandler.loadGApi_","fireauth.RpcHandler.GAPI_CALLBACK_NAME_","goog.async.Deferred.prototype.addErrback","fireauth.RpcHandler.GAPI_SRC_","fireauth.RpcHandler.loadGApiJs_","fireauth.RpcHandler","fireauth.RpcHandler.prototype.getTenantId","fireauth.RpcHandler.prototype.sendXhrUsingXhrIo_","xhrIo","requestTimeout","clearTimeout","goog.net.XhrIo.prototype.getResponseText","getResponseText","dispose","fireauth.RpcHandler.prototype.requestAuthEndpoint_","httpMethod","opt_customErrorMap","opt_cachebuster","getApiKey","setParameterValue","isGet","GET","sendXhr_","fireauth.RpcHandler.getDeveloperError_","fireauth.RpcHandler.validateRequestHasEmail_","fireauth.util.EMAIL_ADDRESS_REGEXP_.test","fireauth.RpcHandler.validateEmailIfPresent_","fireauth.RpcHandler.validateIdTokenResponse_","fireauth.RpcHandler.validateVerifyPhoneNumberRequest_","fireauth.RpcHandler.prototype.sendXhrUsingGApiClient_","oauth2Token","authType","fireauth.RpcHandler.prototype.signInAnonymously","fireauth.RpcHandler.ApiMethod.SIGN_IN_ANONYMOUSLY","fireauth.RpcHandler.prototype.updateEmail","fireauth.RpcHandler.ApiMethod.SET_ACCOUNT_INFO","fireauth.RpcHandler.prototype.updatePassword","newPassword","fireauth.RpcHandler.PROFILE_FIELD_TO_ENUM_NAME_","photoUrl","fireauth.RpcHandler.validateFinalizePhoneMfaRequest_","fireauth.RpcHandler.validateVerifyAssertionRequest_","fireauth.RpcHandler.processVerifyAssertionResponse_","fireauth.constants.OIDC_PREFIX","NONCE","fireauth.RpcHandler.validateVerifyAssertionResponse_","fireauth.AuthErrorWithCredential.fromPlainObject","FEDERATED_USER_ID_ALREADY_LINKED","fireauth.RpcHandler.getDeveloperErrorFromCode_","fireauth.RpcHandler.prototype.verifyAssertion","fireauth.RpcHandler.ApiMethod.VERIFY_ASSERTION","fireauth.RpcHandler.prototype.verifyAssertionForLinking","fireauth.RpcHandler.ApiMethod.VERIFY_ASSERTION_FOR_LINKING","fireauth.RpcHandler.prototype.verifyAssertionForExisting","fireauth.RpcHandler.ApiMethod.VERIFY_ASSERTION_FOR_EXISTING","fireauth.RpcHandler.validateApplyActionCodeRequest_","Ei","fireauth.RpcHandler.prototype.updateProfile","profileData","fieldsToDelete","enumName","fieldName","fieldValue","fireauth.RpcHandler.prototype.sendPasswordResetEmail","additionalRequestData","requestType","fireauth.RpcHandler.ApiMethod.GET_OOB_CODE","fireauth.RpcHandler.prototype.sendSignInLinkToEmail","fireauth.RpcHandler.ApiMethod.GET_EMAIL_SIGNIN_CODE","fireauth.RpcHandler.prototype.sendEmailVerification","fireauth.RpcHandler.ApiMethod.GET_EMAIL_VERIFICATION_CODE","fireauth.RpcHandler.prototype.verifyBeforeUpdateEmail","fireauth.RpcHandler.ApiMethod.GET_EMAIL_VERIFICATION_CODE_BEFORE_UPDATE","fireauth.RpcHandler.prototype","fireauth.RpcHandler.prototype.verifyPhoneNumber","fireauth.RpcHandler.ApiMethod.VERIFY_PHONE_NUMBER","fireauth.RpcHandler.prototype.confirmPasswordReset","fireauth.RpcHandler.ApiMethod.RESET_PASSWORD","fireauth.RpcHandler.prototype.checkActionCode","fireauth.RpcHandler.ApiMethod.CHECK_ACTION_CODE","fireauth.RpcHandler.prototype.applyActionCode","fireauth.RpcHandler.ApiMethod.APPLY_OOB_CODE","APPLY_OOB_CODE","requestValidator","responseField","requireTenantId","CHECK_ACTION_CODE","responseValidator","fireauth.RpcHandler.validateCheckActionCodeResponse_","CREATE_ACCOUNT","fireauth.RpcHandler.validateCreateAccountRequest_","returnSecureToken","CREATE_AUTH_URI","DELETE_ACCOUNT","requestRequiredFields","DELETE_LINKED_ACCOUNTS","fireauth.RpcHandler.validateDeleteLinkedAccountsRequest_","EMAIL_LINK_SIGNIN","EMAIL_LINK_SIGNIN_FOR_LINKING","FINALIZE_PHONE_MFA_ENROLLMENT","useIdentityPlatformEndpoint","FINALIZE_PHONE_MFA_SIGN_IN","GET_ACCOUNT_INFO","GET_EMAIL_SIGNIN_CODE","fireauth.RpcHandler.validateEmailSignInCodeRequest_","GET_EMAIL_VERIFICATION_CODE","fireauth.RpcHandler.validateEmailVerificationCodeRequest_","GET_EMAIL_VERIFICATION_CODE_BEFORE_UPDATE","fireauth.RpcHandler.validateEmailVerificationCodeBeforeUpdateRequest_","GET_OOB_CODE","fireauth.RpcHandler.validateOobCodeRequest_","GET_PROJECT_CONFIG","cachebuster","GET_RECAPTCHA_PARAM","fireauth.RpcHandler.validateGetRecaptchaParamResponse_","RESET_PASSWORD","SEND_VERIFICATION_CODE","SESSION_INFO","SET_ACCOUNT_INFO","SET_ACCOUNT_INFO_SENSITIVE","fireauth.RpcHandler.validateSetAccountInfoSensitive_","SIGN_IN_ANONYMOUSLY","START_PHONE_MFA_ENROLLMENT","fireauth.RpcHandler.validateStartPhoneMfaEnrollmentRequest_","fireauth.RpcHandler.validateStartPhoneMfaEnrollmentResponse_","START_PHONE_MFA_SIGN_IN","fireauth.RpcHandler.validateStartPhoneMfaSignInRequest_","fireauth.RpcHandler.validateStartPhoneMfaSignInResponse_","VERIFY_ASSERTION","responsePreprocessor","VERIFY_ASSERTION_FOR_EXISTING","fireauth.RpcHandler.validateVerifyAssertionForExistingResponse_","USER_NOT_FOUND","VERIFY_ASSERTION_FOR_LINKING","fireauth.RpcHandler.validateVerifyAssertionLinkRequest_","VERIFY_CUSTOM_TOKEN","fireauth.RpcHandler.validateVerifyCustomTokenRequest_","VERIFY_PASSWORD","fireauth.RpcHandler.validateVerifyPasswordRequest_","VERIFY_PHONE_NUMBER","VERIFY_PHONE_NUMBER_FOR_LINKING","fireauth.RpcHandler.validateVerifyPhoneNumberLinkRequest_","fireauth.RpcHandler.validateVerifyPhoneNumberForLinkingResponse_","VERIFY_PHONE_NUMBER_FOR_EXISTING","customErrorMap","fireauth.RpcHandler.verifyPhoneNumberForExistingErrorMap_","WITHDRAW_MFA","fireauth.RpcHandler.validateWithdrawMfaResponse_","fireauth.RpcHandler.prototype.invokeRpc","fireauth.object.hasNonEmptyFields","opt_fields","field","POST","requestAuthEndpoint_","tempResponse","serverErrorCode","errorReasonMap","keyInvalid","ipRefererBlocked","prefixCode","MISSING_CUSTOM_TOKEN","INVALID_IDENTIFIER","MISSING_PASSWORD","PASSWORD_LOGIN_DISABLED","INVALID_PENDING_TOKEN","EMAIL_NOT_FOUND","RESET_PASSWORD_EXCEED_LIMIT","MISSING_OOB_CODE","INVALID_ID_TOKEN","INVALID_TEMPORARY_PROOF","SESSION_EXPIRED","errorMap","errorMessage","fireauth.iframeclient.IframeWrapper","fireauth.iframeclient.IframeWrapper.prototype.open_","fireauth.iframeclient.IframeWrapper.cachedGApiLoader_","onGapiLoad","fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_.get","cbName","fireauth.iframeclient.IframeWrapper.GAPI_LOADER_SRC_","where","messageHandlersFilter","dontclear","onOpen","clearTimerAndResolve","networkErrorTimer","setHideOnLeave","fireauth.iframeclient.IframeWrapper.PING_TIMEOUT_.get","open_","fireauth.iframeclient.IframeWrapper.NETWORK_TIMEOUT_","fireauth.iframeclient.IframeWrapper.PING_TIMEOUT_","fireauth.iframeclient.IframeUrlBuilder","authDomain","fireauth.iframeclient.IfcHandler","opt_clientVersion","opt_endpointId","fireauth.iframeclient.IfcHandler.getOriginValidator_","fireauth.RpcHandler.prototype.getAuthorizedDomains","fireauth.RpcHandler.ApiMethod.GET_PROJECT_CONFIG","authorizedDomains","domainPattern","fireauth.util.IP_ADDRESS_REGEXP_.test","escapedDomainPattern","RegExp","fireauth.iframeclient.IfcHandler.prototype.initialize","fireauth.util.onDomReady","clientVersion_","endpointId_","fireauth.iframeclient.OAuthUrlBuilder.getAuthFrameworksForApp_","builder","opt_frameworks","setEndpointId","fireauth.iframeclient.IfcHandler.prototype.registerEvents_","fireauth.iframeclient.IframeWrapper.prototype.registerEvent","AUTH_EVENT","registerEvent","resolveResponse","isHandled","fireauth.AuthEvent.fromPlainObject","authEvent","ACK","fireauth.iframeclient.IfcHandler.prototype.getRpcHandler_","fireauth.util.getClientVersion","opt_redirectUrl","opt_additionalParams","fireauth.iframeclient.OAuthUrlBuilder","fireauth.storage.AsyncStorage","opt_asyncStorage","ASYNC_STORAGE","fireauth.messagechannel.Receiver","eventTarget","fireauth.iframeclient.IframeUrlBuilder.prototype.toString","fireauth.iframeclient.OAuthUrlBuilder.prototype.setTenantId","fireauth.iframeclient.OAuthUrlBuilder.prototype.toString","provider_","getAuthLanguage_","reservedParams_","scopes","getAuthFrameworks_","frameworks","Sj","fireauth.iframeclient.IfcHandler.prototype.startPopupTimeout","popupWin","onError","timeoutDuration","popupClosedByUserError","webStorageNotSupportedError","isResolved","fireauth.iframeclient.IfcHandler.prototype.isWebStorageSupported","WEB_STORAGE_SUPPORT_EVENT","initialize","fireauth.iframeclient.IframeWrapper.prototype.sendMessage","isWebStorageSupported","isSupported","fireauth.util.onPopupClose","fireauth.util.POPUP_WAIT_CYCLE_MS_","fireauth.iframeclient.IfcHandler.prototype.shouldBeInitializedEarly","fireauth.iframeclient.IfcHandler.prototype.hasVolatileStorage","fireauth.iframeclient.IfcHandler.prototype.processPopup","onInitialize","opt_alreadyRedirected","getRpcHandler_","onReady","fireauth.iframeclient.IfcHandler.getOAuthHelperWidgetUrl","fireauth.iframeclient.IfcHandler.prototype","fireauth.iframeclient.IfcHandler.prototype.processRedirect","fireauth.iframeclient.IfcHandler.prototype.initializeAndWait","fireauth.iframeclient.IfcHandler.prototype.unloadsOnRedirect","fireauth.iframeclient.IfcHandler.prototype.addAuthEventListener","fireauth.iframeclient.IfcHandler.prototype.removeAuthEventListener","ele","Zj","fireauth.storage.AsyncStorage.prototype.get","fireauth.storage.AsyncStorage.prototype.set","fireauth.storage.AsyncStorage.prototype.remove","fireauth.storage.AsyncStorage.prototype.addStorageListener","fireauth.storage.AsyncStorage.prototype.removeStorageListener","lk","fireauth.messagechannel.Receiver.receivers_","fireauth.messagechannel.Receiver.prototype.subscribe","eventType","fireauth.messagechannel.WorkerClientPostMessager","fireauth.messagechannel.Sender","postMessager","fireauth.messagechannel.Sender.prototype.send","opt_useLongTimeout","onMessage","ackTimer","completionTimer","CONNECTION_UNAVAILABLE","ackTimeout","LONG_ACK","messageChannel","digits","UNSUPPORTED_EVENT","COMPLETION","UNKNOWN","INVALID_RESPONSE","removeMessageHandler_","fireauth.messagechannel.Sender.prototype.removeMessageHandler_","messageHandler","fireauth.storage.IndexedDB","fireauth.storage.IndexedDB.isAvailable","goog.global.indexedDB","INDEXEDDB","receiver","fireauth.messagechannel.Receiver.getInstance","keyProcessed","fireauth.util.getActiveServiceWorker","registration","sw","fireauth.storage.IndexedDB.prototype.initializeDb_","fireauth.storage.IndexedDB.DB_NAME_","fireauth.storage.IndexedDB.VERSION_","request.onerror","request.onupgradeneeded","db","fireauth.storage.IndexedDB.DATA_OBJECT_STORE_NAME_","keyPath","fireauth.storage.IndexedDB.DATA_KEY_PATH_","request.onsuccess","fireauth.storage.IndexedDB.prototype.deleteDb_","deleteDb_","newDb","fireauth.storage.IndexedDB.prototype.initializeDbAndRun_","initializeDb_","fireauth.storage.IndexedDB.prototype.getDataObjectStore_","tx","fireauth.storage.IndexedDB.prototype.getTransaction_","isReadWrite","fireauth.storage.IndexedDB.prototype.onIDBRequest_","fireauth.storage.IndexedDB.prototype.notifySW_","fireauth.util.getServiceWorkerController","fireauth.storage.IndexedDB.prototype.sync_","initializeDbAndRun_","objectStore","getDataObjectStore_","getTransaction_","onIDBRequest_","cursor","centralCopy","diffKeys","fireauth.util.getKeyDiff","diff","fireauth.storage.IndexedDB.prototype.stopListeners_","fireauth.storage.IndexedDB.STOP_ERROR_","fireauth.storage.HybridIndexedDB","fallbackStorage","randomId","randomKey","fireauth.storage.HybridIndexedDB.KEY_","fireauth.storage.IndexedDB.managerInstance_","fireauth.storage.InMemoryStorage","IN_MEMORY","fireauth.storage.LocalStorage","fireauth.storage.LocalStorage.isAvailable","fireauth.storage.LocalStorage.getGlobalStorage","fireauth.storage.LocalStorage.STORAGE_AVAILABLE_KEY_","LOCAL_STORAGE","fireauth.storage.NullStorage","NULL_STORAGE","fireauth.storage.SessionStorage","fireauth.storage.SessionStorage.isAvailable","fireauth.storage.SessionStorage.getGlobalStorage","fireauth.storage.SessionStorage.STORAGE_AVAILABLE_KEY_","SESSION_STORAGE","fireauth.storage.Factory","envMap","fireauth.storage.Factory.EnvConfig.BROWSER","fireauth.storage.Factory.EnvConfig.NODE","fireauth.storage.Factory.EnvConfig.REACT_NATIVE","fireauth.storage.Factory.EnvConfig.WORKER","fireauth.messagechannel.Receiver.prototype.handleEvent_","handlers","allResponses","fireauth.messagechannel.WorkerClientPostMessager.prototype.postMessage","transfer","fireauth.messagechannel.Sender.prototype.close","ik","fireauth.storage.IndexedDB.prototype.set","dbTemp","isLocked","fireauth.storage.IndexedDB.prototype","fireauth.storage.IndexedDB.prototype.get","fireauth.storage.IndexedDB.prototype.remove","fireauth.storage.IndexedDB.prototype.addStorageListener","fireauth.storage.IndexedDB.prototype.startListeners_","stopListeners_","sync_","fireauth.storage.IndexedDB.POLLING_DELAY_","startListeners_","fireauth.storage.IndexedDB.prototype.removeStorageListener","vk","fireauth.storage.HybridIndexedDB.prototype.get","fireauth.storage.HybridIndexedDB.prototype.set","fireauth.storage.HybridIndexedDB.prototype.remove","fireauth.storage.HybridIndexedDB.prototype.addStorageListener","fireauth.storage.HybridIndexedDB.prototype.removeStorageListener","wk","fireauth.storage.InMemoryStorage.prototype.get","fireauth.storage.InMemoryStorage.prototype.set","fireauth.storage.InMemoryStorage.prototype.remove","fireauth.storage.InMemoryStorage.prototype.addStorageListener","fireauth.storage.InMemoryStorage.prototype.removeStorageListener","xk","fireauth.storage.LocalStorage.prototype.get","fireauth.storage.LocalStorage.prototype.set","fireauth.storage.LocalStorage.prototype.remove","fireauth.storage.LocalStorage.prototype.addStorageListener","fireauth.storage.LocalStorage.prototype.removeStorageListener","Ak","fireauth.storage.NullStorage.prototype.get","fireauth.storage.NullStorage.prototype.set","fireauth.storage.NullStorage.prototype.remove","fireauth.storage.NullStorage.prototype.addStorageListener","fireauth.storage.NullStorage.prototype.removeStorageListener","Bk","fireauth.storage.SessionStorage.prototype.get","fireauth.storage.SessionStorage.prototype.set","fireauth.storage.SessionStorage.prototype.remove","fireauth.storage.SessionStorage.prototype.addStorageListener","fireauth.storage.SessionStorage.prototype.removeStorageListener","Jk","Nk","persistent","temporary","fireauth.authStorage.Persistence","LOCAL","NONE","SESSION","fireauth.authStorage.Manager","safariLocalStorageNotSynced","runsInBackground","webStorageSupported","fireauth.storage.Factory.instance_","storageFactory","fireauth.authStorage.Manager.instance_","fireauth.authStorage.Manager.prototype.getStorage_","fireauth.authStorage.Manager.prototype.getKeyName_","dataKey","fireauth.authStorage.SEPARATOR_","fireauth.authStorage.Manager.prototype.remove","getStorage_","fireauth.authStorage.Manager.prototype.stopManualListeners_","clearInterval","fireauth.storage.AuthEventManager","appId","fireauth.authStorage.Manager.getInstance","Mk","fireauth.authStorage.Manager.prototype.get","fireauth.authStorage.Manager.prototype","fireauth.authStorage.Manager.prototype.set","serializedValue","fireauth.authStorage.Manager.prototype.addListener","fireauth.authStorage.Manager.prototype.startManualListeners_","stopManualListeners_","setInterval","currentValue","newValue","poll","fireauth.authStorage.Manager.LOCAL_STORAGE_POLLING_TIMER_","startManualListeners_","fireauth.authStorage.Manager.prototype.removeListener","fireauth.authStorage.Manager.prototype.storageChangeEvent_","storedValue","realValue","triggerListeners","fireauth.authStorage.IE10_LOCAL_STORAGE_SYNC_DELAY","fireauth.authStorage.Manager.prototype.callListeners_","bl","fireauth.storage.OAuthHandlerManager","goog.crypt.Sha2","numHashBlocks","initHashBlocks","goog.crypt.Sha2.BLOCKSIZE_","goog.crypt.Sha2.Kx_","goog.crypt.Sha2.K_","goog.crypt.Hash","dl","goog.crypt.Sha2.PADDING_","goog.crypt.Sha2.prototype.computeChunk_","chunk","w","rounds","w_15","partialSum1","partialSum2","w_2","t2","t1","goog.crypt.Sha2.prototype.update","opt_length","inChunk","computeChunk_","goog.crypt.Sha2.prototype.reset","goog.crypt.Sha256","goog.crypt.Sha2.call","goog.crypt.Sha256.INIT_HASH_BLOCK_","fireauth.CordovaHandler","fireauth.util.STORAGE_KEY_SEPARATOR_","fireauth.CordovaHandler.getError_","fireauth.CordovaHandler.prototype.computeSecureHash_","sha256","goog.crypt.byteArrayToHex","numByte","hexByte","fireauth.CordovaHandler.prototype.dispatchEvent_","fireauth.CordovaHandler.prototype.getInitialAuthEvent_","authEventCallback","fireauth.CordovaHandler.prototype.setAuthEventListener_","universalLinkCb","eventData","initialResolve","noEventTimer","noEvent","errorObject","callbackUrl","dispatchEvent_","fireauth.CordovaHandler.INITIAL_TIMEOUT_MS_","existingHandlerOpenURL","fireauth.UniversalLinkSubscriber.prototype.subscribe","this.masterCb_","fireauth.CordovaHandler.prototype.getPartialStoredEvent_","fireauth.storage.AuthEventManager.prototype.getAuthEvent","fireauth.storage.AuthEventManager.Keys.AUTH_EVENT","fireauth.storage.PendingRedirectManager","ll","fireauth.CordovaHandler.prototype.initializeAndWait","timeoutId","fireauth.util.CORDOVA_ONDEVICEREADY_TIMEOUT_MS_","fireauth.CordovaHandler.prototype","fireauth.CordovaHandler.prototype.startPopupTimeout","fireauth.CordovaHandler.prototype.processPopup","fireauth.CordovaHandler.prototype.unloadsOnRedirect","fireauth.CordovaHandler.prototype.shouldBeInitializedEarly","fireauth.CordovaHandler.prototype.hasVolatileStorage","fireauth.CordovaHandler.prototype.processRedirect","onClose","onResume","onVisibilityChange","fireauth.CordovaHandler.prototype.processRedirectInternal_","numOfChars","fireauth.CordovaHandler.SESSION_ID_TOTAL_CHARS_","allowedChars","generateSessionId_","appIdentifier","appDisplayName","additionalParams","computeSecureHash_","hashedSessionId","oauthHelperWidgetUrl","storageKey_","isAvailable","openUrl","closeBrowsertab","fireauth.CordovaHandler.REDIRECT_TIMEOUT_MS_","fireauth.util.isAppVisible","cleanup","fireauth.CordovaHandler.prototype.addAuthEventListener","getInitialAuthEvent_","fireauth.CordovaHandler.prototype.removeAuthEventListener","fireauth.storage.PendingRedirectManager.PENDING_REDIRECT_KEY_","fireauth.storage.PendingRedirectManager.prototype.removePendingStatus","fireauth.AuthEventManager","fireauth.RedirectAuthEventProcessor","fireauth.PopupAuthEventProcessor","fireauth.AuthEventManager.KEY_SEPARATOR_","fireauth.AuthEventManager.instantiateOAuthSignInHandler","fireauth.constants.clientEndpoint","fireauth.AuthEventManager.prototype.initialize","previousOauthSignInHandler","fireauth.AuthEventManager.prototype.initializeWithNoPendingRedirectResult_","notSupportedEvent","defaultToEmptyResponse","fireauth.AuthEventManager.prototype.subscribe","fireauth.storage.PendingRedirectManager.prototype.getPendingStatus","fireauth.storage.PendingRedirectManager.PENDING_FLAG_","getPendingStatus","removePendingStatus","initializeWithNoPendingRedirectResult_","fireauth.AuthEventManager.prototype.unsubscribe","fireauth.AuthEventManager.prototype.reset","fireauth.AuthEventManager.prototype.handleAuthEvent_","fireauth.AuthEventManager.EVENT_DUPLICATION_CACHE_DURATION","hasProcessedAuthEvent_","processed","potentialHandler","eventManager","saveProcessedAuthEvent_","fireauth.AuthEventManager.POPUP_TIMEOUT_MS_","fireauth.AuthEventManager.REDIRECT_TIMEOUT_MS_","fireauth.AuthEventManager.prototype.processPopup","fireauth.AuthEventManager.isCordovaFalsePositive_","fireauth.AuthEventManager.prototype.processRedirect","fireauth.storage.PendingRedirectManager.prototype.setPendingStatus","fireauth.AuthEventManager.prototype.startPopupTimeout","owner","fireauth.AuthEventManager.POPUP_TIMEOUT_MS_.get","fireauth.AuthEventManager.prototype.getRedirectResult","fireauth.AuthEventManager.manager_","fireauth.RedirectAuthEventProcessor.prototype.defaultToEmptyResponse","setRedirectResult_","fireauth.RedirectAuthEventProcessor.prototype.clearRedirectResult","fireauth.RedirectAuthEventProcessor.prototype.setRedirectResolve_","popupRedirectResult","this.redirectedUserPromise_","fireauth.RedirectAuthEventProcessor.prototype.setRedirectResult_","isRedirect","fireauth.RedirectAuthEventProcessor.prototype.setRedirectReject_","setRedirectReject_","setRedirectResolve_","user","fireauth.AuthSettings","setAppVerificationDisabledForTesting","fireauth.ConfirmationResult","credentialResolver","auth","appVerifier","verifyPhoneNumber","fireauth.IdTokenResult","expirationTime","authTime","issuedAtTime","signInProvider","signInSecondFactor","fireauth.MultiFactorResolver","errorResponse","onIdTokenResolver","fireauth.MultiFactorResolver.SignInResponseField.MFA_PENDING_CREDENTIAL","fireauth.MultiFactorResolver.SignInResponseField.MFA_INFO","mfaEnrollment","fireauth.RedirectAuthEventProcessor.prototype.reset","fireauth.RedirectAuthEventProcessor.prototype.processAuthEvent","isWebStorageNotSupported","isOperationNotSupported","processErrorEvent_","fireauth.RedirectAuthEventProcessor.prototype.processSuccessEvent_","popupRedirectResponse","processSuccessEvent_","processUnknownEvent_","fireauth.RedirectAuthEventProcessor.prototype.getRedirectResult","fireauth.RedirectAuthEventProcessor.prototype.startRedirectTimeout_","fireauth.AuthEventManager.REDIRECT_TIMEOUT_MS_.get","startRedirectTimeout_","fireauth.PopupAuthEventProcessor.prototype.processAuthEvent","fireauth.ConfirmationResult.prototype.confirm","fireauth.PhoneAuthProvider.credential","MFA_PENDING_CREDENTIAL","fireauth.MultiFactorError","fireauth.MultiFactorAssertion","fireauth.AuthCredentialMultiFactorAssertion","multiFactorAuthCredential","phoneAuthCredential","fireauth.AuthCredentialMultiFactorAssertion.call","fireauth.UserEvent","fireauth.MultiFactorUser","accountInfo","USER_RELOADED","enrolledFactors","updateEnrolledFactors_","fireauth.MultiFactorUser.prototype.updateEnrolledFactors_","fireauth.ProactiveRefresh","retryPolicy","getWaitDuration","RETRIAL_MIN_WAIT","RETRIAL_MAX_WAIT","fireauth.ProactiveRefresh.prototype.getNextRun_","hasSucceeded","fireauth.StsTokenManager","fireauth.StsTokenManager.prototype.getExpirationTime","fireauth.StsTokenManager.prototype.parseServerResponse","refreshToken","fireauth.StsTokenManager.prototype.requestToken_","fireauth.RpcHandler.prototype.requestStsToken","fireauth.UserMetadata","opt_createdAt","opt_lastLoginAt","lastSignInTime","creationTime","opt_email","opt_displayName","opt_photoURL","opt_phoneNumber","photoURL","fireauth.AuthUser","appOptions","stsTokenResponse","opt_accountInfo","clientFullVersion","setLastAccessToken_","setAccountInfo","fireauth.AuthEventManager.getManager","fireauth.AuthUser.prototype.initializeProactiveRefreshUtility_","waitInterval","getExpirationTime","OFFSET_DURATION","initializeProactiveRefreshUtility_","this.onLanguageCodeChanged_","this.onFrameworkChanged_","setFramework","fireauth.AuthUser.prototype.setLanguageCodeChangeDispatcher","dispatcher","LANGUAGE_CODE_CHANGED","fireauth.AuthUser.prototype.setFramework","framework","fireauth.AuthUser.prototype.setFrameworkChangeDispatcher","FRAMEWORK_CHANGED","fireauth.AuthUser.prototype.getAuth_","fireauth.AuthUser.prototype.startProactiveRefresh","TOKEN_CHANGED","fireauth.AuthUser.prototype.stopProactiveRefresh","fireauth.AuthUser.prototype.setLastAccessToken_","lastAccessToken","fireauth.AuthUser.prototype.notifyStateChangeListeners_","fireauth.AuthUser.prototype.enablePopupRedirect","fireauth.AuthUser.prototype.setAccountInfo","emailVerified","isAnonymous","providerData","fireauth.AuthUser.prototype.checkDestroyed_","fireauth.AuthUser.prototype.getProviderIds","fireauth.AuthUser.prototype.addProviderData","removeProviderData","fireauth.AuthUser.prototype.removeProviderData","fireauth.AuthUser.prototype.updateProperty","propName","fireauth.AuthUser.prototype.copy","userToCopy","fireauth.UserMetadata.prototype.clone","addProviderData","fireauth.StsTokenManager.prototype.copy","tokenManagerToCopy","fireauth.AuthUser.prototype.reloadWithoutSaving_","fireauth.AuthUser.prototype.setUserAccountInfoFromToken_","fireauth.RpcHandler.ApiMethod.GET_ACCOUNT_INFO","updateProperty","fireauth.AuthUser.prototype.updateTokensIfPresent","parseServerResponse","notifyAuthListeners_","fireauth.AuthUser.prototype.checkIfAlreadyLinked_","reloadWithoutSaving_","getProviderIds","fireauth.AuthUser.prototype.getUserCredential_","idTokenResponse","operationType","additionalUserInfo","fireauth.AuthUser.prototype.finalizeLinking_","updateTokensIfPresent","fireauth.AuthUser.prototype.runOperationWithPopup_","additionalCheck","isReauthOperation","settings","generateEventId_","getAuthEventManager","startPopupTimeout","registerPendingPromise_","fireauth.AuthUser.prototype.runOperationWithRedirect_","errorThrown","fireauth.storage.RedirectUserManager.REDIRECT_USER_KEY_","redirectUser","fireauth.AuthUser.prototype.getAuthEventManager","fireauth.AuthUser.prototype.registerPendingPromise_","opt_skipInvalidationCheck","processedP","fireauth.AuthUser.prototype.checkIfInvalidated_","USER_INVALIDATED","checkIfInvalidated_","multiFactorError","fireauth.MultiFactorError.fromPlainObject","getAuth_","stsTokenManagerResponse","firebaseUser","fireauth.storage.RedirectUserManager","fireauth.MultiFactorResolver.prototype.resolveSignIn","newSignInResponse","fireauth.MultiFactorAssertion.prototype.process","fireauth.MultiFactorAssertion.prototype.finalizeMfaEnrollment_","phoneVerificationInfo","fireauth.RpcHandler.ApiMethod.FINALIZE_PHONE_MFA_ENROLLMENT","finalizeMfaEnrollment_","fireauth.MultiFactorAssertion.prototype.finalizeMfaSignIn_","fireauth.RpcHandler.ApiMethod.FINALIZE_PHONE_MFA_SIGN_IN","signInRequest","finalizeMfaSignIn_","fireauth.PhoneMultiFactorAssertion","lm","fireauth.MultiFactorUser.prototype.handleUserReload_","fireauth.MultiFactorUser.extractEnrolledFactors_","fireauth.MultiFactorUser.prototype","fireauth.MultiFactorUser.prototype.getSession","fireauth.MultiFactorUser.prototype.enroll","tokenResponse","fireauth.MultiFactorUser.prototype.unenroll","fireauth.RpcHandler.ApiMethod.WITHDRAW_MFA","fireauth.MultiFactorUser.prototype.toPlainObject","multiFactor","fireauth.ProactiveRefresh.prototype.start","fireauth.ProactiveRefresh.prototype.process_","getNextRun_","fireauth.util.onAppVisible","process_","fireauth.ProactiveRefresh.prototype.stop","fireauth.StsTokenManager.prototype.toPlainObject","fireauth.StsTokenManager.prototype.getToken","opt_forceRefresh","forceRefresh","isRefreshTokenExpired","isExpired_","fireauth.StsTokenManager.TOKEN_REFRESH_BUFFER","requestToken_","exchangeRefreshToken_","grant_type","refresh_token","fireauth.UserMetadata.prototype.toPlainObject","lastLoginAt","createdAt","fireauth.AuthUser.prototype.setLanguageCode","fireauth.AuthUser.prototype.getLanguageCode","fireauth.AuthUser.prototype.getFramework","fireauth.AuthUser.prototype.handleUserTokenChange_","FIREBASE","fireauth.AuthUser.prototype.reload","fireauth.AuthUser.returnNothing_","fireauth.AuthUser.prototype","fireauth.AuthUser.prototype.getIdTokenResult","fireauth.AuthUser.prototype.getIdToken","fireauth.AuthUser.prototype.parseAccountInfo_","users","linkedAccounts","providerInfo","fireauth.AuthUserInfo","extractLinkedAccounts_","userServerResponse","fireauth.AuthUser.prototype.reauthenticateAndRetrieveDataWithCredential","fireauth.deprecation.log","REAUTH_WITH_CREDENTIAL","fireauth.AuthUser.prototype.reauthenticateWithCredential","userCredential","getUserCredential_","REAUTHENTICATE","fireauth.AuthUser.prototype.linkAndRetrieveDataWithCredential","LINK_WITH_CREDENTIAL","fireauth.AuthUser.prototype.linkWithCredential","checkIfAlreadyLinked_","LINK","fireauth.AuthUser.prototype.linkWithPhoneNumber","fireauth.AuthUser.prototype.reauthenticateWithPhoneNumber","fireauth.AuthUser.prototype.updateEmail","fireauth.AuthUser.prototype.updatePhoneNumber","phoneCredential","fireauth.AuthUser.prototype.updatePassword","fireauth.AuthUser.prototype.updateProfile","profile","profileRequest","fireauth.AuthUser.prototype.unlink","fireauth.RpcHandler.prototype.deleteLinkedAccounts","providersToDelete","fireauth.RpcHandler.ApiMethod.DELETE_LINKED_ACCOUNTS","deleteProvider","deleteLinkedAccounts","remainingProviderIds","pId","notifyStateChangeListeners_","fireauth.AuthUser.prototype.delete","fireauth.RpcHandler.ApiMethod.DELETE_ACCOUNT","unsubscribe","fireauth.AuthUser.prototype.canHandleAuthEvent","LINK_VIA_POPUP","getPopupEventId","REAUTH_VIA_POPUP","LINK_VIA_REDIRECT","getRedirectEventId","REAUTH_VIA_REDIRECT","fireauth.AuthUser.prototype.resolvePendingPopupEvent","fireauth.AuthUser.prototype.getAuthEventHandlerFinisher","fireauth.AuthUser.prototype.linkWithPopup","runOperationWithPopup_","fireauth.AuthUser.prototype.reauthenticateWithPopup","fireauth.AuthUser.prototype.linkWithRedirect","runOperationWithRedirect_","fireauth.AuthUser.prototype.reauthenticateWithRedirect","fireauth.AuthUser.prototype.finishPopupAndRedirectLink","fireauth.AuthUser.prototype.finishPopupAndRedirectReauth","fireauth.AuthUser.prototype.sendEmailVerification","opt_actionCodeSettings","latestIdToken","buildRequest","fireauth.AuthUser.prototype.verifyBeforeUpdateEmail","fireauth.AuthUser.prototype.handleMultiFactorIdTokenResolver_","fireauth.AuthCredential.verifyTokenResponseUid","fireauth.AuthUser.prototype.toJSON","fireauth.AuthUser.prototype.toPlainObject","stsTokenManager","redirectEventId","fireauth.object.makeWritableCopy","fireauth.storage.RedirectUserManager.prototype.removeRedirectUser","fireauth.storage.UserManager","fireauth.storage.UserManager.prototype.initialize_","localKey","fireauth.storage.UserManager.getAuthUserKey_","sessionKey","inMemoryKey","fireauth.authStorage.Manager.prototype.migrateFromLocalStorage","oldStorageValue","fireauth.storage.UserManager.PERSISTENCE_KEY_","persistence","currentKey","fireauth.storage.UserManager.prototype.removeAllExcept_","goog.Promise.all","toFulfill","onFulfill","onReject","fireauth.storage.UserManager.prototype.switchToLocalOnExternalEvent_","waitForReady_","fireauth.storage.UserManager.AUTH_USER_KEY_NAME_","fireauth.storage.UserManager.prototype.setCurrentUser","currentUser","fireauth.storage.UserManager.prototype.removeCurrentUser","fireauth.storage.UserManager.prototype.getCurrentUser","opt_authDomain","fireauth.storage.UserManager.prototype.waitForReady_","fireauth.Auth","app_","setCurrentUser_","getStorageKey","fireauth.Auth.prototype.initAuthState_","fireauth.Auth.prototype.initRedirectUser_","fireauth.storage.RedirectUserManager.prototype.getRedirectUser","getRedirectUser","initRedirectUser_","removeCurrentUser","initAuthState_","fireauth.Auth.prototype.initAuthRedirectState_","userStorageManager_","initAuthRedirectState_","fireauth.Auth.prototype.initAuthEventManager_","enablePopupRedirect","currentUser_","redirectUser_","initAuthEventManager_","fireauth.Auth.prototype.initializeReadableWritableProps_","initializeReadableWritableProps_","fireauth.Auth.prototype.getAuthEventManager_","fireauth.Auth.prototype.getRedirectResultWithoutClearing_","getAuthEventManager_","fireauth.Auth.prototype.signInWithIdTokenResponse","fireauth.AuthUser.initializeFromIdTokenResponse","opt_redirectStorageManager","fireauth.Auth.prototype.setCurrentUser_","attachEventListeners_","fireauth.AuthUser.prototype.removeStateChangeListener","removeStateChangeListener","stopProactiveRefresh","startProactiveRefresh","setUserLanguage_","setLanguageCodeChangeDispatcher","setUserFramework_","setFrameworkChangeDispatcher","fireauth.Auth.prototype.signInWithIdTokenProvider_","idTokenPromise","fireauth.Auth.prototype.app_","fireauth.Auth.prototype.currentUser_","fireauth.Auth.prototype.getLastAccessToken_","fireauth.Auth.prototype.notifyAuthListeners_","getLastAccessToken_","fireauth.Auth.prototype.registerPendingPromise_","fireauth.grecaptcha","fireauth.GRecaptchaMockFactory","fireauth.GRecaptchaMockFactory.START_INSTANCE_ID","fireauth.storage.UserManager.prototype.setPersistence","invalidTypeError","unsupportedTypeError","fireauth.Auth.LanguageCodeChangeEvent","fireauth.Auth.FrameworkChangeEvent","un","fireauth.Auth.prototype.setPersistence","fireauth.Auth.prototype.setLanguageCode","updateCustomLocaleHeader","notifyLanguageCodeListeners_","fireauth.Auth.prototype.getLanguageCode","fireauth.Auth.prototype.useDeviceLanguage","fireauth.Auth.prototype.logFramework","frameworkId","fireauth.Auth.prototype.getFramework","fireauth.Auth.prototype.setTenantId","fireauth.Auth.prototype.getTenantId","fireauth.Auth.prototype","fireauth.Auth.prototype.toJSON","fireauth.Auth.prototype.canHandleAuthEvent","SIGN_IN_VIA_REDIRECT","SIGN_IN_VIA_POPUP","fireauth.Auth.prototype.resolvePendingPopupEvent","fireauth.Auth.prototype.getAuthEventHandlerFinisher","fireauth.Auth.prototype.finishPopupAndRedirectSignIn","verifyAssertion","fireauth.Auth.prototype.signInWithPopup","manager","fireauth.Auth.prototype.signInWithRedirect","fireauth.storage.UserManager.prototype.savePersistenceForRedirect","fireauth.Auth.prototype.getRedirectResult","getRedirectResultWithoutClearing_","clearRedirectResult","fireauth.Auth.prototype.updateCurrentUser","newUser","fireauth.AuthUser.copyUser","opt_appOptions","stsTokenManager_","getRefreshToken","fireauth.Auth.prototype.signOut","fireauth.Auth.prototype.syncAuthUserChanges_","U","thisId","thatId","otherUser","fireauth.Auth.prototype.handleUserStateChange_","fireauth.Auth.prototype.handleUserTokenChange_","fireauth.Auth.prototype.handleUserDelete_","fireauth.Auth.prototype.handleUserInvalidated_","fireauth.Auth.prototype.handleMultiFactorIdTokenResolver_","fireauth.Auth.prototype.initIdTokenChangeObserver_","fireauth.Auth.prototype.initUserStateObserver_","fireauth.Auth.prototype.addUserChangeListener_","addUserChangeListener_","fireauth.Auth.prototype.onIdTokenChanged","opt_completed","fireauth.Auth.prototype.onAuthStateChanged","fireauth.Auth.prototype.getIdTokenInternal","stsAccessToken","fireauth.Auth.prototype.signInWithCustomToken","fireauth.RpcHandler.ApiMethod.VERIFY_CUSTOM_TOKEN","fireauth.Auth.prototype.signInWithEmailAndPassword","fireauth.Auth.prototype.createUserWithEmailAndPassword","fireauth.RpcHandler.ApiMethod.CREATE_ACCOUNT","fireauth.Auth.prototype.signInWithCredential","fireauth.Auth.prototype.signInAndRetrieveDataWithCredential","SIGN_IN_WITH_CREDENTIAL","fireauth.Auth.prototype.signInAnonymously","fireauth.Auth.prototype.getUid","fireauth.Auth.prototype.addAuthTokenListenerInternal","fireauth.Auth.prototype.removeAuthTokenListenerInternal","fireauth.Auth.prototype.addAuthTokenListener","fireauth.Auth.prototype.removeAuthTokenListener","fireauth.Auth.prototype.delete","fireauth.Auth.prototype.fetchSignInMethodsForEmail","fireauth.RpcHandler.prototype.fetchSignInMethodsForIdentifier","fireauth.RpcHandler.ApiMethod.CREATE_AUTH_URI","continueUri","fetchSignInMethodsForIdentifier","getRpcHandler","fireauth.Auth.prototype.isSignInWithEmailLink","fireauth.Auth.prototype.sendSignInLinkToEmail","actionCodeSettings","actionCodeSettingsBuilder","fireauth.Auth.prototype.verifyPasswordResetCode","fireauth.Auth.prototype.confirmPasswordReset","fireauth.Auth.prototype.checkActionCode","fireauth.Auth.prototype.applyActionCode","fireauth.Auth.prototype.sendPasswordResetEmail","fireauth.Auth.prototype.signInWithPhoneNumber","fireauth.ConfirmationResult.initialize","fireauth.Auth.prototype.signInWithEmailLink","opt_link","fireauth.grecaptcha.prototype.render","fireauth.grecaptcha.prototype.reset","fireauth.grecaptcha.prototype.getResponse","fireauth.grecaptcha.prototype.execute","fireauth.GRecaptchaMockFactory.instance_","fireauth.GRecaptchaMockFactory.prototype.getMock_","getId_","fireauth.GRecaptchaMockFactory.prototype.getId_","fireauth.RecaptchaMock","elementOrId","this.onClickHandler_","CLICK","fireauth.RecaptchaMock.prototype.checkIfDeleted_","fireauth.PhoneMultiFactorGenerator","fireauth.RecaptchaMockLoader","fireauth.GRecaptchaMockFactory.prototype.render","fireauth.GRecaptchaMockFactory.prototype.reset","mock","getMock_","fireauth.GRecaptchaMockFactory.prototype.getResponse","fireauth.GRecaptchaMockFactory.prototype.execute","fireauth.RecaptchaMock.prototype.getResponse","checkIfDeleted_","fireauth.RecaptchaMock.prototype.execute","fireauth.util.generateRandomAlphaNumericString","expirationCallback","fireauth.GRecaptchaMockFactory.EXPIRATION_TIME_MS","fireauth.GRecaptchaMockFactory.SOLVE_TIME_MS","fireauth.RecaptchaMock.prototype.delete","fireauth.RecaptchaMockLoader.prototype.loadRecaptchaDeps","fireauth.RecaptchaMockLoader.prototype.clearSingleRecaptcha","fireauth.RecaptchaMockLoader.instance_","fireauth.RecaptchaRealLoader","fireauth.RecaptchaRealLoader.RECAPTCHA_SRC_","fireauth.RecaptchaRealLoader.DEFAULT_DEPENDENCY_TIMEOUT_","fireauth.RecaptchaRealLoader.prototype.loadRecaptchaDeps","hl","timer","fireauth.RecaptchaRealLoader.DEFAULT_DEPENDENCY_TIMEOUT_.get","render","parameters","widgetId","fireauth.RecaptchaRealLoader.prototype.clearSingleRecaptcha","fireauth.RecaptchaRealLoader.instance_","fireauth.BaseRecaptchaVerifier","opt_parameters","opt_getLanguageCode","opt_rpcHandlerConfig","opt_isTestingMode","theme","fireauth.BaseRecaptchaVerifier.ParamName.SITEKEY","fireauth.BaseRecaptchaVerifier.ParamName.SIZE","existingCallback","fireauth.BaseRecaptchaVerifier.ParamName.CALLBACK","existingExpiredCallback","fireauth.BaseRecaptchaVerifier.ParamName.EXPIRED_CALLBACK","CALLBACK","EXPIRED_CALLBACK","SITEKEY","SIZE","fireauth.BaseRecaptchaVerifier.prototype.dispatchEvent_","fireauth.BaseRecaptchaVerifier.prototype.registerPendingPromise_","fireauth.BaseRecaptchaVerifier.prototype.checkIfDestroyed_","opt_app","isTestingMode","getLanguageCode","fireauth.args.validate","apiName","expected","actual","opt_isSetter","actualAsArray","numRequiredArgs","isOptionalSection","maxNumArgs","minNumArgs","optionalUndefined","fireauth.args.ORDINAL_NUMBERS_.length","fireauth.args.ORDINAL_NUMBERS_","ordinal","expectedType","Yn","fireauth.BaseRecaptchaVerifier.prototype.isReady_","grecaptcha","fireauth.RpcHandler.ApiMethod.GET_RECAPTCHA_PARAM","fireauth.BaseRecaptchaVerifier.prototype.render","checkIfDestroyed_","outerContainer","goog.dom.createDom","goog.dom.TagName.DIV","fireauth.BaseRecaptchaVerifier.prototype.verify","fireauth.BaseRecaptchaVerifier.prototype.removeTokenChangeListener_","removeTokenChangeListener_","fireauth.BaseRecaptchaVerifier.prototype.reset","fireauth.BaseRecaptchaVerifier.prototype","fireauth.BaseRecaptchaVerifier.prototype.clear","fireauth.RecaptchaVerifier","opt_optional","typeLabel","validator","fireauth.args.bool","fireauth.args.object","fireauth.args.func","fireauth.args.null","fireauth.args.authCredential","opt_requiredProviderId","matchesRequiredProvider","fireauth.args.validateMultiFactorSession_","fireauth.args.validateMultiFactorInfo_","fireauth.args.applicationVerifier","fireauth.args.or","optionA","optionB","fireauth.exportlib.exportPrototypeMethods","protObj","fnMap","obfuscatedFnName","unobfuscatedFnName","fireauth.exportlib.wrapMethodWithArgumentVerifier_","fireauth.exportlib.exportPrototypeProperties","propMap","obfuscatedPropName","unobfuscatedPropName","getter","expectedArg","fireauth.exportlib.exportFunction","parentObj","func","opt_expectedArgs","methodName","argumentsAsArray","shortName","fireauth.exportlib.extractMethodNameFromFullPath_","applyActionCode","fireauth.args.string","checkActionCode","confirmPasswordReset","createUserWithEmailAndPassword","fetchSignInMethodsForEmail","getRedirectResult","isSignInWithEmailLink","onAuthStateChanged","onIdTokenChanged","sendPasswordResetEmail","sendSignInLinkToEmail","setPersistence","signInAndRetrieveDataWithCredential","signInAnonymously","signInWithCredential","signInWithCustomToken","signInWithEmailAndPassword","signInWithEmailLink","signInWithPhoneNumber","signInWithPopup","signInWithRedirect","updateCurrentUser","signOut","toJSON","useDeviceLanguage","verifyPasswordResetCode","lc","ti","getIdTokenResult","getIdToken","linkAndRetrieveDataWithCredential","linkWithCredential","linkWithPhoneNumber","linkWithPopup","linkWithRedirect","reauthenticateAndRetrieveDataWithCredential","reauthenticateWithCredential","reauthenticateWithPhoneNumber","reauthenticateWithPopup","reauthenticateWithRedirect","reload","sendEmailVerification","unlink","updateEmail","updatePassword","updatePhoneNumber","updateProfile","verifyBeforeUpdateEmail","execute","getResponse","thenAlways","appVerificationDisabled","confirm","fireauth.AuthProvider.getCredentialFromJSON","fromJSON","fireauth.OAuthCredential.fromJSON","fireauth.EmailAuthCredential.fromJSON","fireauth.PhoneAuthCredential.fromJSON","fireauth.SAMLAuthCredential.fromJSON","fireauth.EmailAuthProvider.credential","toPlainObject","addScope","setCustomParameters","fireauth.FacebookAuthProvider.credential","fireauth.GithubAuthProvider.credential","fireauth.GoogleAuthProvider.credential","fireauth.TwitterAuthProvider.credential","resolveSignIn","getSession","enroll","unenroll","verify","fireauth.PhoneMultiFactorGenerator.assertion","ActionCodeInfo","Operation","Auth","AuthCredential","authComponent","fireauth.exportlib.AUTH_TYPE","authInteropComponent","getUid","getToken","addAuthTokenListener","removeAuthTokenListener","AUTH_NPM_PACKAGE_VERSION","User","DOMStorageWrapper","domStorage_","removeItem","prefixedName_","setItem","storedVal","getItem","prefix_","MemoryStorage","cache_","createStoragefor","domStorageName","domStorage","sha1","utf8Bytes","high","sha1Bytes","enableLogging","logClient","SessionStorage","varArgs","firstLog_","buildLogMessage_","logWrapper","fatal","isInvalidJSONNumber","POSITIVE_INFINITY","NEGATIVE_INFINITY","stringCompare","requireKey","splitStringBySize","segsize","dataSegs","substring","PersistentStorage","LUIDGenerator","MIN_NAME","MAX_NAME","nameCompare","aAsInt","tryParseInt","bAsInt","ObjectToUniqueKey","sort","each","doubleToIEEE754String","ln","abs","pow","LN2","round","bits","reverse","hexByteString","substr","exceptionGuard","setTimeoutNonBlocking","time","INTEGER_REGEXP_","intVal","Path","pieceNum_","pieces_","pieceNum","pathString","begin","childPathObj","childPieces","outerPath","innerPath","outer","getFront","inner","relativePath","popFront","leftKeys","rightKeys","cmp","other","getLength","pathOrString","copyTo","ValidationPath","parts_","byteLength_","checkValid_","MAX_PATH_LENGTH_BYTES","errorPrefix_","MAX_PATH_DEPTH","toErrorString","FORGE_DOMAIN","WEBSOCKET","LONG_POLLING","RepoInfo","internalHost","isCustomHost","includeNamespaceInQueryParams","newHost","isCacheableHost","connURL","secure","needsQueryParam","toURLString","persistenceKey","webSocketOnly","parseRepoInfo","dataURL","parsedUrl","parseDatabaseURL","repoInfo","subdomain","isValidKey","INVALID_KEY_REGEX_","isValidPathString","INVALID_PATH_REGEX_","isValidPriority","priority","validateFirebaseDataArg","validateFirebaseData","errorPrefixFxn","validateFirebaseMergeDataArg","mergePaths","curPath","getBack","comparePaths","prevPath","validateFirebaseMergePaths","validatePriority","validateEventType","validateKey","validatePathString","validateWritablePath","validateUrl","isValidRootPathString","colonInd","slashInd","questionMarkInd","pathStringDecoded","piece","decodePath","queryParams","queryString","kv","decodeQuery","MAX_LEAF_SIZE_","path_","hasDotValue_1","hasActualChild_1","OnDisconnect","onComplete","repo_","onDisconnectCancel","wrapCallback","onDisconnectSet","onDisconnectSetWithPriority","objectToMerge","newObjectToMerge","onDisconnectUpdate","TransactionResult","committed","snapshot","PUSH_CHARS","lastPushTime","lastRandChars","nextPushId","duplicateTime","timeStampChars","NamedNode","__EMPTY_NODE","Index","compare","oldNode","newNode","oldWrapped","newWrapped","MIN","KeyIndex","indexValue","MAX_NODE","KEY_INDEX","priorityHashText","validatePriorityNode","priorityNode","isLeafNode","getPriority","__childrenNodeConstructor","nodeFromJSON","LeafNode","priorityNode_","newPriorityNode","value_","childName","EMPTY_NODE","childNode","newChildNode","updatePriority","updateImmediateChild","front","updateChild","action","exportFormat",".value","getValue",".priority","lazyHash_","toHash","compareToLeafNode_","otherLeaf","otherLeafType","thisLeafType","otherIndex","VALUE_TYPE_ORDER","thisIndex","equals","PRIORITY_INDEX","PriorityIndex","aPriority","bPriority","indexCmp","compareTo","SortedMapIterator","nodeStack_","resultGenerator_","isReverse_","startKey","comparator","LLRBNode","color","inorderTraversal","reverseTraversal","min_","maxKey","insert","fixUp_","SortedMap","isRed_","moveRedLeft_","removeMin_","smallest","rotateRight_","moveRedRight_","rotateLeft_","colorFlip_","nl","RED","nr","blackDepth","LLRBEmptyNode","comparator_","root_","BLACK","rightParent","minKey","resultGenerator","LOG_2","Base12Num","bits_","current_","num","mask","_defaultIndexMap","buildChildSet","childList","keyFn","mapSortFn","buildBalancedTree","low","namedNode","middle","root","base12","buildPennant","chunkSize","childTree","attachPennant","pennant","isOne","nextBitIsOne","buildFrom12Array","fallbackObject","IndexMap","indexKey","sortedMap","indexes_","indexDefinition","indexSet_","existingChildren","newIndex","sawIndexedValue","Wrap","getNext","isDefinedOn","getCompare","indexName","newIndexSet","newIndexes","indexedChildren","existingSnap","newChildren","NAME_ONLY_COMPARATOR","NAME_COMPARATOR","ChildrenNode","Default","children_","indexMap_","getImmediateChild","getChild","newIndexMap","removeFromIndexes","addToIndexes","newPriority","newImmediateChild","numKeys","allIntegerKeys","forEachChild","toHash_1","childHash","hash","idx","resolveIndex_","predecessor","getPredecessorKey","getFirstChildName","getLastChildName","wrappedNode","getIteratorFrom","minPost","startPost","peek","getReverseIteratorFrom","maxPost","endPost","hasIndex","addIndex","otherChildrenNode","thisIter","otherIter","thisCurrent","otherCurrent","MaxNode","MAX","USE_HINZE","node_1","childData","children_1","childrenHavePriority_1","childSet","sortedChildSet","VALUE_INDEX","ValueIndex","valueNode","PathIndex","snap","indexPath_","aChild","extractChild","bChild","DataSnapshot","node_","exportVal","childPathString","childPath","childRef","ref_","index_","getKey","numChildren","getRef","DataEvent","ref","getParent","eventRegistration","getEventRunner","prevName","CancelEvent","ValueEventRegistration","change","getQueryParams","getIndex","snapshotNode","ctx","context_","getEventType","cancelCallback_","cancelCB_1","cb_1","callback_","__referenceConstructor","ChildEventRegistration","eventToCheck","callbacks_","cancelCB_2","cb_2","otherKeys","thisKeys","otherCount","otherKey","thisKey","Query","startNode","endNode","hasStart","getIndexStartValue","hasEnd","getIndexEndValue","tooManyArgsError","wrongArgTypeError","getIndexStartName","getIndexEndName","hasLimit","hasAnchoredLimit","orderByCalled_","queryParams_","repo","cancelCallbackOrContext","getCancelAndContextArgs_","onValueEvent","cancel","callbacks","onChildEvent","cancelCallback","addEventCallbackForQuery","removeEventCallbackForQuery","userCallback","failureCallbackOrContext","firstCall","onceCallback","off","on","limit","limitToFirst","limitToLast","validateNoPreviousOrderByCall_","parsedPath","newParams","orderBy","validateQueryEndpoints_","startAt","validateLimit_","endAt","toUrlEncodedString","getQueryObject","queryObject","sameRepo","samePath","sameQueryIdentifier","queryIdentifier","cancelOrContext","SparseSnapshotTree","children","childKey","remember","self_1","tree","forget","prefixPath","forEachTree","resolveDeferredValue","serverValues","OperationType","resolveDeferredValueSnapshot","rawPri","leafNode","childrenNode","OperationSource","queryId","fromUser","fromServer","tagged","emptyChildrenSingleton","AckUserWrite","affectedTree","subtree","Empty","revert","ACK_USER_WRITE","ImmutableTree","childSnap","predicate","childExistingPathAndValue","findRootMostMatchingPathAndValue","toSet","newChild","newTree","setTree","fold_","pathSoFar","accum","findOnPath_","pathToFollow","nextChild","foreachOnPath_","currentRelativePath","foreach_","ListenComplete","LISTEN_COMPLETE","Overwrite","OVERWRITE","Merge","MERGE","CacheNode","fullyInitialized_","filtered_","isFullyInitialized","isCompleteForChild","hasChild","ViewCache","eventSnap","filtered","serverCache_","serverSnap","eventCache_","getNode","Change","VALUE","CHILD_ADDED","CHILD_REMOVED","newSnapshot","oldSnapshot","CHILD_CHANGED","CHILD_MOVED","oldSnap","IndexedFilter","affectedPath","optChangeAccumulator","isIndexed","oldChild","trackChildChange","childRemovedChange","childAddedChange","childChangedChange","withIndex","newSnap","ChildChangeAccumulator","oldChange","changeMap","oldType","NO_COMPLETE_CHILD_SOURCE","NoCompleteChildSource_","WriteTreeCompleteChildSource","viewCache_","getEventCache","serverNode","optCompleteServerCache_","getServerCache","writes_","calcCompleteChild","completeServerData","getCompleteServerSnap","nodes","calcIndexedSlice","viewCache","changes","ViewProcessor","filter_","oldViewCache","writesCache","completeCache","newViewCache","filterServerNode","overwrite","applyUserOverwrite_","isFiltered","applyServerOverwrite_","applyUserMerge_","applyServerMerge_","ackUserWrite","revertUserWrite_","ackUserWrite_","listenComplete_","getChanges","maybeAddValueEvent_","ProcessorResult","isLeafOrEmpty","oldCompleteSnap","getCompleteEventSnap","valueChange","changePath","oldEventSnap","shadowingWrite","newEventCache","serverCache","completeChildren","completeEventChildren","calcCompleteEventChildren","updateFullNode","completeNode","calcCompleteEventCache","oldEventNode","updatedPriority","calcEventCacheAfterServerOverwrite","childChangePath","newEventChild","eventChildUpdate","updateEventSnap","filtersNodes","changedSnap","newServerCache","oldServerSnap","serverFilter","getIndexedFilter","newServerNode","isCompleteForPath","updateServerSnap","generateEventCacheAfterServerEvent_","getCompleteChild","newEventSnap","changedChildren","curViewCache","foreach","writePath","cacheHasChild_","viewMergeTree","serverChild","applyMerge_","childMergeTree","isUnknownDeepMerge","ackPath","changedChildren_1","changedChildren_2","mergePath","serverCachePath","oldServerNode","completeServerCache","oldEventCache","serverChildren","EventGenerator","eventCache","eventRegistrations","events","moves","indexedValueChanged","childMovedChange","generateEventsForType_","registrations","filteredChanges","compareChanges_","materializedChange","materializeSingleChange_","respondsTo","query_","getPredecessorChildName","aWrapped","bWrapped","View","loadsAllData","eventRegistrations_","cancelError","cancelEvents","path_1","maybeEvent","createCancelEvent","existing","hasAnyCallback","processor_","applyOperation","assertIndexed","generateEventsForChanges_","initialChanges","eventGenerator_","generateEventsForChanges","initialViewCache","indexFilter","getNodeFilter","initialServerCache","initialEventCache","SyncPoint","views","optCompleteServerCache","serverCacheComplete","eventCacheComplete","addEventRegistration","getInitialEvents","hadCompleteView","hasCompleteView","viewQueryId","removeEventRegistration","getQuery","getCompleteServerCache","getCompleteView","viewForQuery","CompoundWrite","rootmost","writeTree_","findRootMostValueAndPath","rootMostPath","updates","newWrite","addWrite","getCompleteNode","shadowingNode","applySubtreeWrite","writeTree","priorityWrite_1","WriteTree","WriteTreeRef","writeId","visible","lastWriteId_","allWrites_","visibleWrites_","addWrites","record","writeToRemove","splice","removedWriteWasVisible","removedWriteOverlapsWithOtherWrites","currentWrite","recordContainsPath_","resetTree_","removeWrite","treePath","writeIdsToExclude","includeHiddenWrites","childCompoundWrite","hasCompleteWrite","mergeAtPath","layerTree_","layeredCache","subMerge","completeServerChildren","topLevelSet","merge_1","getCompleteChildren","existingEventSnap","existingServerSnap","childMerge","toIterate","writeRecord","DefaultFilter_","writes","treeRoot","compoundWrite","deepNode","treePath_","existingServerCache","SyncTree","newData","pendingWriteTree_","addOverwrite","applyOperationToSyncPoints_","addMerge","changeTree","fromObject","getWrite","affectedTree_1","Server","queryKey","queryKeyForTag_","parseQueryKey_","queryPath","forServerTaggedQuery","applyTaggedOperation_","foundAncestorDefaultView","syncPointTree_","foreachOnPath","pathToSyncPoint","sp","syncPoint","foreachChild","childSyncPoint","viewAlreadyExists","viewExistsForQuery","makeQueryKey_","queryToTagMap","getNextQueryTag_","tagToQueryMap","childWrites","setupListener_","maybeSyncPoint","removedAndEvents","removingDefault","covered","findOnPath","parentSyncPoint","newViews","collectDistinctViewsForSubTree_","newQuery","createListenerForView_","listenProvider_","startListening","queryForListening_","tagForQuery_","hashFn","stopListening","queryToRemove","tagToRemove","removeTags_","fold","maybeChildSyncPoint","childMap","views_1","getQueryViews","_key","childViews","queries","removedQuery","removedQueryKey","removedQueryTag","isDefault","queriesToStop","queries_1","childQueries","queryToStop","applyTaggedListenComplete","applyListenComplete","errorForServerCode","splitIndex","nextQueryTag_","applyOperationHelper_","syncPointTree","applyOperationDescendantsHelper_","childOperation","operationForChild","childServerCache","childWritesCache","SnapshotHolder","rootNode_","newSnapshotNode","AuthTokenProvider","auth_","authProvider_","StatsCollection","amount","counters_","StatsManager","hashString","collections_","creatorFunction","reporters_","StatsListener","newStats","collection_","delta","last_","StatsReporter","statsToReport_","stats","statsListener_","reportedStats","haveStatsToReport","server_","reportStats","reportStats_","EventQueue","eventDataList","currList","eventPath","eventLists_","EventList","queueEvents","raiseQueuedEventsMatchingPredicate_","changedPath","recursionDepth_","sentAll","eventList","raise","events_","eventFn","EventEmitter","listeners_","listeners","validateEventType_","getInitialEvent","allowedEvents_","et","VisibilityMonitor","visible_","hidden","visibilityChange","trigger","OnlineMonitor","online_","PacketReceiver","responseNum","closeAfterResponse","currentResponseNum","requestNum","pendingResponses","toProcess","this_1","onMessage_","BrowserPollConnection","onDisconnect","curSegmentNum","onDisconnect_","myPacketOrderer","isClosed_","connectTimeoutTimer_","log_","onClosed_","called_1","wrappedFn_1","attachEvent","executeWhenDOMReady","scriptTagHolder","FirebaseIFrameScriptHolder","command","arg1","arg2","incrementIncomingBytes_","everConnected_","sendNewPolls","closeAfter","pN","handleResponse","urlFn","urlParams","start","uniqueCallbackIdentifier","transportSessionId","lastSessionId","href","connectURL","addTag","startLongPoll","addDisconnectPingFrame","forceAllow_","forceDisallow_","Windows","UI","myDisconnFrame","shutdown_","dataStr","bytesSent","stats_","incrementCounter","base64data","base64Encode","MAX_URL_DATA_SIZE","enqueueSegment","pw","dframe","bytesReceived","connId","getCollection","connectionURL","contentDocument","alive","myIFrame","innerHTML","myID","myPW","newRequest_","outstandingRequests","pendingSegs","currentSerial","theURL","curDataString","theSeg","seg","ts","addLongPollTag_","segnum","totalsegs","serial","doNewRequest","keepaliveTimeout","loadCB","newScript_1","async","onreadystatechange","rstate","parentNode","commandCB","onMessageCB","createIFrame_","iframeContents","WebSocketImpl","MozWebSocket","WebSocket","WebSocketConnection","device","ENV_CONSTANTS","User-Agent","platform","env","mySock","onopen","onclose","handleIncomingFrame","isOldAndroid","oldAndroidMatch","isInMemoryStorage","frames","totalFrames","fullMess","jsonMess","frameCount","handleNewFrameCount_","mess","resetKeepAlive","appendFrame_","remainingData","extractFrameCount_","sendString_","keepaliveTimer","connectionURL_","TransportManager","isWebSocketsAvailable","isSkipPollConnection","previouslyFailed","transports_","transports","ALL_TRANSPORTS","transport","initTransports_","Connection","conn","transportManager_","initialTransport","conn_","nextTransportId_","repoInfo_","primaryResponsesRequired_","onMessageReceived","connReceiver_","onConnectionLost","disconnReceiver_","tx_","rx_","secondaryConn_","isHealthy_","healthyTimeoutMS","healthyTimeout_","markConnectionHealthy","connectionCount","everConnected","onConnectionLost_","onSecondaryConnectionLost_","state_","onPrimaryMessageReceived_","onSecondaryMessageReceived_","dataMsg","sendData_","controlData","cmd","upgradeIfSecondaryHealthy_","secondaryResponsesRequired_","parsedData","layer","onSecondaryControl_","pendingDataMessages","proceedWithUpgrade_","tryCleanupConnection","onControl_","onDataMessage_","onPrimaryResponse_","payload","onHandshake_","onConnectionShutdown_","onReset_","sendPingOnPrimaryIfNecessary_","handshake","timestamp","updateHost","onConnectionEstablished_","tryStartUpgrade_","upgradeTransport","startUpgrade_","closeConnections_","start_","onReady_","onKill_","ServerActions","PersistentConnection","onResponse","curReqNum","requestNumber_","connected_","realtime_","sendRequest","requestCBHash_","currentHashFn","listens","listenSpec","sendListen_","req","warnOnListenWarnings_","removeListen_","warnings","indexSpec","indexPath","authToken_","tryAuth","reduceReconnectDelayIfAdminCredential_","isAdmin","maxReconnectDelay_","token_1","authMethod","isValidFormat","requestData","cred","authOverride_","invalidAuthTokenCount_","onAuthRevoked_","sendUnlisten_","queryObj","sendOnDisconnect_","onDisconnectRequestQueue_","putInternal","outstandingPuts_","outstandingPutCount_","sendPut_","queued","errorReason","reqNum","onDataPush_","onDataUpdate_","onListenRevoked_","onSecurityDebugPacket_","lastConnectionEstablishedTime_","handleTimestamp_","firstConnection_","sendConnectStats_","restoreState_","onConnectStatus_","establishConnectionTimer_","establishConnection_","reconnectDelay_","scheduleConnect_","online","cancelSentTransactions_","shouldReconnect_","lastConnectionAttemptTime_","timeSinceLastConnectAttempt","reconnectDelay","onDataMessage_1","onReady_1","onDisconnect_1","onRealtimeDisconnect_","connId_1","nextConnectionId_","lastSessionId_1","canceled_1","connection_1","closeFn_1","forceTokenRefresh_","authTokenProvider_","interrupt","interruptReasons_","onServerInfoUpdate_","serverTimeOffset","q","normalizedPathString","statusCode","explanation","notifyForInvalidToken","securityDebugCallback_","_c","_e","getInstance","currentlyOnline","nextPersistentConnectionId_","onVisible_","onOnline_","ReadonlyRestClient","listenId","getListenId_","thisListen","listens_","queryStringParameters","toRestQueryStringParameters","restRequest_","authTokenData","authToken","querystringParams","arrayVal","querystring","INTERRUPT_REASON","Repo","infoData_","generateWithValues","serverTime","isMerge","dataUpdateCount","interceptServerDataCallback_","taggedChildren","raw","serverSyncTree_","applyTaggedQueryMerge","taggedSnap","applyTaggedQueryOverwrite","applyServerMerge","applyServerOverwrite","rerunTransactions_","eventQueue_","raiseEventsForChangedPath","connectStatus","updateInfo_","runOnDisconnectEvents_","updateSnapshot","infoSyncTree_","nextWriteId_","newVal","generateServerValues","newNodeUnresolved","getNextWriteId_","applyUserOverwrite","success","clearEvents","callOnCompleteCallback","abortTransactions_","childrenToMerge","empty","changedKey","changedValue","writeId_1","applyUserMerge","resolvedOnDisconnectTree","resolvedTree","resolveDeferredValueTree","onDisconnectPut","onDisconnectMerge","raiseEventsAtPath","persistentConnection_","resume","showDelta","longestName","previousValue","paddedStat","metric","statsReporter_","includeStat","__database","Database","forceRestClient","authProvider","authTokenProvider","authOverride","addTokenChangeListener","refreshAuthToken","getOrCreateReporter","transactionsInit_","infoEvents","unlisten","RangedFilter","startPost_","endPost_","getStartPost","getEndPost","indexedFilter_","startName","makePost","endName","getStartPost_","getEndPost_","LimitedFilter","rangedFilter_","limit_","fullLimitUpdateChild_","reverse_","hasNext","getReverseIterator","indexCompare_1","foundStartPost","changeAccumulator","indexCmp_1","newChildNamedNode","windowBoundary","getFirstChild","getLastChild","inRange","oldChildSnap","getChildAfterChild","compareNext","getLimit","isViewFromLeft","QueryParams","startSet_","viewFrom_","WIRE_PROTOCOL_CONSTANTS_","VIEW_FROM_LEFT","indexStartValue_","startNameSet_","indexStartName_","endSet_","indexEndValue_","endNameSet_","indexEndName_","limitSet_","newLimit","copy_","VIEW_FROM_RIGHT","WIRE_PROTOCOL_CONSTANTS","INDEX_START_VALUE","INDEX_START_NAME","INDEX_END_VALUE","INDEX_END_NAME","LIMIT","viewFrom","VIEW_FROM","INDEX","REST_CONSTANTS","REST_QUERY_CONSTANTS_","qs","ORDER_BY","START_AT","END_AT","LIMIT_TO_FIRST","LIMIT_TO_LAST","Reference","validateRootPathString","parentPath","database","setWithPriority","transactionUpdate","applyLocally","bool","validateBoolean","startTransaction","thennablePushRef","pushRef","databaseProp","getRoot","TransactionStatus","Tree","pathObj","TreeNode","updateParents_","hasChildren","includeSelf","childrenFirst","forEachDescendant","forEachImmediateDescendantWithValue","updateChild_","childEmpty","childExists","MAX_TRANSACTION_RETRIES_","transactionQueueTree_","valueCallback","watchRef","transaction","retryCount","unwatcher","abortReason","currentWriteId","currentInputSnapshot","currentOutputSnapshotRaw","currentOutputSnapshotResolved","currentState","getLatestState_","RUN","queueNode","subTree","nodeQueue","setValue","priorityForNode","sendReadyTransactions_","excludeSets","pruneCompletedTransactionsBelowNode_","buildTransactionQueue_","sendTransactionQueue_","setsToIgnore","txn","latestState","snapToSend","latestHash","SENT","dataToSend","pathToSend","COMPLETED","SENT_NEEDS_ABORT","NEEDS_ABORT","rootMostTransactionNode","getAncestorTransactionNode_","rerunTransactionQueue_","abortTransaction","currentNode","newDataNode","oldWriteId","newNodeResolved","lastInput","transactionNode","transactionQueue","aggregateTransactionQueuesForNode_","to","forEachAncestor","abortTransactionsOnNode_","lastSent","_staticInstance","DATABASE_URL_OPTION","RepoManager","repos_","dbUrl","dbEmulatorHost","createRepo","appRepos","useRestClient_","checkDeleted_","refFromURL","parsedURL","TIMESTAMP",".sv","DatabaseInternals","deleteRepo","forceDisallow","forceAllow","statsIncrementCounter","interceptServerData_","DataConnection","simpleListen","echo","onEcho","RealTimeConnection","ConnectionTarget","newHash","oldPut","ServerValue","databaseFromApp","setServiceProps","TEST_ACCESS","setMultipleInstances","goog.isNumber","goog.getObjectByName","goog.isArray","childCtor.base","me","goog.isString","goog.string.internal.isEmptyOrWhitespace","Ia","Na","G","xb","goog.Timer","opt_interval","opt_timerObject","goog.Timer.prototype.stop","goog.async.Throttle","interval","goog.async.Throttle.prototype.doAction_","goog.events.EventHandler","Cb","goog.Timer.prototype.tick_","elapsed","goog.Timer.intervalScale","dispatchTick","goog.Timer.TICK","goog.Timer.prototype.start","goog.Timer.prototype","goog.Timer.prototype.disposeInternal","goog.Timer.superClass_.disposeInternal.call","Fb","goog.async.Throttle.prototype.fire","doAction_","goog.async.Throttle.prototype.disposeInternal","goog.async.Throttle.superClass_.disposeInternal.call","goog.async.Throttle.prototype.onTimer_","goog.events.EventHandler.typeArray_","goog.events.EventHandler.prototype.listen_","opt_fn","goog.events.EventHandler.prototype.removeAll","goog.labs.net.webChannel.WebChannelDebug","goog.events.EventHandler.prototype.disposeInternal","goog.events.EventHandler.superClass_.disposeInternal.call","removeAll","goog.events.EventHandler.prototype.handleEvent","goog.labs.net.webChannel.requestStats.statEventTarget_","goog.labs.net.webChannel.requestStats.Event.SERVER_REACHABILITY_EVENT","reachabilityType","goog.labs.net.webChannel.requestStats.statEventTarget_.dispatchEvent","goog.labs.net.webChannel.requestStats.ServerReachabilityEvent","requestStats.StatEvent","goog.labs.net.webChannel.requestStats.Event.STAT_EVENT","goog.labs.net.webChannel.requestStats.StatEvent","requestStats.TimingEvent","goog.labs.net.webChannel.requestStats.Event.TIMING_EVENT","ms","goog.labs.net.webChannel.requestStats.TimingEvent","goog.net.ErrorCode","NO_ERROR","ACCESS_DENIED","FILE_NOT_FOUND","FF_SILENT_ERROR","CUSTOM_ERROR","EXCEPTION","HTTP_ERROR","OFFLINE","goog.net.EventType","INCREMENTAL_DATA","PROGRESS","DOWNLOAD_PROGRESS","UPLOAD_PROGRESS","cachedOptions_","goog.net.WebChannel","Wb","goog.net.WebChannel.EventType","OPEN","CLOSE","MESSAGE","goog.labs.net.webChannel.ChannelRequest","opt_requestId","opt_retryId","goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_","EDGE_POLLING_INTERVAL_","goog.net.WebChannel.MessageEvent","goog.net.WebChannel.ErrorEvent","goog.labs.net.webChannel.ChannelRequest.INVALID_CHUNK_","goog.labs.net.webChannel.ChannelRequest.INCOMPLETE_CHUNK_","ChannelRequest.prototype.xmlHttpPost","postData","XML_HTTP","makeUnique","decodeChunks","sendXmlHttp_","ChannelRequest.prototype.xmlHttpGet","hostPrefix","ChannelRequest.prototype.sendXmlHttp_","ensureWatchDogTimer_","REQUEST_MADE","ChannelRequest.prototype.decodeNextChunks_","decodeNextChunksSuccessful","chunkText","getNextChunk_","BAD_DATA","goog.labs.net.webChannel.requestStats.notifyStatEvent","REQUEST_INCOMPLETE_DATA","REQUEST_BAD_DATA","safeOnRequestData_","NO_DATA","REQUEST_NO_DATA","cleanup_","dispatchFailure_","ChannelRequest.prototype.getNextChunk_","sizeStartIndex","sizeEndIndex","chunkStartIndex","ChannelRequest.prototype.ensureWatchDogTimer_","startWatchDogTimer_","ChannelRequest.prototype.startWatchDogTimer_","goog.labs.net.webChannel.requestStats.setTimeout","ChannelRequest.prototype.cancelWatchDogTimer_","ChannelRequest.prototype.dispatchFailure_","ChannelRequest.prototype.cleanup_","cancelWatchDogTimer_","readyStateChangeThrottle_","xmlhttp","ChannelRequest.prototype.safeOnRequestData_","goog.labs.net.webChannel.requestStats.notifyServerReachabilityEvent","BACK_CHANNEL_ACTIVITY","goog.structs.Map.prototype.remove","M","ChannelRequest.prototype.setTimeout","goog.labs.net.webChannel.ChannelRequest.prototype","ChannelRequest.prototype.readyStateChangeHandler_","throttle","INTERACTIVE","ChannelRequest.prototype.xmlHttpHandler_","onXmlHttpReadyStateChanged_","errorCode","REQUEST_FAILED","REQUEST_SUCCEEDED","getStreamingResponseHeader","goog.net.WebChannel.X_HTTP_INITIAL_RESPONSE","initialResponse","UNKNOWN_SESSION_ID","REQUEST_UNKNOWN_SESSION_ID","decodeNextChunks_","listen_","STATUS","REQUEST_BAD_STATUS","ChannelRequest.prototype.pollResponse_","ChannelRequest.prototype.cancel","ChannelRequest.prototype.onWatchDogTimeout_","CLOSE_REQUEST","handleTimeout_","REQUEST_TIMEOUT","goog.Uri.prototype.clone","goog.Uri.prototype.setDomain","newDomain","goog.Uri.prototype.setParameterValues","goog.Uri.prototype.makeUnique","RANDOM","goog.labs.net.webChannel.BaseTestChannel","BaseTestChannel.prototype.checkBufferingProxy_","bufferingProxyResult","TEST_STAGE_TWO_START","PROXY","testConnectionFinished","NOPROXY","createDataUri","channel_","recvDataUri","goog.labs.net.webChannel.ConnectionState","goog.structs.Set","goog.structs.Set.getKey_","Wire.QueuedMap","mapId","ForwardChannelRequestPool","opt_maxPoolSize","module$contents$goog$labs$net$webChannel$ForwardChannelRequestPool_ForwardChannelRequestPool.MAX_POOL_SIZE_","entrys","goog.global.performance.getEntriesByType","goog.global.chrome","goog.global.chrome.loadTimes","Ac","goog.debug.TextFormatter","goog.debug.Formatter","Sc","goog.labs.net.webChannel.BaseTestChannel.prototype","BaseTestChannel.prototype.createXhrIo","BaseTestChannel.prototype.abort","BaseTestChannel.prototype.isClosed","BaseTestChannel.prototype.onRequestData","INIT","applyControlHeaders_","protocolHeader","goog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL","httpSessionIdHeader","goog.net.WebChannel.X_HTTP_SESSION_ID","respArray","testChannel","signalError_","CONNECTION_TESTING","TEST_STAGE_TWO_DATA_TWO","TEST_STAGE_TWO_DATA_ONE","TEST_STAGE_TWO_DATA_BOTH","BaseTestChannel.prototype.onRequestComplete","checkBufferingProxy_","TEST_STAGE_ONE_FAILED","TEST_STAGE_TWO_FAILED","BaseTestChannel.prototype.shouldUseSecondaryDomains","BaseTestChannel.prototype.isActive","goog.structs.Set.prototype.add","goog.structs.Set.prototype.getValues","ForwardChannelRequestPool.prototype.applyClientProtocol","clientProtocol","addRequest","ForwardChannelRequestPool.prototype.isFull","ForwardChannelRequestPool.prototype.getRequestCount","ForwardChannelRequestPool.prototype.hasRequest","Zc","ForwardChannelRequestPool.prototype.addRequest","ForwardChannelRequestPool.prototype.removeRequest","requestPool_","ForwardChannelRequestPool.prototype.getPendingMessages","goog.json.NativeJsonProcessor","goog.labs.net.webChannel.WireV8","WireV8.prototype.encodeMessage","encodedValue","netUtils.imageCallback_","channelDebug","img","debugText","ForwardChannelRequestPool.prototype.cancel","getPendingMessages","goog.json.NativeJsonProcessor.prototype.stringify","opt_replacer","goog.json.NativeJsonProcessor.prototype.parse","opt_reviver","goog.json.hybrid.parse","goog.net.XhrIo.prototype.getStreamingResponseHeader","exports.setHttpHeadersWithOverwriteParam","urlParam","extraHeaders","exports.generateHttpHeadersOverwriteParam","module$exports$goog$net$rpc$HttpCors.generateHttpHeadersOverwriteParam","httpHeaders","hashIndex","questionIndex","goog.labs.net.webChannel.WebChannelBase","WebChannelBase.prototype.disconnect","cancelRequests_","rid","addAdditionalParams_","goog.global.navigator.sendBeacon","requestSent","goog.global.Image","Image","onClose_","WebChannelBase.prototype.cancelRequests_","clearDeadBackchannelTimer_","clearForwardChannelTimer_","WebChannelBase.prototype.sendMap","goog.labs.net.webChannel.Wire.QueuedMap","ensureForwardChannel_","WebChannelBase.prototype.ensureForwardChannel_","isFull","WebChannelBase.prototype.makeForwardChannelRequest_","opt_retryRequest","module$exports$goog$net$rpc$HttpCors.setHttpHeadersWithOverwriteParam","requeuePendingMaps_","dequeueOutgoingMaps_","goog.labs.net.webChannel.WebChannelBase.MAX_MAPS_PER_REQUEST_","requestText","WebChannelBase.prototype.addAdditionalParams_","WebChannelBase.prototype.dequeueOutgoingMaps_","maxNum","badMapHandler","outgoingMaps_","messageQueue","encodeMessage","pendingMessages","WebChannelBase.prototype.ensureBackChannel_","WebChannelBase.prototype.maybeRetryBackChannel_","goog.labs.net.webChannel.WebChannelBase.BACK_CHANNEL_MAX_RETRIES","getRetryTime_","WebChannelBase.prototype.testConnectionFinished","useChunked","applyClientProtocol","connectChannel_","WebChannelBase.prototype.clearDeadBackchannelTimer_","WebChannelBase.prototype.getRetryTime_","retryTime","goog.labs.net.webChannel.WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR","WebChannelBase.prototype.signalError_","imageUri","goog.global.location","goog.global.location.protocol","netUtils.testLoadImage","goog.labs.net.webChannel.netUtils.imageCallback_","goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT","ERROR_OTHER","CLOSED","onError_","WebChannelBase.prototype.onClose_","WebChannelBase.prototype.createDataUri","hostName","locationPage","opt_scheme","opt_port","getHttpSessionIdParam","getHttpSessionId","goog.labs.net.webChannel.WebChannelBaseTransport","goog.string.path.join","suffix","messageHeaders","goog.net.WebChannel.X_CLIENT_PROTOCOL","goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL","initHeaders","goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE","goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE","httpHeadersOverwriteParam","httpSessionIdParam","messageUrlParams_","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.Handler_","goog.net.WebChannel.MessageEvent.call","metadataKey","goog.net.WebChannel.ErrorEvent.call","NETWORK_ERROR","X","opt_failureCode","goog.net.XhrIo.prototype.getResponseJson","opt_xssiPrefix","goog.net.XhrIo.prototype.getLastErrorCode","goog.net.XhrIo.prototype.getLastError","Ad","goog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION","goog.labs.net.webChannel.WebChannelBase.prototype","WebChannelBase.prototype.isClosed","WebChannelBase.prototype.onStartForwardChannelTimer_","startForwardChannel_","total","goog.labs.net.webChannel.Wire.RAW_DATA_KEY","goog.labs.net.webChannel.WebChannelBase.MAX_CHARS_PER_GET_","goog.net.WebChannelTransport.CLIENT_VERSION","xmlHttpPost","OPENING","makeForwardChannelRequest_","WebChannelBase.prototype.onStartBackChannelTimer_","startBackChannel_","readyStateChangeThrottleMs_","WebChannelBase.prototype.onRequestData","hasRequest","handlePostResponse_","goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE","BACKCHANNEL_MISSING","responseValues","goog.labs.net.webChannel.WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF","getRequestCount","onForwardChannelFlushed_","BAD_RESPONSE","nextArray","onInput_","negotiatedVersion","serverKeepaliveMs","removeRequest","backChannelRequestTimeoutMs_","ensureBackChannel_","STOP","disconnect","WebChannelBase.prototype.onBackChannelDead_","maybeRetryBackChannel_","BACKCHANNEL_DEAD","WebChannelBase.prototype.onRequestComplete","BACK_CHANNEL","FORWARD_CHANNEL","rtt","lastError","WebChannelBase.prototype.maybeRetryForwardChannel_","getForwardChannelMaxRetries","maybeRetryForwardChannel_","forwardChannelRequestPool_","WebChannelBase.prototype.testNetworkCallback_","networkUp","ERROR_NETWORK","WebChannelBase.prototype.createXhrIo","WebChannelBase.prototype.isActive","WebChannelBase.prototype.shouldUseSecondaryDomains","Od","WebChannelBase.Handler.prototype.channelOpened","WebChannelBase.Handler.prototype.channelHandleArray","WebChannelBase.Handler.prototype.channelError","WebChannelBase.Handler.prototype.channelClosed","WebChannelBase.Handler.prototype.badMapError","WebChannelBaseTransport.prototype.createWebChannel","goog.labs.net.webChannel.WebChannelBaseTransport.Channel","Y","WebChannelBaseTransport.Channel.prototype.addEventListener","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.superClass_.addEventListener.call","WebChannelBaseTransport.Channel.prototype.removeEventListener","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.superClass_.removeEventListener.call","WebChannelBaseTransport.Channel.prototype.open","supportCrossDomain","testUrl_","url_","CONNECT_ATTEMPT","channelPath","opt_extraParams","connectTest_","testPath","urlPath","TEST_STAGE_ONE_START","handshakeResult","setParameterValues","sendDataUri","xmlHttpGet","WebChannelBaseTransport.Channel.prototype.close","WebChannelBaseTransport.Channel.prototype.send","rawJson","sendMap","WebChannelBaseTransport.Channel.prototype.disposeInternal","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.MessageEvent","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.ErrorEvent","goog.labs.net.webChannel.WebChannelBase.Handler","WebChannelBaseTransport.Channel.Handler_.prototype.channelOpened","WebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray","WebChannelBaseTransport.Channel.Handler_.prototype.channelError","WebChannelBaseTransport.Channel.Handler_.prototype.channelClosed","goog.net.createWebChannelTransport","goog.functions.create","Authorization","createWebChannelTransport","ErrorCode","EventType","WebChannel","XhrIo","__PRIVATE_otherUser","Code","CANCELLED","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","UNAUTHENTICATED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","UNAVAILABLE","DATA_LOSS","__PRIVATE_EmptyCredentialsProvider","__PRIVATE_changeListener","__PRIVATE_FirebaseCredentialsProvider","__PRIVATE_initialTokenCounter","__PRIVATE_tokenData","FirestoreError","__PRIVATE_currentUid","X-Goog-AuthUser","__PRIVATE_authHeader","__PRIVATE_FirstPartyCredentialsProvider","__PRIVATE_gapi","__PRIVATE_sessionIndex","__PRIVATE_authProvider","__PRIVATE_cls","__PRIVATE_optionalMessage","__PRIVATE_PublicConstructor","defaultValue","functionName","__PRIVATE_formatPlural","__PRIVATE_numberOfArgs","__PRIVATE_minNumberOfArgs","__PRIVATE_maxNumberOfArgs","__PRIVATE_argument","__PRIVATE_validateType","__PRIVATE_ordinal","__PRIVATE_validateArgType","__PRIVATE_optionName","__PRIVATE_validateNamedType","__PRIVATE_inputName","__PRIVATE_expectedDescription","expected_1","__PRIVATE_valueDescription","__PRIVATE_actualDescription","__PRIVATE_isPlainObject","__PRIVATE_customObjectName","__PRIVATE_optionNames","obj.forEach","__PRIVATE__","__PRIVATE_ByteString","__PRIVATE_PlatformSupport","__PRIVATE_binaryStringFromUint8Array","__PRIVATE_uint8ArrayFromBinaryString","__PRIVATE_binaryString","__PRIVATE_i","__PRIVATE_validateExactNumberOfArgs","__PRIVATE_assertBase64Available","__PRIVATE_assertUint8ArrayAvailable","__PRIVATE_invalidClassError","toBase64","__PRIVATE_primitiveComparator","__PRIVATE_PublicBlob","__PRIVATE_makeConstructorPrivate","GeoPoint","Timestamp","fromMillis","milliseconds","seconds","toMillis","nanoseconds","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_SnapshotVersion","isEqual","__PRIVATE_BasePath","__PRIVATE_nameOrPath","__PRIVATE_segment","__PRIVATE_potentialChild","end","p1","p2","ResourcePath","__PRIVATE_identifierRegExp","FieldPath","__PRIVATE_current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","collectionId","__PRIVATE_DocumentKey","k1","k2","__PRIVATE_LLRBNode","__PRIVATE_SortedMap","__PRIVATE_prunedNodes","__PRIVATE_descriptions","__PRIVATE_comparator","EMPTY","__PRIVATE_smallest","__PRIVATE_nl","__PRIVATE_nr","__PRIVATE_blackDepth","__PRIVATE_LLRBEmptyNode","__PRIVATE_startKey","__PRIVATE_isReverse","latitude","longitude","__PRIVATE_SortedSet","__PRIVATE_elem","range","__PRIVATE_iter","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","targetId","__PRIVATE_localWriteTime","__PRIVATE_transformResult","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_coercedFieldValuesArray","elements","ArrayValue","__PRIVATE_misc.__PRIVATE_arrayEquals","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_baseValue","__PRIVATE_sum","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","transformResults","__PRIVATE_fieldsAsSet","fieldPath","found","__PRIVATE_fieldMaskPath","__PRIVATE_FieldMask","FieldTransform","transform","Precondition","exists","updateTime","__PRIVATE_maybeDoc","Document","__PRIVATE_mutationResult","hasCommittedMutations","__PRIVATE_baseDoc","__PRIVATE_Mutation","rn","__PRIVATE_SetMutation","__PRIVATE_newData","__PRIVATE_PatchMutation","__PRIVATE_ObjectValue","__PRIVATE_builder","__PRIVATE_baseObject","fieldTransforms","__PRIVATE_existingValue","__PRIVATE_fieldTransform","__PRIVATE_coercedValue","__PRIVATE_TransformMutation","__PRIVATE_serverTransformResults","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","timestampsInSnapshots","serverTimestamps","FieldValue","__PRIVATE_NullValue","__PRIVATE_BooleanValue","__PRIVATE_NumberValue","__PRIVATE_internalValue","__PRIVATE_serverTimestampBehavior","__PRIVATE_precondition","__PRIVATE_fieldMask","__PRIVATE_IntegerValue","__PRIVATE_numericEquals","__PRIVATE_DoubleValue","NaN","__PRIVATE_StringValue","__PRIVATE_TimestampValue","toDate","__PRIVATE_ServerTimestampValue","__PRIVATE_BlobValue","__PRIVATE_RefValue","projectId","__PRIVATE_GeoPointValue","__PRIVATE_it1","__PRIVATE_it2","__PRIVATE_next1","__PRIVATE_next2","__PRIVATE_pathSegment","__PRIVATE_currentPath","__PRIVATE_nestedFields","__PRIVATE_nestedPath","__PRIVATE_ObjectValueBuilder","__PRIVATE_childName","minLength","__PRIVATE_totalSize","__PRIVATE_d1","__PRIVATE_d2","__PRIVATE_canonicalPath","__PRIVATE_fieldValue","__PRIVATE_protoValue","converter","result_1","mapValue","v1","v2","__PRIVATE_NoDocument","__PRIVATE_UnknownDocument","__PRIVATE_objectValue","__PRIVATE_databaseId","isNullOrUndefined","isSafeInteger","__PRIVATE_isNegativeZero","MIN_SAFE_INTEGER","Target","canonicalId","collectionGroup","filters","__PRIVATE_inequalityField","__PRIVATE_firstOrderByField","__PRIVATE_foundKeyOrdering","__PRIVATE_lastDirection","dir","__PRIVATE_Direction","ASCENDING","FieldFilter","__PRIVATE_newFilters","__PRIVATE_newOrderBy","bound","__PRIVATE_comparedOnKeyField","__PRIVATE_comp","__PRIVATE_operators","__PRIVATE_orderBys","DESCENDING","before","__PRIVATE_docPath","__PRIVATE_Operator","LESS_THAN","LESS_THAN_OR_EQUAL","EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","ARRAY_CONTAINS","IN","ARRAY_CONTAINS_ANY","__PRIVATE_comparison","__PRIVATE_KeyFieldFilter","__PRIVATE_refValue","__PRIVATE_KeyFieldInFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","arrayValue","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_lhsElem","__PRIVATE_Bound","__PRIVATE_orderByComponent","__PRIVATE_docValue","__PRIVATE_thisPosition","__PRIVATE_otherPosition","__PRIVATE_OrderBy","__PRIVATE_KEY_ORDERING_ASC","__PRIVATE_KEY_ORDERING_DESC","sequenceNumber","lastLimboFreeSnapshotVersion","resumeToken","__PRIVATE_snapshotVersion","__PRIVATE_TargetData","ExistenceFilter","__PRIVATE_purpose","__PRIVATE_explicitOrderBy","__PRIVATE_limitType","log.error","__PRIVATE_RpcCode","RpcCode","__PRIVATE_EMPTY_MAYBE_DOCUMENT_MAP","__PRIVATE_maybeDocumentMap","__PRIVATE_EMPTY_DOCUMENT_MAP","__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP","__PRIVATE_EMPTY_DOCUMENT_KEY_SET","keys_1","__PRIVATE_EMPTY_TARGET_ID_SET","__PRIVATE_updatedTargetIds","removedTargetIds","__PRIVATE_newDoc","__PRIVATE_existenceFilter","targetIds","cause","__PRIVATE_oldSet","__PRIVATE_DocumentSet","__PRIVATE_thisDoc","__PRIVATE_otherDoc","__PRIVATE_docStrings","__PRIVATE_keyedMap","__PRIVATE_sortedSet","__PRIVATE_newSet","__PRIVATE_DocumentChangeSet","__PRIVATE_change","__PRIVATE_oldChange","__PRIVATE_changes","documents","__PRIVATE_mutatedKeys","fromCache","__PRIVATE_ViewSnapshot","docs","docChanges","__PRIVATE_otherChanges","__PRIVATE_targetChanges","TargetChange","__PRIVATE_targetIdSet","__PRIVATE_documentKeySet","__PRIVATE_TargetState","__PRIVATE_addedDocuments","__PRIVATE_modifiedDocuments","__PRIVATE_removedDocuments","__PRIVATE_changeType","__PRIVATE_snapshotChangesMap","__PRIVATE_docChange","targetChange","__PRIVATE_targetState","removeTarget","__PRIVATE_objUtils.__PRIVATE_forEachNumber","__PRIVATE_watchChange","__PRIVATE_expectedCount","__PRIVATE_targetData","__PRIVATE_resolvedLimboDocuments","__PRIVATE_targets","__PRIVATE_isOnlyLimboTarget","__PRIVATE_remoteEvent","__PRIVATE_documentTargetMap","__PRIVATE_updatedDocument","__PRIVATE_WatchChangeAggregator","__PRIVATE_targetMapping","__PRIVATE_targetActive","__PRIVATE_metadataProvider","__PRIVATE_targetMismatches","__PRIVATE_documentUpdates","__PRIVATE_oldDocs","__PRIVATE_syncStateChanged","__PRIVATE_excludesMetadataChanges","__PRIVATE_documentMap","__PRIVATE_dirs","__PRIVATE_ops","__PRIVATE_DIRECTIONS","__PRIVATE_OPERATORS","__PRIVATE_ISO_REG_EXP","__PRIVATE_typeUtils.isNullOrUndefined","__PRIVATE_mapCodeFromRpcCode","nanos","__PRIVATE_parseInt64","__PRIVATE_utc","__PRIVATE_fraction","__PRIVATE_nanoStr","toUint8Array","fromBase64String","fromUint8Array","__PRIVATE_JsonProtoSerializer","resource","__PRIVATE_resourceName","__PRIVATE_fieldValue.__PRIVATE_NullValue","nullValue","__PRIVATE_fieldValue.__PRIVATE_BooleanValue","booleanValue","__PRIVATE_fieldValue.__PRIVATE_IntegerValue","integerValue","__PRIVATE_fieldValue.__PRIVATE_DoubleValue","doubleValue","__PRIVATE_typeUtils.__PRIVATE_isNegativeZero","__PRIVATE_fieldValue.__PRIVATE_StringValue","stringValue","__PRIVATE_fieldValue.__PRIVATE_ObjectValue","__PRIVATE_fieldValue.ArrayValue","__PRIVATE_fieldValue.__PRIVATE_TimestampValue","timestampValue","__PRIVATE_fieldValue.__PRIVATE_GeoPointValue","geoPointValue","__PRIVATE_fieldValue.__PRIVATE_BlobValue","bytesValue","__PRIVATE_fieldValue.__PRIVATE_RefValue","referenceValue","__PRIVATE_assertPresent","__PRIVATE_dbId","fromVersion","missing","readTime","documentChange","toVersion","documentDelete","documentRemove","__PRIVATE_mapRpcCodeFromCode","targetChangeType","__PRIVATE_causeProto","__PRIVATE_entityChange","__PRIVATE_docDelete","__PRIVATE_docRemove","__PRIVATE_mutation","updateMask","currentDocument","commitTime","__PRIVATE_protos","setToServerValue","appendMissingElements","removeAllFromArray","increment","__PRIVATE_fieldValue.__PRIVATE_NumberValue","__PRIVATE_documentsTarget","structuredQuery","allDescendants","__PRIVATE_fromCount","__PRIVATE_filterBy","goog-listen-tags","compositeFilter","unaryFilter","fieldFilter","__PRIVATE_accum","__PRIVATE_fieldReference","direction","__PRIVATE_nanField","__PRIVATE_nullField","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_logClient","__PRIVATE_FirebaseLogLevel","__PRIVATE_newLevel","__PRIVATE_failure","__PRIVATE_autoId","randomBytes","ssl","forceLongPolling","__PRIVATE_DatabaseId","__PRIVATE_docKey","__PRIVATE_batchResult","__PRIVATE_mutationResults","mutations","baseMutations","__PRIVATE_maybeDocs","__PRIVATE_mutatedDocuments","__PRIVATE_mutatedDocument","__PRIVATE_MutationBatch","batchId","__PRIVATE_MutationBatchResult","batch","__PRIVATE_commitVersion","streamToken","__PRIVATE_versionMap","__PRIVATE_documentVersionMap","__PRIVATE_ObjectMap","matches_1","__PRIVATE_otherKey","__PRIVATE_objUtil.forEach","entries_1","__PRIVATE_objUtil.__PRIVATE_isEmpty","__PRIVATE_viewSnapshot","__PRIVATE_addedKeys","__PRIVATE_removedKeys","__PRIVATE_externalPreviousValue","__PRIVATE_ListenSequence","__PRIVATE_nextValue","__PRIVATE_asyncQueue","__PRIVATE_timerId","__PRIVATE_delayMs","__PRIVATE_removalCallback","__PRIVATE_delayedOp","__PRIVATE_DelayedOperation","enqueue","__PRIVATE_AsyncQueue","__PRIVATE_newTail","__PRIVATE_removedOp","__PRIVATE_currentTail","__PRIVATE_lastTimerId","PersistencePromise","__PRIVATE_nextFn","__PRIVATE_catchFn","__PRIVATE_resolvedCount","__PRIVATE_predicates","__PRIVATE_isTrue","__PRIVATE_promises","__PRIVATE_targetTimeMs","__PRIVATE_sequenceNumberSyncer","__PRIVATE_mapKeyFn","__PRIVATE_docVersions","__PRIVATE_aSequence","__PRIVATE_aIndex","__PRIVATE_bSequence","__PRIVATE_bIndex","__PRIVATE_seqCmp","__PRIVATE_entry","__PRIVATE_highestValue","__PRIVATE_bufferEntryComparator","__PRIVATE_RollingSequenceNumberBuffer","__PRIVATE_GC_DID_NOT_RUN","Bu","Mu","Qu","Gu","__PRIVATE_cacheSize","__PRIVATE_LruParams","__PRIVATE_LruScheduler","__PRIVATE_localStore","log.debug","__PRIVATE_percentile","targetCount","maxValue","upperBound","activeTargetIds","__PRIVATE_upperBoundSequenceNumber","__PRIVATE_sequenceNumbersToCollect","__PRIVATE_targetsRemoved","__PRIVATE_countedTargetsTs","__PRIVATE_foundUpperBoundTs","__PRIVATE_removedTargetsTs","__PRIVATE_removedDocumentsTs","__PRIVATE_startTs","__PRIVATE_sequenceNumbers","__PRIVATE_numTargetsRemoved","__PRIVATE_documentsRemoved","log.__PRIVATE_getLogLevel","__PRIVATE_emptyKey","__PRIVATE_startRef","__PRIVATE_endRef","__PRIVATE_firstRef","__PRIVATE_RemoteDocumentChangeBuffer","__PRIVATE_maybeDocument","__PRIVATE_documentKey","__PRIVATE_bufferedEntry","__PRIVATE_documentKeys","__PRIVATE_LocalStore","__PRIVATE_newMutationQueue","__PRIVATE_newLocalDocuments","runTransaction","__PRIVATE_oldBatches","__PRIVATE_promisedOldBatches","__PRIVATE_newBatches","__PRIVATE_removedBatchIds","__PRIVATE_addedBatchIds","__PRIVATE_changedKeys","__PRIVATE_affectedDocuments","oo","ho","co","__PRIVATE_existingDocs","mutations_1","ks","__PRIVATE_affected","__PRIVATE_documentBuffer","mo","__PRIVATE_affectedKeys","__PRIVATE_remoteVersion","__PRIVATE_newTargetDataByTargetMap","__PRIVATE_oldTargetData","__PRIVATE_newTargetData","__PRIVATE_changedDocs","__PRIVATE_updatedKeys","getEntries","__PRIVATE_existingDoc","hasPendingWrites","__PRIVATE_updateRemoteVersion","lastRemoteSnapshotVersion","__PRIVATE_viewChanges","__PRIVATE_viewChange","__PRIVATE_updatedTargetData","__PRIVATE_afterBatchId","__PRIVATE_cached","__PRIVATE_keepPersistedTargetData","__PRIVATE_removed","__PRIVATE_usePreviousResults","__PRIVATE_remoteKeys","Yo","networkEnabled","__PRIVATE_docKeys","__PRIVATE_promiseChain","__PRIVATE_remoteDoc","__PRIVATE_ackVersion","__PRIVATE_garbageCollector","__PRIVATE_cachedTargetData","__PRIVATE_queryEngine","__PRIVATE_initialUser","__PRIVATE_targetOrBatchId","__PRIVATE_DocReference","__PRIVATE_delegate","__PRIVATE_cacheSizeCollectionThreshold","__PRIVATE_percentileToCollect","__PRIVATE_maximumSequenceNumbersToCollect","__PRIVATE_maxElements","createWebStorageClientStateKey","clientId","CLIENT_STATE_KEY_PREFIX","createWebStorageMutationBatchKey","__PRIVATE_mutationKey","MUTATION_BATCH_KEY_PREFIX","createWebStorageQueryTargetMetadataKey","QUERY_TARGET_KEY_PREFIX","__PRIVATE_mutationBatch","__PRIVATE_validData","__PRIVATE_firestoreError","__PRIVATE_batchMetadata","updateTimeMs","__PRIVATE_clientState","__PRIVATE_activeTargetIdsSet","onlineState","localStorage","__PRIVATE_WebStorageSharedClientState","__PRIVATE_existingClients","__PRIVATE_storageItem","__PRIVATE_RemoteClientState","__PRIVATE_onlineStateJSON","event_1","shutdown","__PRIVATE_activeTargets","__PRIVATE_objUtils.forEach","__PRIVATE_queryState","__PRIVATE_QueryTargetMetadata","removeEventListener","storageArea","__PRIVATE_mutationMetadata","__PRIVATE_queryTargetMetadata","__PRIVATE_seqString","__PRIVATE_parsed","__PRIVATE_mutationState","__PRIVATE_targetKey","__PRIVATE_targetMetadata","userId","__PRIVATE_MutationMetadata","__PRIVATE_SharedOnlineState","__PRIVATE_existingTargets","__PRIVATE_newTargets","__PRIVATE_addedTargets","__PRIVATE_removedTargets","__PRIVATE_queue","__PRIVATE_localClientId","__PRIVATE_escapedPersistenceKey","SEQUENCE_NUMBER_KEY_PREFIX","ONLINE_STATE_KEY_PREFIX","__PRIVATE_MemorySharedClientState","__PRIVATE_PRIMARY_LEASE_LOST_ERROR_MSG","__PRIVATE_batches","__PRIVATE_inBatches","__PRIVATE_nullableMaybeDocumentMap","__PRIVATE_localView","__PRIVATE_baseDocs","__PRIVATE_sinceReadTime","__PRIVATE_parents","__PRIVATE_collectionQuery","__PRIVATE_mutationBatches","__PRIVATE_queryResults","__PRIVATE_matchingMutationBatches","__PRIVATE_mergedDocuments","__PRIVATE_mutatedDoc","__PRIVATE_existingDocuments","__PRIVATE_missingBaseDocEntriesForPatching","__PRIVATE_missingBaseDocs","__PRIVATE_localDocuments","__PRIVATE_previousResults","__PRIVATE_getLogLevel","__PRIVATE_updatedResults","__PRIVATE_sortedPreviousResults","__PRIVATE_limboFreeSnapshotVersion","__PRIVATE_docAtLimitEdge","__PRIVATE_remoteDocumentCache","__PRIVATE_mutationQueue","__PRIVATE_indexManager","encode","__PRIVATE_encodeSeparator","__PRIVATE_encodeSegment","__PRIVATE_resultBuf","__PRIVATE_escapeChar","__PRIVATE_lastReasonableEscapeIndex","__PRIVATE_segmentBuilder","__PRIVATE_currentPiece","collectionPath","__PRIVATE_MemoryCollectionParentIndex","__PRIVATE_existingParents","__PRIVATE_added","__PRIVATE_batchIndex","__PRIVATE_check","lastStreamToken","__PRIVATE_nextBatchId","__PRIVATE_rawIndex","__PRIVATE_uniqueBatchIDs","__PRIVATE_immediateChildrenPathLength","__PRIVATE_startPath","__PRIVATE_rowKeyPath","__PRIVATE_batchIDs","__PRIVATE_references","__PRIVATE_referenceDelegate","__PRIVATE_previousSize","__PRIVATE_currentSize","Nc","__PRIVATE_MemoryRemoteDocumentCache","__PRIVATE_TargetIdGenerator","__PRIVATE_nextId","__PRIVATE_nextTargetId","after","highestTargetId","highestListenSequenceNumber","__PRIVATE_removals","__PRIVATE_matchingKeys","__PRIVATE_MEMORY_ONLY_PERSISTENCE_ERROR_MESSAGE","__PRIVATE_MemoryPersistence","__PRIVATE_primaryStateListener","__PRIVATE_transactionOperation","__PRIVATE_vs","__PRIVATE_inMemoryPins","__PRIVATE_MemoryEagerDelegate","__PRIVATE_changeBuffer","__PRIVATE_isReferenced","__PRIVATE_MemoryPersistenceProvider","__PRIVATE_databaseInfo","__PRIVATE_started","ss","__PRIVATE_ExponentialBackoff","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_delaySoFarMs","__PRIVATE_remainingDelayMs","__PRIVATE_PersistentStream","__PRIVATE_finalState","__PRIVATE_dispatchIfNotClosed","__PRIVATE_closeCount","__PRIVATE_rpcError","__PRIVATE_startCloseCount","connection","__PRIVATE_PersistentListenStream","__PRIVATE_watchChangeProto","serializer","addTarget","labels","__PRIVATE_PersistentWriteStream","__PRIVATE_responseProto","writeResults","__PRIVATE_Datastore","__PRIVATE_rpcName","__PRIVATE_InternalFieldPath","__PRIVATE_RESERVED","fieldNames","__PRIVATE_minNumberOfElements","__PRIVATE_validateNamedArrayAtLeastNumberOfElements","__PRIVATE_connectionTimerId","__PRIVATE_idleTimerId","__PRIVATE_credentialsProvider","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentSequenceNumber","__PRIVATE_referenceDelegateFactory","__PRIVATE_generatorId","seed","__PRIVATE_sizer","__PRIVATE_documentCache","__PRIVATE_FieldValueImpl","__PRIVATE_validateNoArgs","__PRIVATE_DeleteFieldValueImpl","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_validateAtLeastNumberOfArgs","__PRIVATE_PublicFieldValue","__PRIVATE_RESERVED_FIELD_REGEX","__PRIVATE__operand","__PRIVATE__elements","__PRIVATE__methodName","__PRIVATE_dataSource","__PRIVATE_childPath","__PRIVATE_fieldDescription","__PRIVATE_ParseContext","__PRIVATE_isWrite","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_validatedFieldPaths","fieldPaths_1","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_fieldMaskPaths","__PRIVATE_childContext","__PRIVATE_parsedValue","moreFieldsAndValues","__PRIVATE_fieldPathFromArgument","value_1","__PRIVATE_allowArrays","__PRIVATE_errorMessage","__PRIVATE_looksLikeJsonObject","__PRIVATE_isEmpty","__PRIVATE_entryIndex","array_1","__PRIVATE_parsedEntry","__PRIVATE_parsedElements","arrayUnion","arrayRemove","__PRIVATE_numericIncrement","__PRIVATE_typeUtils.isSafeInteger","fromDate","__PRIVATE_preConverter","__PRIVATE_arrayElement","Transaction","lookup","__PRIVATE_unwritten","__PRIVATE__version","commit","__PRIVATE_docVersion","__PRIVATE_existingVersion","__PRIVATE_OnlineStateTracker","__PRIVATE_newState","details","__PRIVATE_RemoteStore","enableNetwork","__PRIVATE_objUtils.contains","__PRIVATE_objUtils.__PRIVATE_isEmpty","watch","isPrimary","__PRIVATE_requestTargetData","__PRIVATE_lastBatchIdRetrieved","__PRIVATE_success","__PRIVATE_isPermanentError","__PRIVATE_previousChanges","__PRIVATE_changeSet","__PRIVATE_oldDocumentSet","__PRIVATE_newMutatedKeys","__PRIVATE_newDocumentSet","__PRIVATE_needsRefill","__PRIVATE_lastDocInLimit","__PRIVATE_firstDocInLimit","__PRIVATE_newMaybeDoc","__PRIVATE_oldDoc","__PRIVATE_oldDocHadPendingMutations","__PRIVATE_newDocHasPendingMutations","__PRIVATE_changeApplied","track","Vl","yc","yi","__PRIVATE_updateLimboDocuments","__PRIVATE_c1","__PRIVATE_c2","__PRIVATE_limboChanges","__PRIVATE_newSyncState","Ml","__PRIVATE_oldLimboDocuments","__PRIVATE_queryResult","__PRIVATE__syncedDocuments","__PRIVATE_datastore","__PRIVATE_onlineStateHandler","__PRIVATE_connectivityMonitor","Ma","Ga","Ya","Ja","__PRIVATE_TransactionRunner","__PRIVATE_userPromise","__PRIVATE_commitError","__PRIVATE_userPromiseError","updateFunction","__PRIVATE_SyncEngine","__PRIVATE_syncEngineListener","__PRIVATE_queryView","status_1","__PRIVATE_viewDocChanges","__PRIVATE_synthesizedTargetChange","__PRIVATE_queries","__PRIVATE_userCallback","__PRIVATE_deferred","__PRIVATE_limboResolution","__PRIVATE_ignoreIfPrimaryLeaseLoss","__PRIVATE_newViewSnapshots","__PRIVATE_limboKey","__PRIVATE_batchState","__PRIVATE_mutationBatchResult","__PRIVATE_highestBatchId","__PRIVATE_callbacks","__PRIVATE_newCallbacks","__PRIVATE_limboKeys","__PRIVATE_limboTargetId","__PRIVATE_limboChange","__PRIVATE_newSnaps","__PRIVATE_docChangesInAllViews","__PRIVATE_queriesProcessed","__PRIVATE_LocalViewChanges","__PRIVATE_fnName","__PRIVATE_userChanged","__PRIVATE_activeQueries","p_1","__PRIVATE_synthesizedRemoteEvent","__PRIVATE_RemoteEvent","disableNetwork","__PRIVATE_keySet","__PRIVATE_EventManager","__PRIVATE_firstListen","__PRIVATE_queryInfo","__PRIVATE_lastListen","__PRIVATE_viewSnaps","__PRIVATE_raisedEvent","__PRIVATE_viewSnap","__PRIVATE_snap","includeMetadataChanges","__PRIVATE_QueryListener","__PRIVATE_maybeOnline","__PRIVATE_hasPendingWritesChanged","__PRIVATE_FirestoreClient","__PRIVATE_persistenceProvider","__PRIVATE_persistenceSettings","__PRIVATE_initializationDone","__PRIVATE_persistenceResult","__PRIVATE_initialized","error_1","aa","DOMException","__PRIVATE_remoteStoreOnlineStateChangedHandler","__PRIVATE_sharedClientStateOnlineStateChangedHandler","terminate","__PRIVATE_AsyncObserver","muted","eventHandler","__PRIVATE_AutoId","__PRIVATE_queryObserver","__PRIVATE_syncEngine","__PRIVATE_remoteStore","__PRIVATE_sharedClientState","CACHE_SIZE_UNLIMITED","__PRIVATE_FirestoreSettings","cacheSizeBytes","Firestore","__PRIVATE_settingsLiteral","__PRIVATE_newSettings","__PRIVATE_client","getAuthHeaderValueForFirstParty","__PRIVATE_makeCredentialsProvider","synchronizeTabs","experimentalTabSynchronization","__PRIVATE_objUtils.__PRIVATE_defaulted","clearPersistence","e_1","_removeServiceInstance","waitForPendingWrites","__PRIVATE_isPartialObserver","__PRIVATE_asyncObserver","DocumentReference","__PRIVATE_thisDb","__PRIVATE_otherDb","firestore","CollectionReference","WriteBatch","log.setLogLevel","documentRef","__PRIVATE_validateReference","DocumentSnapshot","__PRIVATE_validateBetweenNumberOfArgs","__PRIVATE_validateSetOptions","__PRIVATE_convertedValue","mergeFields","__PRIVATE_fieldOrUpdateData","__PRIVATE_currArg","__PRIVATE_validateOptionNames","__PRIVATE_validateNamedOptionalType","__PRIVATE_internalOptions","__PRIVATE_validateOptionalArgType","__PRIVATE_errHandler","__PRIVATE_internalListener","__PRIVATE_InternalQuery","__PRIVATE_validateGetOptions","__PRIVATE_unlisten","Wd","SnapshotMetadata","__PRIVATE_validateSnapshotOptions","QueryDocumentSnapshot","fromFirestore","__PRIVATE_FieldValueOptions","opStr","__PRIVATE_validateDefined","__PRIVATE_enums","__PRIVATE_validateStringEnum","operator","__PRIVATE_referenceList","directionStr","__PRIVATE_validatePositiveNumber","__PRIVATE_docOrField","Fv","__PRIVATE_allFields","__PRIVATE_rawValue","__PRIVATE_wrapped","QuerySnapshot","__PRIVATE_firestoreClient","__PRIVATE_documentIdValue","__PRIVATE_arrayOps","__PRIVATE_disjunctiveOps","__PRIVATE_isArrayOp","__PRIVATE_isDisjunctiveOp","__PRIVATE_existingField","__PRIVATE_conflictingOp","__PRIVATE_inequality","__PRIVATE_lastDoc","index_1","oldIndex","__PRIVATE_indexTracker","__PRIVATE_resultChangeType","__PRIVATE__firestore","__PRIVATE__originalQuery","__PRIVATE__snapshot","__PRIVATE__converter","__PRIVATE__query","__PRIVATE__key","__PRIVATE__document","__PRIVATE__fromCache","__PRIVATE__hasPendingWrites","__PRIVATE__transaction","__PRIVATE_databaseIdOrApp","external_1","experimentalForceLongPolling","toFirestore","__PRIVATE_docRef","__PRIVATE__path","__PRIVATE_typeDescription","__PRIVATE_validator","__PRIVATE_validateOptionalArrayElements","__PRIVATE_validateNamedOptionalPropertyEquals","__PRIVATE_PublicFirestore","__PRIVATE_PublicTransaction","__PRIVATE_PublicWriteBatch","__PRIVATE_PublicDocumentReference","__PRIVATE_PublicDocumentSnapshot","__PRIVATE_PublicQueryDocumentSnapshot","__PRIVATE_PublicQuery","__PRIVATE_PublicQuerySnapshot","__PRIVATE_PublicCollectionReference","__PRIVATE_schemaConverter","__PRIVATE_SimpleDb","indexedDB","onsuccess","onblocked","onupgradeneeded","oldVersion","createOrUpgrade","SCHEMA_VERSION","__PRIVATE_wrapRequest","deleteDatabase","__PRIVATE_ua","__PRIVATE_iOSVersion","__PRIVATE_isUnsupportedIOS","__PRIVATE_androidVersion","__PRIVATE_isUnsupportedAndroid","__PRIVATE_iOSVersionRegex","__PRIVATE_androidVersionRegex","__PRIVATE_versionChangeListener","onversionchange","__PRIVATE_objectStores","__PRIVATE_transactionFn","__PRIVATE_readonly","__PRIVATE_attemptNumber","__PRIVATE_SimpleDbTransaction","__PRIVATE_transactionFnResult","abort","__PRIVATE_retryable","__PRIVATE_IterationController","objectStoreNames","aborted","__PRIVATE_storeName","__PRIVATE_SimpleDbStore","__PRIVATE_keyOrValue","__PRIVATE_indexOrRange","control","__PRIVATE_optionsOrCallback","__PRIVATE_cursorRequest","__PRIVATE_checkForAndReportiOSError","primaryKey","__PRIVATE_shouldContinue","continue","controller","__PRIVATE_userResult","__PRIVATE_indexName","openKeyCursor","openCursor","oncomplete","onabort","__PRIVATE_dbCursor","__PRIVATE_reportedIOSError","__PRIVATE_IOS_ERROR","__PRIVATE_newError","IDBKeyRange","__PRIVATE_mutationsStore","DbMutationBatch","userMutationsIndex","__PRIVATE_mutationQueuesStore","__PRIVATE_documentStore","__PRIVATE_documentMutationsStore","__PRIVATE_mutationStore","__PRIVATE_dbBatch","__PRIVATE_collectionParents","__PRIVATE_l","__PRIVATE_indexKey","DbDocumentMutation","PLACEHOLDER","lowerBound","__PRIVATE_foundBatch","__PRIVATE_dbBatches","__PRIVATE_indexPrefix","prefixForPath","__PRIVATE_indexStart","__PRIVATE_userID","__PRIVATE_encodedPath","EncodedResourcePath.decode","__PRIVATE_batchID","__PRIVATE_queryPath","__PRIVATE_immediateChildrenLength","__PRIVATE_removeMutationBatch","__PRIVATE_startRange","prefixForUser","__PRIVATE_danglingMutationReferences","__PRIVATE_mutationQueueContainsKey","DbMutationQueue","__PRIVATE_containsKey","__PRIVATE_indexTxn","only","__PRIVATE_numDeleted","__PRIVATE_removePromise","__PRIVATE_IndexedDbPersistence","__PRIVATE_getHighestListenSequenceNumber","__PRIVATE_targetsStore","__PRIVATE_retrieveMetadata","DbTargetGlobal","updated","DbTarget","queryTargetsIndexName","__PRIVATE_documentTargetStore","EncodedResourcePath.encode","DbTargetDocument","__PRIVATE_immediateSuccessor","documentTargetsIndex","__PRIVATE_targetGlobal","__PRIVATE_remoteDocumentsStore","__PRIVATE_dbKey","__PRIVATE_IndexedDbRemoteDocumentCache","__PRIVATE_sizeDelta","getMetadata","byteSize","__PRIVATE_dbRemoteDoc","__PRIVATE_dbDocumentSize","__PRIVATE_sizeMap","Lw","qw","__PRIVATE_keyIter","__PRIVATE_nextKey","__PRIVATE_potentialKeyRaw","__PRIVATE_potentialKey","__PRIVATE_iterationOptions","__PRIVATE_collectionKey","__PRIVATE_readTimeKey","DbRemoteDocument","collectionReadTimeIndex","__PRIVATE_lastReadTime","__PRIVATE_documentsStore","readTimeIndex","rh","__PRIVATE_documentGlobalStore","DbRemoteDocumentGlobal","__PRIVATE_deletedDoc","updateMetadata","__PRIVATE_getResult","__PRIVATE_maybeDocuments","__PRIVATE_trackRemovals","unknownDocument","noDocument","SchemaConverter","__PRIVATE_simpleDbTransaction","createObjectStore","DbPrimaryClient","autoIncrement","createIndex","userMutationsKeyPath","unique","__PRIVATE_createQueryCache","deleteObjectStore","__PRIVATE_globalStore","__PRIVATE_existingMutations","__PRIVATE_v3MutationsStore","__PRIVATE_writeAll","DbClientMetadata","removeAcknowledgedMutations","addDocumentGlobal","ensureSequenceNumbers","createCollectionParentIndex","__PRIVATE_remoteDocumentStore","readTimeIndexPath","collectionReadTimeIndexPath","__PRIVATE_byteCount","__PRIVATE_queuesStore","__PRIVATE_queues","lastAcknowledgedBatchId","__PRIVATE_docSentinelKey","__PRIVATE_maybeSentinel","__PRIVATE_addEntry","__PRIVATE_collectionParentsStore","DbCollectionParent","pathSegments","ownerId","allowTabSynchronization","leaseTimestampMs","localWriteTimeMs","lastListenSequenceNumber","documentTargetsKeyPath","queryTargetsKeyPath","inForeground","ALL_STORES","__PRIVATE_collectionParent","__PRIVATE_parentPaths","__PRIVATE_dbReadTime","readTime_1","DbNoDocument","readTime_2","DbUnknownDocument","__PRIVATE_dbTimestampKey","DbTimestamp","__PRIVATE_dbTimestamp","__PRIVATE_serializedBaseMutations","__PRIVATE_serializedMutations","__PRIVATE_encodedKeys","__PRIVATE_encodedPaths","__PRIVATE_dbTarget","__PRIVATE_queryProto","__PRIVATE_dbLastLimboFreeTimestamp","__PRIVATE_remoteSerializer","__PRIVATE_PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","__PRIVATE_primaryState","__PRIVATE_databaseDeletedListener","newVersion","__PRIVATE_clientMetadataStore","__PRIVATE_canActAsPrimary","__PRIVATE_primaryClientStore","__PRIVATE_primaryClient","__PRIVATE_metadataStore","active","__PRIVATE_inactive","__PRIVATE_inactiveClient","__PRIVATE_currentPrimary","__PRIVATE_otherClient","__PRIVATE_otherClientHasBetterNetworkState","__PRIVATE_otherClientHasBetterVisibility","__PRIVATE_otherClientHasSameNetworkState","__PRIVATE_clients","__PRIVATE_activityThresholdMs","__PRIVATE_clientMetadata","__PRIVATE_dbName","__PRIVATE_IndexedDbMutationQueue","__PRIVATE_persistenceTransaction","__PRIVATE_simpleDbMode","__PRIVATE_simpleDbTxn","__PRIVATE_holdsPrimaryLease","__PRIVATE_newPrimary","__PRIVATE_maxAgeMs","visibilityState","__PRIVATE_isZombied","__PRIVATE_ZOMBIED_CLIENTS_KEY_PREFIX","__PRIVATE_lruParams","LocalSerializer","__PRIVATE_docCountPromise","__PRIVATE_docCount","__PRIVATE_orphanedCount","__PRIVATE_writeSentinelKey","__PRIVATE_documentCount","__PRIVATE_isPinned","__PRIVATE_IndexedDbLruDelegate","__PRIVATE_nextPath","__PRIVATE_nextToReport","__PRIVATE_IndexedDbPersistenceProvider","fh","hm","$w","__PRIVATE_firestoreNamespace","__PRIVATE_firestoreFactory","__PRIVATE_NoopConnectivityMonitor","__PRIVATE_BrowserConnectivityMonitor","__PRIVATE_StreamBridge","__PRIVATE_RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","__PRIVATE_X_GOOG_API_CLIENT_VALUE","__PRIVATE_xhr","getLastErrorCode","getResponseJson","__PRIVATE_responseError","__PRIVATE_firestoreErrorCode","__PRIVATE_serverError","getLastError","__PRIVATE_jsonObj","__PRIVATE_requestString","__PRIVATE_urlParts","__PRIVATE_webchannelTransport","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","isIE","runtime","chrome","browser","isBrowserExtension","__PRIVATE_unguardedEventListen","createWebChannel","__PRIVATE_opened","closed","__PRIVATE_streamBridge","qm","Bm","__PRIVATE_msgData","__PRIVATE_msgDataOrError","status_2","__PRIVATE_urlRpcName","__PRIVATE_BrowserPlatform","__PRIVATE_encoded","__PRIVATE_nBytes","crypto","getRandomValues","errorCodeMap","HttpsErrorImpl","_errorForResponse","bodyJSON","codeForHTTPStatus","errorJSON","ContextProvider","messaging","Notification","permission","getAuthToken","getInstanceIdToken","instanceIdToken","messagingProvider","Serializer","Service","region","region_","emulatorOrigin","_url","contextProvider","postJSON","millis","failAfter","cancelAllRequests","responseData","deleteService","namespaceExports","promisifyRequest","promisifyRequestCall","proxyProperties","ProxyClass","targetProp","proxyRequestMethods","proxyMethods","proxyCursorRequestMethods","Cursor","promisifyCursorRequestCall","_index","_cursor","_request","ObjectStore","_store","idbTransaction","_tx","UpgradeDB","_db","DB","openDb","upgradeCallback","deleteDb","Functions","IDBIndex","IDBCursor","IDBObjectStore","IDBTransaction","IDBDatabase","funcName","toArray","nativeObject","getAll","iterateCursor","PENDING_TIMEOUT_MS","PACKAGE_VERSION","INTERNAL_AUTH_VERSION","INSTALLATIONS_API_URL","TOKEN_EXPIRATION_BUFFER","ERROR_DESCRIPTION_MAP","isServerError","getInstallationsEndpoint","extractAuthTokenInfoFromResponse","requestStatus","expiresIn","responseExpiresIn","getExpiresInFromResponseExpiresIn","getErrorFromResponse","requestName","responseJson","errorData","serverCode","serverMessage","serverStatus","getHeaders","Accept","x-goog-api-key","getHeadersWithAuth","appConfig","getAuthorizationHeader","retryIfServerError","sleep","VALID_FID_PATTERN","INVALID_FID","generateFid","fidByteArray","msCrypto","fid","bufferToBase64UrlSafe","fidChangeCallbacks","fidChanged","callFidChangeCallbacks","getBroadcastChannel","closeBroadcastChannel","broadcastFidChange","callbacks_1","broadcastChannel","BroadcastChannel","DATABASE_NAME","DATABASE_VERSION","OBJECT_STORE_NAME","dbPromise","getDbPromise","upgradeDB","getInstallationEntry","oldEntry","installationEntry","clearTimedOutRequest","registrationStatus","updateOrCreateInstallationEntry","entryWithPromise","registrationPromise","updateInstallationRequest","waitUntilFidRegistration","onLine","registrationPromiseWithError","inProgressEntry","registrationTime","authVersion","responseValue","createInstallationRequest","registeredInstallationEntry","registerInstallation","triggerRegistrationIfNecessary","hasInstallationRequestTimedOut","generateAuthTokenRequest","platformLoggerProvider","getGenerateAuthTokenEndpoint","platformLogger","getPlatformInfoString","installation","dependencies","isEntryRegistered","oldAuthToken","isAuthTokenExpired","isAuthTokenValid","tokenPromise","updateAuthTokenRequest","waitUntilAuthTokenRequest","inProgressAuthToken","requestTime","makeAuthTokenRequestInProgressEntry","updatedInstallationEntry","fetchAuthTokenFromServer","hasAuthTokenRequestTimedOut","completeInstallationRegistration","deleteInstallationRequest","getDeleteEndpoint","onIdChange","callbackSet","addCallback","removeCallback","getMissingValueError","valueName","configKeys_1","extractAppConfig","getId","deleteInstallation","ERROR_MAP","arrayToBase64","uint8Array","OLD_DB_NAME","OLD_DB_VERSION","OLD_OBJECT_STORE_NAME","migrateOldDatabase","senderId","databases","tokenDetails","oldDetails","p256dh","fcmToken","createTime","subscriptionOptions","swScope","vapidKey","checkTokenDetails","upgradeDb","dbGet","firebaseDependencies","oldTokenDetails","dbSet","DEFAULT_VAPID_KEY","ENDPOINT","FCM_MSG","CONSOLE_CAMPAIGN_ID","requestDeleteToken","unsubscribeOptions","getEndpoint","errorInfo","err_3","installations","x-goog-firebase-installations-auth","getBody","web","applicationPubKey","MessageType","swRegistration","pushManager","getSubscription","subscription","userVisibleOnly","applicationServerKey","getPushSubscription","pushSubscription","getNewToken","dbOptions","currentOptions","isVapidKeyEqual","isEndpointEqual","isAuthEqual","isP256dhEqual","isTokenValid","updateOptions","err_2","requestUpdateToken","updatedToken","updatedTokenDetails","deleteToken","e_2","updateToken","dbRemove","subscribeOptions","err_1","requestGetToken","isConsoleMessage","WindowController","getServiceWorkerRegistration","requestPermission","permissionResult","ServiceWorkerRegistration","onMessageCallback","serviceWorker","register","browserErrorMessage","firebaseMessaging","PUSH_RECEIVED","logEvent","messageType","NOTIFICATION_CLICKED","analyticsProvider","message_id","message_name","message_time","message_device_time","messageEventListener","SwController","bgMessageHandler","getMessagePayload","getClientList","clientList","client","hasVisibleClients","createNewMessage","clientList_2","sendMessageToWindowClients","notificationDetails","notification","notificationInformation","getNotificationData","title","actions","maxActions","showNotification","stopImmediatePropagation","fcmOptions","click_action","getLink","clientList_1","getWindowClient","clients","openWindow","focus","waitUntil","onPush","onSubChange","onNotificationClick","matchAll","includeUncontrolled","NAMESPACE_EXPORTS","PushSubscription","cookieEnabled","messagingSenderId","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","FirebaseStorageError","prependCode","codeProp","serverResponse_","code_","message_","OBJECT_NOT_FOUND","BUCKET_NOT_FOUND","PROJECT_NOT_FOUND","UNAUTHORIZED","RETRY_LIMIT_EXCEEDED","INVALID_CHECKSUM","CANCELED","INVALID_EVENT_NAME","INVALID_URL","INVALID_DEFAULT_BUCKET","NO_DEFAULT_BUCKET","CANNOT_SLICE_BLOB","SERVER_FILE_WRONG_SIZE","NO_DOWNLOAD_URL","INVALID_ARGUMENT_COUNT","APP_DELETED","INVALID_ROOT_OPERATION","INVALID_FORMAT","unknown","canceled","cannotSliceBlob","invalidArgument","appDeleted","invalidFormat","internalError","StringFormat","RAW","BASE64","BASE64URL","DATA_URL","formatValidator","stringFormat","contentType","dataFromString","stringData","StringData","utf8Bytes_","base64Bytes_","dataUrl","DataURLParts","rest","decoded","errorsExports.invalidFormat","percentEncodedBytes_","dataURLBytes_","dataURLContentType_","errorsExports.unknown","hasMinus","hasUnder","hasPlus","hasSlash","endsWith","TaskEvent","STATE_CHANGED","InternalTaskState","TaskState","RUNNING","PAUSED","taskStateFromInternalTaskState","isDef","isJustDef","isString","isNumber","isNativeBlob","isNativeBlobDefined","NetworkXhrIo","sent_","errorsExports.internalError","xhr_","type.isDef","sendPromise_","errorCode_","getResponseHeader","upload","XhrIoPool","getBlob","BlobBuilder","WebKitBlobBuilder","bb","type.isNativeBlobDefined","FbsBlob","size_","type_","startByte","endByte","type.isNativeBlob","data_","sliced","webkitSlice","mozSlice","fs.sliceBlob","blobby","fs.getBlob","uint8Arrays","type.isString","finalLength_1","merged_1","elideCopy","blobType","Location","bucket","bucketString","bucketLocation","makeFromUrl","errorsExports.invalidDefaultBucket","bucketDomain","gsRegex","hostRegex","groups","regex","indices","postModify","loc","group","captures","bucketValue","pathValue","errorsExports.invalidUrl","jsonObjectOrNull","type.isNonArrayObject","lastComponent","lastIndexOf","makeUrl","urlPart","makeQueryString","queryPart","noXform_","server","local","xform","mappings_","getMappings","mappings","Mapping","nameMapping","_metadata","fullPath","path.lastComponent","xformPath","sizeMapping","addRef","authWrapper","makeStorageReference","fromResourceString","resourceString","json.jsonObjectOrNull","fromResource","toResourceString","metadataValidator","type.isObject","MAX_RESULTS_KEY","MAX_MAX_RESULTS","PAGE_TOKEN_KEY","PREFIXES_KEY","ITEMS_KEY","fromBackendResponse","listResult","prefixes","nextPageToken","pathWithoutTrailingSlash","reference","listOptionsValidator","handlerCheck","cndn","metadataHandler","MetadataUtils.fromResourceString","listHandler","ListResultUtils.fromResponseString","downloadUrlHandler","tokens","UrlUtils.makeUrl","UrlUtils.makeQueryString","alt","MetadataUtils.downloadUrlFromResourceString","sharedErrorHandler","newErr","quotaExceeded","unauthorized","setServerResponseProp","serverResponseProp","objectErrorHandler","objectNotFound","fullServerUrl","maxOperationRetryTime","requestInfo","RequestInfo","errorHandler","metadataForUpload_","metadataClone","determineContentType_","multipartUpload","bucketOnlyServerUrl","X-Goog-Upload-Protocol","boundary","genBoundary","metadata_","preBlobPart","MetadataUtils.toResourceString","postBlobPart","maxUploadRetryTime","uploadData","current","checkResumeHeader_","allowed","createResumableUpload","metadataForUpload","X-Goog-Upload-Command","X-Goog-Upload-Header-Content-Length","X-Goog-Upload-Header-Content-Type","getResumableUploadStatus","sizeString","ResumableUploadStatus","continueResumableUpload","progressCallback","status_","bytesLeft","bytesToUpload","X-Goog-Upload-Offset","uploadStatus","newCurrent","type.isFunction","bytesTransferred","totalBytes","validate","specs","passed","minArgs","maxArgs","argMin","argMax","countPart","plural","errorsExports.invalidArgumentCount","errorsExports.invalidArgument","type.isJustDef","stringSpec","stringValidator","chainedValidator","and_","ArgSpec","uploadDataSpec","metadataSpec","MetadataUtils.metadataValidator","nonNegativeNumberSpec","type.isNumber","looseObjectSpec","nullFunctionSpec","argsToForward","UploadTask","sizeBefore","transferred_","loaded","updateProgress_","request_","resumable_","uploadUrl_","createResumable_","needToFetchStatus_","fetchStatus_","needToFetchMetadata_","fetchMetadata_","continueUpload_","oneShotUpload_","authWrapper_","transition_","resolveToken_","fbsRequests.createResumableUpload","location_","blob_","createRequest","makeRequest","getPromise","completeTransitions_","errorHandler_","fbsRequests.getResumableUploadStatus","statusRequest","chunkMultiplier_","fbsRequests.ResumableUploadStatus","fbsRequests.continueResumableUpload","makeProgressCallback_","uploadRequest","newStatus","increaseMultiplier_","fbsRequests.getMetadata","metadataRequest","metadataErrorHandler_","fbsRequests.multipartUpload","multipartRequest","transferred","old","notifyObservers_","wasPaused","externalState","UploadTaskSnapshot","completed","nextOrObserverMessage","nextValidator","observerValidator","nextOrObserverValidator","typeUtils.isJustDef","makeBinder","Observer","addObserver_","removeObserver_","binderSpecs","promise_","observers_","notifyObserver_","finishPromise_","triggered","fbsAsync","reject_","valid","shouldDoResumable_","codeEquals","metadata.getMappings","newPath","canonicalChildPath","path.child","newRef","path.parent","throwIfRoot_","_xhr","_text","successCodes","requests.deleteObject","listAllHelper","pageToken","opt","list","nextPage","ListOptionsUtils.listOptionsValidator","listOptionSpec","delimiter","maxResults","isRoot","requests.list","requests.getMetadata","requests.updateMetadata","requests.getDownloadUrl","errorsExports.invalidRootOperation","FailRequest","_appDelete","RequestMap","AuthWrapper","constants.CONFIG_STORAGE_BUCKET_KEY","makeFromBucketSpec","deleted_","errorsExports.appDeleted","bucket_","service_","storageRefMaker_","requestMaker_","appId_","pool_","requestMap_","maxUploadRetryTime_","maxOperationRetryTime_","maker","requestMaker","pool","extractBucket_","NetworkRequest","backoffDone","requestWentThrough","wasSuccessCode","errorCallback_","appDelete_","canceled_","RequestEndStatus","backoffId_","waitSeconds","hitTimeout","cancelState","triggeredCallback","triggerCallback","callWithDelay","wasTimeout","backoff.start","backoffCallback","createXhrIo","pendingXhr_","progressCallback_","addUploadProgressListener","progressListener","method_","body_","headers_","removeUploadProgressListener","hitServer","getErrorCode","isRetryStatusCode_","successCode","successCodes_","wasCanceled","progressEvent","lengthComputable","appDelete","backoff.stop","isFiveHundredCode","isExtraRetryCode","isRequestSpecificRetryCode","additionalRetryCodes_","additionalRetryCodes","errorCallback","addGmpidHeader_","addAuthHeader_","addVersionHeader_","args.validate","args.stringSpec","args.nonNegativeNumberSpec","setMaxUploadRetryTime","setMaxOperationRetryTime","internals_","RequestExports.makeRequest","authWrapperBucket","ServiceInternals","deleteApp","Storage","apiInstance","windowInstance","settingsServiceInstance","TRACE_MEASURE_PREFIX","CONFIG_LOCAL_STORAGE_KEY","CONFIG_EXPIRY_LOCAL_STORAGE_KEY","SERVICE_NAME","Api","windowLocation","performance","mark","measureName","mark1","mark2","measure","getEntriesByType","getEntriesByName","timeOrigin","timing","navigationStart","entryType","PerformanceObserver","entryTypes","perfMetrics","onFirstInputDelay","iid","VisibilityState","SettingsService","firebaseAppInstance","getIid","RESERVED_ATTRIBUTE_PREFIXES","ATTRIBUTE_FORMAT_REGEX","getVisibilityState","VISIBLE","consoleLogger","REMOTE_CONFIG_SDK_VERSION","SECONDARY_CONFIGS","loggingEnabled","FIS_AUTH_PREFIX","getConfig","expiryString","expiry","configValid","configStringified","getStoredConfig","processConfig","authTokenPromise","installationsService","authTokenVal","getAuthTokenPromise","configEndPoint","getProjectId","app_instance_id","app_instance_id_token","app_id","getAppId","app_version","sdk_version","COULD_NOT_GET_CONFIG_MSG","getRemoteConfig","configTimeToLive","storeConfig","fpr_enabled","fpr_log_source","logSource","fpr_log_endpoint_url","logEndPointUrl","fpr_vc_network_request_sampling_rate","networkRequestsSamplingRate","fpr_vc_trace_sampling_rate","tracesSamplingRate","logTraceAfterSampling","shouldLogAfterSampling","logNetworkAfterSampling","samplingRate","initializationPromise","initializationStatus","getInitializationPromise","handler_1","getDocumentReadyComplete","iidPromise","iidVal","getIidPromise","changeInitializationStatus","DEFAULT_SEND_INTERVAL_MS","INITIAL_SEND_TIME_DELAY_MS","DEFAULT_REMAINING_TRIES","remainingTries","isTransportSetup","setupTransportService","processQueue","timeOffset","staged","log_event","source_extension_json_proto3","event_time_ms","eventTime","request_time_ms","client_info","client_type","js_client_info","log_source","wait","next_request_wait_millis","requestOffset","transportHandler","addToQueue","sendLog","resourceType","logTrace","trace","settingsService","instrumentationEnabled","isAuto","dataCollectionEnabled","requiredApisAvailable","sendTraceLog","networkRequest","networkRequestMetric","http_method","http_response_code","response_payload_bytes","responsePayloadBytes","client_start_time_us","startTimeUs","time_to_response_initiated_us","timeToResponseInitiatedUs","time_to_response_completed_us","timeToResponseCompletedUs","perfMetric","application_info","getApplicationInfo","network_request_metric","serializeNetworkRequest","traceMetric","is_auto","duration_us","durationUs","counters","customAttributes","getAttributes","custom_attributes","trace_metric","serializeTrace","google_app_id","web_app_info","page_url","getUrl","service_worker_status","getServiceWorkerStatus","visibility_state","effective_connection_type","navigatorConnection","effectiveType","getEffectiveConnectionType","application_process_state","oobMetrics","Trace","traceName","api","traceStartMark","traceStopMark","traceMeasure","calculateTraceMetrics","startTime","duration","metrics","putMetric","isValidMetricName","customMetricName","attr","isValidName","isValidCustomAttributeName","isValidValue","isValidCustomAttributeValue","attributeName","attributeValue","perfMeasureEntries","perfMeasureEntry","getTimeOrigin","navigationTimings","paintTimings","firstInputDelay","route","timeOriginUs","setStartTime","setDuration","domInteractive","domContentLoadedEventEnd","loadEventEnd","firstPaint","paintObject","firstContentfulPaint","traceMeasureName","TRACE_START_MARK_PREFIX","TRACE_STOP_MARK_PREFIX","createNetworkRequestEntry","performanceEntry","responseStart","responseEnd","logNetworkRequest","transferSize","FID_WAIT_TIME_MS","setupOobResources","timeoutId_1","createOobTrace","setupOobTraces","resources","resources_1","setupObserver","setupNetworkRequests","measures","measures_1","createUserTimingTrace","setupUserTimingTraces","PerformanceController","factoryMethod","setupApi","GtagCommand","EventName","ANALYTICS_ID_FIELD","GA_FID_KEY","ORIGIN_KEY","GTAG_URL","wrapOrCreateGtag","initializedIdPromisesMap","dataLayerName","gtagFunctionName","gtagCore","_args","idOrNameOrParams","gtagParams","EVENT","initializationPromisesToWaitFor","gaSendToList","gaSendToList_1","sendToId","idPromise","CONFIG","SET","wrapGtag","wrappedGtag","gtagCoreFunction","wrappedGtagFunction","gtagName","globalInitDone","analyticsId","scriptTags","getElementsByTagName","findGtagScriptOnPage","insertScriptTag","dataLayer","getOrCreateDataLayer","initializeGAId","eventName","eventParams","gtagFunction","send_to","setCurrentScreen","screenName","screen_name","setUserId","user_id","setUserProperties","flatProperties","user_properties","setAnalyticsCollectionEnabled","enabled","ANALYTICS_TYPE","CachingClient","cacheMaxAgeMillis","lastSuccessfulFetchTimestampMillis","cacheAgeMillis","isCachedDataFresh","getLastSuccessfulFetchTimestampMillis","getLastSuccessfulFetchResponse","lastSuccessfulFetchResponse","eTag","storageOperations","storageCache","setLastSuccessfulFetchTimestampMillis","setLastSuccessfulFetchResponse","RestClient","firebaseInstallations","installationId","installationToken","urlBase","FIREBASE_REMOTE_CONFIG_URL_BASE","Content-Encoding","If-None-Match","requestBody","language_code","navigatorLanguage","languages","language","getUserLanguage","fetchPromise","timeoutPromise","_resolve","signal","originalError_1","originalErrorMessage","responseEtag","responseBody","originalError_2","httpStatus","RemoteConfigAbortSignal","BOOLEAN_TRUTHY_VALUES","Value","_value","_source","RemoteConfig","_logger","FirebaseLogLevel","_storageCache","getLastFetchStatus","_storage","getActiveConfigEtag","activeConfigEtag","setActiveConfig","setActiveConfigEtag","_initializePromise","loadFromStorage","_isInitializationComplete","abortSignal","fetchTimeoutMillis","_client","minimumFetchIntervalMillis","setLastFetchStatus","lastFetchStatus","hasErrorCode","activate","obj1","obj2","getAllKeys","getActiveConfig","defaultConfig","allConfigs","asBoolean","asNumber","asString","activeConfig","toFirebaseError","originalError","APP_NAMESPACE_STORE","DB_NAME","DB_VERSION","etag","openDbPromise","compositeKey","createCompositeKey","StorageCache","lastFetchStatusPromise","lastSuccessfulFetchTimestampMillisPromise","activeConfigPromise","timestampMillis","RetryingClient","getThrottleMetadata","throttleMetadata","backoffCount","throttleEndTimeMillis","attemptFetch","backoffMillis","setAbortableTimeout","deleteThrottleMetadata","isRetriableError","currBaseValue","randomWait","calculateBackoffMillis","setThrottleMetadata","firebaseInstance","packageName","restClient","retryingClient","cachingClient","remoteConfigInstance","ensureInitialized"],"mappings":"+LAAA,SAAUA,GAGR,IAAIA,EAAKC,MAAT,CAIA,IAAIC,EACY,oBAAqBF,EADjCE,EAEQ,WAAYF,GAAQ,aAAcG,OAF1CD,EAGI,eAAgBF,GAAQ,SAAUA,GAAQ,WAC9C,IAEE,OADA,IAAII,MACG,EACP,MAAMC,GACN,OAAO,GALqC,GAH9CH,EAWQ,aAAcF,EAXtBE,EAYW,gBAAiBF,EAGhC,GAAIE,EACF,IAAII,EAAc,CAChB,qBACA,sBACA,6BACA,sBACA,uBACA,sBACA,uBACA,wBACA,yBAGEC,EAAa,SAASC,GACxB,OAAOA,GAAOC,SAASC,UAAUC,cAAcH,IAG7CI,EAAoBC,YAAYC,QAAU,SAASN,GACrD,OAAOA,IAAmE,EAA5DF,EAAYS,QAAQC,OAAON,UAAUO,SAASC,KAAKV,KAyDrEW,EAAQT,UAAUU,OAAS,SAASC,EAAMC,GACxCD,EAAOE,EAAcF,GACrBC,EAAQE,EAA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