1
0
mirror of https://github.com/musix-org/musix-oss synced 2024-11-10 11:20:19 +00:00
musix-oss/node_modules/firebase/firebase.js.map
2020-03-03 22:30:50 +02:00

1 line
6.3 MiB
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{"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] ","../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/dom/asserts.js","../node_modules/google-closure-library/closure/goog/array/array.js","../node_modules/google-closure-library/closure/goog/object/object.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/string/internal.js","../node_modules/google-closure-library/closure/goog/html/safeurl.js","../node_modules/google-closure-library/closure/goog/labs/useragent/util.js","../node_modules/google-closure-library/closure/goog/html/safehtml.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/string/string.js","../node_modules/google-closure-library/closure/goog/labs/useragent/engine.js","../node_modules/google-closure-library/closure/goog/dom/safe.js","../node_modules/google-closure-library/closure/goog/labs/useragent/browser.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/reflect/reflect.js","../node_modules/google-closure-library/closure/goog/useragent/useragent.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/dom/browserfeature.js","../node_modules/google-closure-library/closure/goog/dom/dom.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/object.js","../auth/dist/src/deprecation.js","../auth/dist/src/actioncodeinfo.js","../auth/dist/src/error_auth.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/defines.js","../auth/dist/src/idp.js","../auth/dist/src/additionaluserinfo.js","../auth/dist/src/dynamiclink.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/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/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/util/log.ts","../firestore/src/core/version.ts","../firestore/src/util/assert.ts","../firestore/src/platform/platform.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/misc.ts","../firestore/src/api/blob.ts","../firestore/src/core/database_info.ts","../firestore/src/core/listen_sequence.ts","../firestore/src/model/path.ts","../firestore/src/model/document_key.ts","../firestore/src/util/promise.ts","../firestore/src/util/async_queue.ts","../firestore/src/local/encoded_resource_path.ts","../firestore/src/api/timestamp.ts","../firestore/src/core/snapshot_version.ts","../firestore/src/util/sorted_map.ts","../firestore/src/util/sorted_set.ts","../firestore/src/model/collections.ts","../firestore/src/model/mutation_batch.ts","../firestore/src/local/persistence_promise.ts","../firestore/src/local/simple_db.ts","../firestore/src/local/indexeddb_mutation_queue.ts","../firestore/src/core/target_id_generator.ts","../firestore/src/local/indexeddb_target_cache.ts","../firestore/src/model/mutation.ts","../firestore/src/model/field_value.ts","../firestore/src/model/document.ts","../firestore/src/util/obj_map.ts","../firestore/src/local/remote_document_change_buffer.ts","../firestore/src/local/indexeddb_remote_document_cache.ts","../firestore/src/local/memory_index_manager.ts","../firestore/src/local/indexeddb_schema.ts","../firestore/src/local/target_data.ts","../firestore/src/local/indexeddb_index_manager.ts","../firestore/src/local/local_serializer.ts","../firestore/src/local/local_documents_view.ts","../firestore/src/local/persistence.ts","../firestore/src/local/reference_set.ts","../firestore/src/local/local_store.ts","../firestore/src/local/lru_garbage_collector.ts","../firestore/src/local/indexeddb_persistence.ts","../firestore/src/util/types.ts","../firestore/src/core/target.ts","../firestore/src/core/query.ts","../firestore/src/local/index_free_query_engine.ts","../firestore/src/local/memory_mutation_queue.ts","../firestore/src/local/memory_remote_document_cache.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/core/transaction.ts","../firestore/src/core/types.ts","../firestore/src/remote/online_state_tracker.ts","../firestore/src/remote/rpc_error.ts","../firestore/src/model/document_set.ts","../firestore/src/core/view_snapshot.ts","../firestore/src/remote/remote_event.ts","../firestore/src/remote/watch_change.ts","../firestore/src/remote/remote_store.ts","../firestore/src/api/geo_point.ts","../firestore/src/model/transform_operation.ts","../firestore/src/remote/existence_filter.ts","../firestore/src/remote/serializer.ts","../firestore/src/core/event_manager.ts","../firestore/src/local/local_view_changes.ts","../firestore/src/core/view.ts","../firestore/src/core/transaction_runner.ts","../firestore/src/core/sync_engine.ts","../firestore/src/auth/user.ts","../firestore/src/local/shared_client_state_schema.ts","../firestore/src/local/shared_client_state.ts","../firestore/src/core/firestore_client.ts","../firestore/src/util/async_observer.ts","../firestore/src/api/field_path.ts","../firestore/src/api/credentials.ts","../firestore/src/api/observer.ts","../firestore/src/api/field_value.ts","../firestore/src/api/user_data_converter.ts","../firestore/src/api/database.ts","../firestore/src/platform/config.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","../firestore/index.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/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.2',\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;\n\nvar thrower = function (it) { throw it; };\n\nmodule.exports = function (METHOD_NAME, options) {\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 !!method && !fails(function () {\n if (ACCESSORS && !DESCRIPTORS) return true;\n var O = { length: -1 };\n\n var addTrap = function (key) {\n if (ACCESSORS) defineProperty(O, key, { enumerable: true, get: thrower });\n else O[key] = 1;\n };\n\n addTrap(1);\n addTrap(2147483646);\n addTrap(4294967294);\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 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) : new P(function (resolve) { resolve(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 m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n 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}\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","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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\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\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 * 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 switch (logType) {\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 */\n case LogLevel.DEBUG:\n console.log(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.VERBOSE:\n console.log(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.INFO:\n console.info(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.WARN:\n console.warn(`[${now}] ${instance.name}:`, ...args);\n break;\n case LogLevel.ERROR:\n console.error(`[${now}] ${instance.name}:`, ...args);\n break;\n default:\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 log handler for the Logger instance.\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 functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._logHandler(this, LogLevel.ERROR, ...args);\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}\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};\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 { 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 // @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 // 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","// 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 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 * Returns true if the specified value is not undefined.\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is defined.\n */\ngoog.isDef = function(val) {\n // void 0 always evaluates to undefined and hence we do not need to depend on\n // the definition of the global variable named 'undefined'.\n return val !== void 0;\n};\n\n/**\n * Returns true if the specified value is a string.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a string.\n */\ngoog.isString = function(val) {\n return typeof val == 'string';\n};\n\n\n/**\n * Returns true if the specified value is a boolean.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is boolean.\n */\ngoog.isBoolean = function(val) {\n return typeof val == 'boolean';\n};\n\n\n/**\n * Returns true if the specified value is a number.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a number.\n */\ngoog.isNumber = function(val) {\n return typeof val == 'number';\n};\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 && goog.isDef(opt_object)) {\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 (!goog.isString(name) || !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\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 */\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] &&\n goog.isDefAndNotNull(goog.getObjectByName(name)));\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 (!goog.isDefAndNotNull(cur)) {\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\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 */\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 (goog.isString(moduleDef)) {\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 (goog.isString(moduleName) && 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 null.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is null.\n */\ngoog.isNull = function(val) {\n return val === null;\n};\n\n\n/**\n * Returns true if the specified value is defined and not null.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is defined and not null.\n */\ngoog.isDefAndNotNull = function(val) {\n // Note that undefined == null.\n return val != null;\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\n // In Opera window.hasOwnProperty exists but always returns false so we avoid\n // using it. As a consequence the unique ID generated for BaseClass.prototype\n // and SubClass.prototype will be the same.\n return 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 * @param {Object} target Target.\n * @param {Object} source Source.\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 */\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 * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values) {\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 * Call up to the superclass.\n *\n * If this is called from a constructor, then this calls the superclass\n * constructor with arguments 1-N.\n *\n * If this is called from a prototype method, then you must pass the name of the\n * method as the second argument to this function. If you do not, you will get a\n * runtime error. This calls the superclass' method with arguments 2-N.\n *\n * This function only works if you use goog.inherits to express inheritance\n * relationships between your classes.\n *\n * This function is a compiler primitive. At compile-time, the compiler will do\n * macro expansion to remove a lot of the extra overhead that this function\n * introduces. The compiler will also enforce a lot of the assumptions that this\n * function makes, and treat it as a compiler error if you break them.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {*=} opt_methodName The method name if calling a super method.\n * @param {...*} var_args The rest of the arguments.\n * @return {*} The return value of the superclass method.\n * @suppress {es5Strict} This method can not be used in strict mode, but\n * all Closure Library consumers must depend on this file.\n * @deprecated goog.base is not strict mode compatible. Prefer the static\n * \"base\" method added to the constructor by goog.inherits\n * or ES6 classes and the \"super\" keyword.\n */\ngoog.base = function(me, opt_methodName, var_args) {\n var caller = arguments.callee.caller;\n\n if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) {\n throw new Error(\n 'arguments.caller not defined. goog.base() cannot be used ' +\n 'with strict mode code. See ' +\n 'http://www.ecma-international.org/ecma-262/5.1/#sec-C');\n }\n\n if (typeof caller.superClass_ !== 'undefined') {\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 ctorArgs = new Array(arguments.length - 1);\n for (var i = 1; i < arguments.length; i++) {\n ctorArgs[i - 1] = arguments[i];\n }\n // This is a constructor. Call the superclass constructor.\n return /** @type {!Function} */ (caller.superClass_)\n .constructor.apply(me, ctorArgs);\n }\n\n if (typeof opt_methodName != 'string' && typeof opt_methodName != 'symbol') {\n throw new Error(\n 'method names provided to goog.base must be a string or a symbol');\n }\n\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 var foundCaller = false;\n for (var proto = me.constructor.prototype; proto;\n proto = Object.getPrototypeOf(proto)) {\n if (proto[opt_methodName] === caller) {\n foundCaller = true;\n } else if (foundCaller) {\n return proto[opt_methodName].apply(me, args);\n }\n }\n\n // If we did not find the caller in the prototype chain, then one of two\n // things happened:\n // 1) The caller is an instance method.\n // 2) This method was not called by the right caller.\n if (me[opt_methodName] === caller) {\n return me.constructor.prototype[opt_methodName].apply(me, args);\n } else {\n throw new Error(\n 'goog.base called from a method of one name ' +\n 'to a method of a different name');\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 */\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.isDef(goog.global.CLOSURE_BASE_PATH) &&\n // Anti DOM-clobbering runtime check (b/37736576).\n goog.isString(goog.global.CLOSURE_BASE_PATH)) {\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\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.isDef(goog.global.JSON)) {\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 closures 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 if (typeof TrustedTypes === 'undefined' || !TrustedTypes.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 = TrustedTypes.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,"// 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\ngoog.provide('goog.Thenable');\n\n/** @suppress {extraRequire} */\ngoog.forwardDeclare('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","// Copyright 2009 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 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 */\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 var 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","// Copyright 2008 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 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 * @author agrieve@google.com (Andrew Grieve)\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_(\n 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 && !goog.isNumber(value)) {\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 && !goog.isString(value)) {\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 && !goog.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 && !goog.isBoolean(value)) {\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 */\ngoog.asserts.assertElement = function(value, opt_message, var_args) {\n if (goog.asserts.ENABLE_ASSERTS &&\n (!goog.isObject(value) || 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 * @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","// 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\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 = goog.defineClass(null, {\n /**\n * @param {function():ITEM} create\n * @param {function(ITEM):void} reset\n * @param {number} limit\n */\n constructor: function(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: function() {\n var 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: function(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: function() { return this.occupants_; }\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.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","// Copyright 2017 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.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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 value.constructor.displayName || value.constructor.name ||\n 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","// 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 Utilities for manipulating arrays.\n *\n * @author arv@google.com (Erik Arvidsson)\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 =\n goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false);\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 (goog.isString(arr)) {\n // Array.prototype.indexOf uses === so only strings should be found.\n if (!goog.isString(obj) || 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 (goog.isString(arr)) {\n // Array.prototype.lastIndexOf uses === so only strings should be found.\n if (!goog.isString(obj) || 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 = goog.isString(arr) ? 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 = goog.isString(arr) ? 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 = goog.isString(arr) ? 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 = goog.isString(arr) ? 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 = goog.isString(arr) ? 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 = goog.isString(arr) ? 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 : goog.isString(arr) ? 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 = goog.isString(arr) ? 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 : goog.isString(arr) ? 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 = goog.isString(arr) ? 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 (!goog.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, any\n * of these instances may 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) >> 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 // ~left is a shorthand for -left - 1.\n return found ? left : ~left;\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 (goog.isDef(key)) {\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 (goog.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","// 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 Utilities for manipulating objects/maps/hashes.\n * @author arv@google.com (Erik Arvidsson)\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 (var 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 var res = {};\n for (var 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 var res = {};\n for (var 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 (var 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 (var 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 var rv = 0;\n for (var 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 (var 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 (var 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 var res = [];\n var i = 0;\n for (var key in obj) {\n res[i++] = obj[key];\n }\n return res;\n};\n\n\n/**\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 var res = [];\n var i = 0;\n for (var 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 var isArrayLike = goog.isArrayLike(var_args);\n var 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 (var 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 (var 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 (var 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 var 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 (var 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 (var 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 var 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 var 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 (var k in a) {\n if (!(k in b) || a[k] !== b[k]) {\n return false;\n }\n }\n for (var 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 var res = {};\n for (var 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 var type = goog.typeOf(obj);\n if (type == 'object' || type == 'array') {\n if (goog.isFunction(obj.clone)) {\n return obj.clone();\n }\n var clone = type == 'array' ? [] : {};\n for (var 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 var transposed = {};\n for (var 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 */\ngoog.object.extend = function(target, var_args) {\n var key, source;\n for (var 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 (var 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 var argLength = arguments.length;\n if (argLength == 1 && goog.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 var rv = {};\n for (var 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 var argLength = arguments.length;\n if (argLength == 1 && goog.isArray(arguments[0])) {\n return goog.object.createSet.apply(null, arguments[0]);\n }\n\n var rv = {};\n for (var 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 var 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 var visitedSet = {};\n\n // Traverse the prototype chain and add all properties to the visited set.\n var proto = obj;\n while (proto &&\n (proto !== Object.prototype || !!opt_includeObjectPrototype) &&\n (proto !== Function.prototype || !!opt_includeFunctionPrototype)) {\n var names = Object.getOwnPropertyNames(proto);\n for (var 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","// 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\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\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 */\ngoog.string.Const.prototype.toString = function() {\n return 'Const{' +\n this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ +\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","// 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 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.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 * intentionally takes no parameters and the type is immutable; hence only a\n * default instance corresponding to the empty string can be obtained via\n * constructor invocation.\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 */\ngoog.html.TrustedResourceUrl = function() {\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 * @private {!TrustedScriptURL|string}\n */\n this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = '';\n\n /**\n * Value stored as TrustedURL. TrustedResourceURL corresponds to TrustedURL in\n * some context thus we need to store it separately.\n * @private {?TrustedURL}\n */\n this.trustedURL_ = null;\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 * Unwraps value as TrustedURL if supported or as a string if not.\n * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl\n * @return {!TrustedURL|string}\n * @see goog.html.TrustedResourceUrl.unwrap\n */\ngoog.html.TrustedResourceUrl.unwrapTrustedURL = function(trustedResourceUrl) {\n return trustedResourceUrl.trustedURL_ ?\n trustedResourceUrl.trustedURL_ :\n goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl);\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/**\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 trustedResourceUrl = new goog.html.TrustedResourceUrl();\n trustedResourceUrl.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ =\n 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 if (goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY) {\n trustedResourceUrl.trustedURL_ =\n goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createURL(\n url);\n }\n return trustedResourceUrl;\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 (goog.isString(params)) {\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 = goog.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","// 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 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 var 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 var test1 = String(str1).toLowerCase();\n var 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 var order = 0;\n // Trim leading and trailing whitespace and split the versions into\n // subversions.\n var v1Subs = goog.string.internal.trim(String(version1)).split('.');\n var v2Subs = goog.string.internal.trim(String(version2)).split('.');\n var subCount = Math.max(v1Subs.length, v2Subs.length);\n\n // Iterate over the subversions, as long as they appear to be equivalent.\n for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\n var v1Sub = v1Subs[subIdx] || '';\n var 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 var v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\n var 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 var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\n var 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 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.html.trustedtypes');\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 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 * @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 */\ngoog.html.SafeUrl = function() {\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 {!TrustedURL|string}\n */\n this.privateDoNotAccessOrElseSafeUrlWrappedValue_ = '';\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 return goog.html.SafeUrl.unwrapTrustedURL(safeUrl).toString();\n};\n\n\n/**\n * Unwraps value as TrustedURL if supported or as a string if not.\n * @param {!goog.html.SafeUrl} safeUrl\n * @return {!TrustedURL|string}\n * @see goog.html.SafeUrl.unwrap\n */\ngoog.html.SafeUrl.unwrapTrustedURL = 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(b/68188949): 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 var safeUrl = new goog.html.SafeUrl();\n safeUrl.privateDoNotAccessOrElseSafeUrlWrappedValue_ =\n goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY ?\n goog.html.trustedtypes.PRIVATE_DO_NOT_ACCESS_OR_ELSE_POLICY.createURL(\n url) :\n url;\n return safeUrl;\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","// 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 * @author nnaze@google.com (Nathan Naze)\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","// 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/**\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 * @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('Invalid tag name <' + tagName + '>.');\n }\n if (tagName.toUpperCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) {\n throw new Error('Tag name <' + tagName + '> is not allowed for SafeHtml.');\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('The browser does not support sandboxed iframes.');\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('Cannot set \"' + attrLower + '\" attribute');\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 value = goog.html.SafeHtml.getStyleValue_(value);\n } else if (/^on/i.test(name)) {\n // TODO(jakubvrana): Disallow more attributes with a special meaning.\n throw new Error(\n 'Attribute \"' + name + '\" requires goog.string.Const value, \"' + value +\n '\" given.');\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 (goog.isString(value)) {\n value = goog.html.SafeUrl.sanitize(value).getTypedStringValue();\n } else {\n throw new Error(\n 'Attribute \"' + name + '\" on tag \"' + tagName +\n '\" requires goog.html.SafeUrl, goog.string.Const, or string,' +\n ' value \"' + value + '\" given.');\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 goog.isString(value) || goog.isNumber(value),\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 'The \"style\" attribute requires goog.html.SafeStyle or map ' +\n 'of style properties, ' + (typeof value) + ' given: ' + value);\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 (goog.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 (!goog.isDefAndNotNull(content)) {\n content = [];\n } else if (!goog.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('Invalid attribute name \"' + name + '\".');\n }\n var value = opt_attributes[name];\n if (!goog.isDefAndNotNull(value)) {\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 for (name in opt_attributes) {\n var nameLower = name.toLowerCase();\n if (nameLower in fixedAttributes) {\n throw new Error(\n 'Cannot override \"' + nameLower + '\" attribute, got \"' + name +\n '\" with value \"' + opt_attributes[name] + '\"');\n }\n if (nameLower in defaultAttributes) {\n delete combinedAttributes[nameLower];\n }\n combinedAttributes[name] = opt_attributes[name];\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","// 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 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 */\n\ngoog.provide('goog.async.nextTick');\ngoog.provide('goog.async.throwException');\n\ngoog.require('goog.debug.entryPointRegistry');\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 = /** @type {!HTMLIFrameElement} */ (\n document.createElement(String(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 (goog.isDef(head.next)) {\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 // Implementation for IE6 to IE10: Script elements fire an asynchronous\n // onreadystatechange event when inserted into the DOM.\n if (typeof document !== 'undefined' &&\n 'onreadystatechange' in\n document.createElement(String(goog.dom.TagName.SCRIPT))) {\n return function(cb) {\n var script = /** @type {!HTMLScriptElement} */ (\n document.createElement(String(goog.dom.TagName.SCRIPT)));\n script.onreadystatechange = function() {\n // Clean up and call the callback.\n script.onreadystatechange = null;\n script.parentNode.removeChild(script);\n script = null;\n cb();\n cb = null;\n };\n document.documentElement.appendChild(script);\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 IE11.\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","// 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\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","// 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 Utilities for string manipulation.\n * @author arv@google.com (Erik Arvidsson)\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 = goog.isDef(opt_precision) ? 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 = goog.isString(opt_delimiters) ?\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 (goog.isString(value)) {\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","// 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 */\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","// 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 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 * 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.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.unwrapTrustedURL(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 * 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.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.unwrapTrustedURL(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 * 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.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.unwrapTrustedURL(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.unwrapTrustedURL(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.unwrapTrustedURL(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.unwrapTrustedURL(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.unwrapTrustedURL(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.unwrapTrustedURL(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.unwrapTrustedURL(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.unwrapTrustedURL(url);\n } else if (url instanceof goog.html.TrustedResourceUrl) {\n link.href = goog.html.TrustedResourceUrl.unwrapTrustedURL(url);\n } else if (url instanceof goog.html.SafeUrl) {\n link.href = goog.html.SafeUrl.unwrapTrustedURL(url);\n } else { // string\n // SafeUrl.sanitize must return legitimate SafeUrl when passed a string.\n link.href = goog.html.SafeUrl.unwrapTrustedURL(\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.unwrapTrustedURL(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.unwrapTrustedURL(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 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.replace(goog.html.SafeUrl.unwrapTrustedURL(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.unwrapTrustedURL(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","// 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 * @author martone@google.com (Andy Martone)\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']);\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\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 goog.async.run(function() {\n var err = new goog.Promise.CancellationError(opt_message);\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 (!goog.isDef(result) &&\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 try {\n var then = value['then'];\n if (goog.isFunction(then)) {\n goog.Promise.tryThen_(value, 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 && goog.isString(err.stack)) {\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 && goog.isString(err.stack) &&\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","// Copyright 2005 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 Implements the disposable interface. The dispose method is used\n * to clean up references and resources.\n * @author arv@google.com (Erik Arvidsson)\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 one or more references to COM objects, DOM nodes, or other\n * disposable objects, it should extend this class or implement the disposable\n * interface (defined in goog.disposable.IDisposable).\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 delete references to COM\n * objects, DOM nodes, 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 goog.isDef(opt_scope) ? callback.call(opt_scope) : callback();\n return;\n }\n if (!this.onDisposeCallbacks_) {\n this.onDisposeCallbacks_ = [];\n }\n\n this.onDisposeCallbacks_.push(\n goog.isDef(opt_scope) ? goog.bind(callback, opt_scope) : callback);\n};\n\n\n/**\n * Deletes or nulls out any references to COM objects, DOM nodes, or other\n * disposable objects. Classes that extend `goog.Disposable` should\n * override this method.\n * Not reentrant. To avoid calling it twice, it must only be called from the\n * subclass' `disposeInternal` method. Everywhere else the public\n * `dispose` method must be used.\n * For example:\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 * @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","// Copyright 2009 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 Useful compiler idioms.\n *\n * @author johnlenz@google.com (John Lenz)\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 var 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","// 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 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 * @author arv@google.com (Erik Arvidsson)\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 * @define {boolean} Whether the user agent is running on Go2Phone.\n */\ngoog.userAgent.ASSUME_GO2PHONE =\n goog.define('goog.userAgent.ASSUME_GO2PHONE', 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 * Whether the user agent is running on Go2Phone.\n * @type {boolean}\n */\ngoog.userAgent.GO2PHONE = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_GO2PHONE :\n goog.labs.userAgent.platform.isGo2Phone();\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(2019/05/31): 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 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 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 (!goog.isDef(obj)) {\n str.push('undefined');\n } else if (goog.isNull(obj)) {\n str.push('NULL');\n } else if (goog.isString(obj)) {\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 (goog.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 (goog.isString(err)) {\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","// 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 Browser capability checks for the events package.\n *\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","// Copyright 2005 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 base class for event objects.\n *\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 * @suppress {underscore} Several properties on this class are technically\n * public, but referencing these properties outside this package is strongly\n * discouraged.\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 * @public\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 * Return value for in internal capture/bubble processing for IE.\n * @type {boolean}\n * @public\n */\n this.returnValue_ = true;\n};\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 this.returnValue_ = false;\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","// Copyright 2005 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 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 * @author arv@google.com (Erik Arvidsson)\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 (goog.isString(e.pointerType)) {\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","// 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 Event Types.\n *\n * @author arv@google.com (Erik Arvidsson)\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 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","// Copyright 2012 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 An interface for a listenable JavaScript object.\n * @author chrishenry@google.com (Chris Henry)\n */\n\ngoog.provide('goog.events.Listenable');\ngoog.provide('goog.events.ListenableKey');\n\n/** @suppress {extraRequire} */\ngoog.require('goog.events.EventId');\n\ngoog.forwardDeclare('goog.events.EventLike');\ngoog.forwardDeclare('goog.events.EventTarget');\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","// Copyright 2005 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 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","// 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 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\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 = goog.isDef(opt_type);\n var typeStr = hasType ? opt_type.toString() : '';\n var hasCapture = goog.isDef(opt_capture);\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","// Copyright 2005 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 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 * @author arv@google.com (Erik Arvidsson)\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.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\ngoog.forwardDeclare('goog.debug.ErrorHandler');\ngoog.forwardDeclare('goog.events.EventWrapper');\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 (goog.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 // 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 (goog.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 (goog.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 (goog.isNumber(key)) {\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; !evt.propagationStopped_ && i >= 0;\n 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.propagationStopped_ && i < ancestors.length; 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","// Copyright 2005 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 disposable implementation of a custom\n * listenable/event target. See also: documentation for\n * `goog.events.Listenable`.\n *\n * @author arv@google.com (Erik Arvidsson) [Original implementation]\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.returnValue_ != false;\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 = goog.isDef(opt_type) ? 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 (goog.isString(e)) {\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; !e.propagationStopped_ && i >= 0;\n 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.propagationStopped_) {\n currentTarget = /** @type {?} */ (e.currentTarget = target);\n rv = currentTarget.fireListeners(type, true, e) && rv;\n if (!e.propagationStopped_) {\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.propagationStopped_ && i < opt_ancestorsTree.length; i++) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n return rv;\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 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","// 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 Generics method for collection-like classes and objects.\n *\n * @author arv@google.com (Erik Arvidsson)\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) || goog.isString(col)) {\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 (goog.isString(col)) {\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) || goog.isString(col)) {\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) || goog.isString(col)) {\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) || goog.isString(col)) {\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) || goog.isString(col)) {\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) || goog.isString(col)) {\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) || goog.isString(col)) {\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) || goog.isString(col)) {\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) || goog.isString(col)) {\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","// 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 Datastructure: Hash Map.\n *\n * @author arv@google.com (Erik Arvidsson)\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","// Copyright 2008 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 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 * @author gboyer@google.com (Garrett Boyer) - The \"lightened\" design.\n * @author msamuel@google.com (Mike Samuel) - Domain knowledge and regexes.\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 (goog.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 = goog.isDefAndNotNull(opt_value) ?\n '=' + goog.string.urlEncode(opt_value) :\n '';\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","// 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 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 * @author msamuel@google.com (Mike Samuel)\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_ =\n goog.isDef(opt_ignoreCase) ? opt_ignoreCase : 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 (!goog.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 (goog.isString(unescapedPart)) {\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 (!goog.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 (goog.isString(opt_key)) {\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","// 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 Browser capability checks for the dom package.\n *\n */\n\n\ngoog.provide('goog.dom.BrowserFeature');\n\ngoog.require('goog.userAgent');\n\n\n/**\n * Enum of browser capabilities.\n * @enum {boolean}\n */\ngoog.dom.BrowserFeature = {\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 */\n 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 */\n CAN_USE_CHILDREN_ATTRIBUTE: !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 */\n 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 */\n 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 */\n INNER_HTML_NEEDS_SCOPED_ELEMENT: goog.userAgent.IE,\n\n /**\n * Whether we use legacy IE range API.\n */\n LEGACY_IE_RANGES:\n goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)\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 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 * @author arv@google.com (Erik Arvidsson)\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 goog.isString(element) ? 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 = doc.createElement(tagName);\n\n if (attributes) {\n if (goog.isString(attributes)) {\n element.className = attributes;\n } else if (goog.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 goog.isString(child) ? 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 return doc.createElement(String(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(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 (goog.isDef(node.firstElementChild)) {\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 (goog.isDef(node.lastElementChild)) {\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 (goog.isDef(node.nextElementSibling)) {\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 (goog.isDef(node.previousElementSibling)) {\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 goog.isDefAndNotNull(attrNode) && 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 goog.isNumber(index) && 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 goog.isDefAndNotNull(rect) && 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 goog.isString(node.className) &&\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 (goog.isDef(win.devicePixelRatio)) {\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} 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","// 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 JSON utility functions.\n * @author arv@google.com (Erik Arvidsson)\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 var backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\n var simpleValuesRe =\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\n var openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\n var 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 var 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 var o = String(s);\n if (goog.json.isValid(o)) {\n\n try {\n var 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 var 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 (goog.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 var 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 var l = arr.length;\n sb.push('[');\n var sep = '';\n for (var i = 0; i < l; i++) {\n sb.push(sep);\n\n var 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 var sep = '';\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var 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 goog.isString(email) &&\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 (goog.isNull(json)) {\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","// 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 Utilities for window manipulation.\n */\n\n\ngoog.provide('goog.window');\n\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 = /** @type {!HTMLAnchorElement} */\n (parentWin.document.createElement(String(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 goog.dom.safe.documentWrite(newWin.document, safeHtml);\n newWin.document.close();\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 */\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 * @return {boolean} Whether the platform is Go2Phone.\n */\ngoog.labs.userAgent.platform.isGo2Phone = function() {\n return goog.labs.userAgent.util.matchUserAgentIgnoreCase('GAFP');\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 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 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.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 // Email could be empty only if the request type is EMAIL_SIGNIN.\n if (!operation ||\n (operation != fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN &&\n !email)) {\n // This is internal only.\n throw new Error('Invalid provider user info!');\n }\n data[fireauth.ActionCodeInfo.DataField.FROM_EMAIL] = newEmail || null;\n data[fireauth.ActionCodeInfo.DataField.EMAIL] = email || 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 EMAIL_SIGNIN: 'EMAIL_SIGNIN',\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 // 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 FROM_EMAIL: 'fromEmail'\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 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=} opt_message The human-readable message.\n * @constructor\n * @extends {Error}\n */\nfireauth.AuthError = function(code, opt_message) {\n this['code'] = fireauth.AuthError.ERROR_CODE_PREFIX + code;\n this.message = opt_message || fireauth.AuthError.MESSAGES_[code] || '';\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 return {\n 'code': this['code'],\n 'message': this.message\n };\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), response['message']);\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_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_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 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_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 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_PERSISTENCE: 'unsupported-persistence-type',\n UNSUPPORTED_TENANT_OPERATION: 'unsupported-tenant-operation',\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_[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_[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.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_[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.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_[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.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 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/**\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 'signIn': fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN,\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","// 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 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 * @author doughtie@google.com (Gavin Doughtie)\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// Static lookup maps, lazily populated by init_()\n\n\n/**\n * Maps bytes to characters.\n * @type {?Object}\n * @private\n */\ngoog.crypt.base64.byteToCharMap_ = null;\n\n\n/**\n * Maps characters to bytes. Used for normal and websafe characters.\n * @type {?Object}\n * @private\n */\ngoog.crypt.base64.charToByteMap_ = null;\n\n\n/**\n * Maps bytes to websafe characters.\n * @type {?Object}\n * @private\n */\ngoog.crypt.base64.byteToCharMapWebSafe_ = null;\n\n\n/**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n * @type {string}\n */\ngoog.crypt.base64.ENCODED_VALS_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +\n 'abcdefghijklmnopqrstuvwxyz' +\n '0123456789';\n\n\n/**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n * @type {string}\n */\ngoog.crypt.base64.ENCODED_VALS = goog.crypt.base64.ENCODED_VALS_BASE + '+/=';\n\n\n/**\n * Our websafe alphabet.\n * @type {string}\n */\ngoog.crypt.base64.ENCODED_VALS_WEBSAFE =\n goog.crypt.base64.ENCODED_VALS_BASE + '-_.';\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 {boolean=} opt_webSafe True indicates we should use the alternative\n * alphabet, which does not require escaping for use in URLs.\n * @return {string} The base64 encoded string.\n */\ngoog.crypt.base64.encodeByteArray = function(input, opt_webSafe) {\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 goog.crypt.base64.init_();\n\n var byteToCharMap = opt_webSafe ? goog.crypt.base64.byteToCharMapWebSafe_ :\n goog.crypt.base64.byteToCharMap_;\n\n var output = [];\n\n for (var i = 0; i < input.length; i += 3) {\n var byte1 = input[i];\n var haveByte2 = i + 1 < input.length;\n var byte2 = haveByte2 ? input[i + 1] : 0;\n var haveByte3 = i + 2 < input.length;\n var byte3 = haveByte3 ? input[i + 2] : 0;\n\n var outByte1 = byte1 >> 2;\n var outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n var outByte3 = ((byte2 & 0x0F) << 2) | (byte3 >> 6);\n var outByte4 = byte3 & 0x3F;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1], 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 {boolean=} opt_webSafe True indicates we should use the alternative\n * alphabet, which does not require escaping for use in URLs.\n * @return {string} The base64 encoded string.\n */\ngoog.crypt.base64.encodeString = function(input, opt_webSafe) {\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_ && !opt_webSafe) {\n return goog.global.btoa(input);\n }\n return goog.crypt.base64.encodeByteArray(\n goog.crypt.stringToByteArray(input), opt_webSafe);\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=} opt_webSafe True indicates we should use the alternative\n * alphabet, which does not require escaping for use in URLs. Note that\n * passing false may also still allow webSafe input decoding, when the\n * fallback decoder is used on browsers without native support.\n * @return {string} string representing the decoded value.\n */\ngoog.crypt.base64.decodeString = function(input, opt_webSafe) {\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_ && !opt_webSafe) {\n return goog.global.atob(input);\n }\n var output = '';\n function pushByte(b) { output += String.fromCharCode(b); }\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 (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 (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.byteToCharMap_) {\n goog.crypt.base64.byteToCharMap_ = {};\n goog.crypt.base64.charToByteMap_ = {};\n goog.crypt.base64.byteToCharMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (var i = 0; i < goog.crypt.base64.ENCODED_VALS.length; i++) {\n goog.crypt.base64.byteToCharMap_[i] =\n goog.crypt.base64.ENCODED_VALS.charAt(i);\n goog.crypt.base64.charToByteMap_[goog.crypt.base64.byteToCharMap_[i]] = i;\n goog.crypt.base64.byteToCharMapWebSafe_[i] =\n goog.crypt.base64.ENCODED_VALS_WEBSAFE.charAt(i);\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= goog.crypt.base64.ENCODED_VALS_BASE.length) {\n goog.crypt.base64\n .charToByteMap_[goog.crypt.base64.ENCODED_VALS_WEBSAFE.charAt(i)] =\n i;\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 {!fireauth.IdToken.JsonToken} token The parsed JSON token.\n * @constructor\n */\nfireauth.IdToken = function(token) {\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 * 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 var token = fireauth.IdToken.parseIdTokenClaims(tokenString);\n if (token && token['sub'] && token['iss'] && token['aud'] && token['exp']) {\n return new fireauth.IdToken(\n /** @type {!fireauth.IdToken.JsonToken} */ (token));\n }\n return null;\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 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 * 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>id: defines the endpoint identifier.</li>\n * </ul>\n * @typedef {{\n * firebaseAuthEndpoint: string,\n * secureTokenEndpoint: 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 PRODUCTION: {\n firebaseAuthEndpoint: 'https://www.googleapis.com/identitytoolkit/v3/' +\n 'relyingparty/',\n secureTokenEndpoint: 'https://securetoken.googleapis.com/v1/token',\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 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 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 };\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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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.require('fireauth.ActionCodeInfo');\ngoog.require('fireauth.ActionCodeURL');\ngoog.require('fireauth.AuthError');\ngoog.require('fireauth.DynamicLink');\ngoog.require('fireauth.IdToken');\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\ngoog.forwardDeclare('fireauth.RpcHandler');\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;\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\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\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;\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 * @override\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 * @override\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 * @override\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 * @override\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 * @override\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.\n * @param {!fireauth.PhoneAuthCredential.Parameters_} params The credential\n * parameters that prove the user owns the claimed phone number.\n * @constructor\n * @implements {fireauth.AuthCredential}\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 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 * 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 * Initiates a phone number confirmation flow.\n * @param {string} phoneNumber The user's 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(phoneNumber, 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 (!goog.isString(assertion)) {\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 return rpcHandler\n .sendVerificationCode(\n {'phoneNumber': phoneNumber, 'recaptchaToken': assertion})\n .then(\n function(verificationId) {\n if (typeof applicationVerifier.reset === 'function') {\n applicationVerifier.reset();\n }\n return verificationId;\n },\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 * @override\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 = goog.isString(json) ? 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 this.secureTokenHeaders_ = goog.object.clone(\n config['secureTokenHeaders'] ||\n fireauth.RpcHandler.DEFAULT_SECURE_TOKEN_HEADERS_);\n this.firebaseEndpoint_ = config['firebaseEndpoint'] ||\n fireauth.RpcHandler.FIREBASE_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_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_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 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_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 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_TENANT_OPERATION: 'UNSUPPORTED_TENANT_OPERATION',\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 NEED_CONFIRMATION: 'needConfirmation',\n OAUTH_ID_TOKEN: 'oauthIdToken',\n PENDING_TOKEN: 'pendingToken',\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_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 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.\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 var self = this;\n // Construct endpoint URL.\n var uri = goog.Uri.parse(this.firebaseEndpoint_ + 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 * @param {?Object} response The server response data.\n * @private\n */\nfireauth.RpcHandler.validateIdTokenResponse_ = function(response) {\n if (!response[fireauth.RpcHandler.AuthServerField.ID_TOKEN]) {\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 * 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 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 * 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 // If no error found and ID token is missing, throw an internal error.\n if (!response[fireauth.RpcHandler.AuthServerField.ID_TOKEN]) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\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 // If no error found and ID token is missing, throw an internal error.\n if (!response[fireauth.RpcHandler.AuthServerField.ID_TOKEN]) {\n throw new fireauth.AuthError(fireauth.authenum.Error.INTERNAL_ERROR);\n }\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 || (!response['email'] && operation != 'EMAIL_SIGNIN')) {\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 * </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 * }}\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 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_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 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};\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 * @private\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 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 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 // 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 * @author arv@google.com (Erik Arvidsson)\n * @author dbk@google.com (David Barrett-Kahn)\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', 'MSXML2.XMLHTTP.3.0', '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 * @override\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 * @author dbk@google.com (David Barrett-Kahn)\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 (goog.isDefAndNotNull(opt_async) && (!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","// 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 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 */\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","// 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 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","// Copyright 2008 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 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 * @author nicksantos@google.com (Nick Santos)\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 var 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 var rightArgs = Array.prototype.slice.call(arguments, 1);\n return function() {\n var self = /** @type {*} */ (this);\n var 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 var functions = arguments;\n var length = functions.length;\n return function() {\n var self = /** @type {*} */ (this);\n var result;\n if (length) {\n result = functions[length - 1].apply(self, arguments);\n }\n\n for (var 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 var functions = arguments;\n var length = functions.length;\n return function() {\n var self = /** @type {*} */ (this);\n var result;\n for (var 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 var functions = arguments;\n var length = functions.length;\n return function() {\n var self = /** @type {*} */ (this);\n for (var 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 var functions = arguments;\n var length = functions.length;\n return function() {\n var self = /** @type {*} */ (this);\n for (var 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 var 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 */\ngoog.functions.create = function(constructor, var_args) {\n /**\n * @constructor\n * @final\n */\n var 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 var 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 var called = false;\n var 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 var inner = f;\n return function() {\n if (inner) {\n var 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 var timeout = 0;\n return /** @type {function(...?)} */ (function(var_args) {\n goog.global.clearTimeout(timeout);\n var 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 var timeout = 0;\n var shouldFire = false;\n var args = [];\n\n var handleTimeout = function() {\n timeout = 0;\n if (shouldFire) {\n shouldFire = false;\n fire();\n }\n };\n\n var 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 var timeout = 0;\n\n var 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","// 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 Basic strippable logging definitions.\n * @see http://go/closurelogging\n *\n * @author johnlenz@google.com (John Lenz)\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(b/70808323): 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\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');\n\ngoog.forwardDeclare('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 goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&\n goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);\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 goog.isNull(value) ? 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(b/120371595): 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 (!goog.isString(value)) {\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 goog.isString(this.lastError_) ? 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 * @author arv@google.com (Erik Arvidsson)\n * @author brenneman@google.com (Shawn Brenneman)\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 */\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 (!goog.isDef(result)) {\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 (goog.isDef(ret)) {\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 */\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 = goog.isDefAndNotNull(options.timeout) ?\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 (goog.isDef(verifyObjs[verificationObjName])) {\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 (goog.isDef(result)) {\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 (goog.isDef(verifyObjs[verificationObjName])) {\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 (goog.isDefAndNotNull(opt_timeout)) {\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 (goog.isNull(obj)) {\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 (goog.isNull(obj)) {\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","// Copyright 2012 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 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 */\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.isDef(goog.crypt.Sha2.Kx_)) {\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 (!goog.isDef(opt_length)) {\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 (goog.isString(message)) {\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","// Copyright 2011 The Closure Library Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * @fileoverview Abstract cryptographic hash interface.\n *\n * See goog.crypt.Sha1 and goog.crypt.Md5 for sample implementations.\n *\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","// Copyright 2012 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 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 */\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","// Copyright 2008 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 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 'claims': idToken\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.UserEvent');\ngoog.provide('fireauth.UserEventType');\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.PhoneAuthProvider');\ngoog.require('fireauth.ProactiveRefresh');\ngoog.require('fireauth.RpcHandler');\ngoog.require('fireauth.StsTokenManager');\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/**\n * User custom event.\n * @param {string} type The event type.\n * @param {?Object=} opt_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, opt_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 opt_properties) {\n this[key] = opt_properties[key];\n }\n};\ngoog.inherits(fireauth.UserEvent, goog.events.Event);\n\n\n/**\n * Events dispatched by pages on containers.\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\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};\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 * 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 * }}\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};\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 * @private\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};\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 email 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 * 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};\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 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. It is\n // also difficult to have toPlainObject equal server response due to expiresIn\n // field in server response. toPlainObject will return an expiration time\n // instead.\n var stsTokenManagerResponse = {};\n if (user['stsTokenManager'] &&\n user['stsTokenManager']['accessToken'] &&\n user['stsTokenManager']['expirationTime']) {\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 stsTokenManagerResponse[fireauth.RpcHandler.AuthServerField.EXPIRES_IN] =\n (user['stsTokenManager']['expirationTime'] - goog.now()) / 1000;\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.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 {?string} The STS ID token. */\n this.accessToken_ = null;\n /** @private {number} The STS expiration timestamp. */\n this.expirationTime_ = 0;\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_,\n 'expirationTime': this.expirationTime_\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(\n obj['accessToken'], obj['expirationTime'] || 0);\n }\n return stsTokenManager;\n};\n\n\n/**\n * @typedef {{\n * accessToken: (?string),\n * expirationTime: (number),\n * refreshToken: (?string)\n * }}\n */\nfireauth.StsTokenManager.Response;\n\n\n/**\n * @typedef {{\n * access_token: (?string|undefined),\n * expires_in: (number|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 * @param {number} expirationTime The STS token expiration time.\n */\nfireauth.StsTokenManager.prototype.setAccessToken = function(\n accessToken, expirationTime) {\n this.accessToken_ = accessToken;\n this.expirationTime_ = expirationTime;\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.\n */\nfireauth.StsTokenManager.prototype.getExpirationTime = function() {\n return this.expirationTime_;\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 * @private\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.expirationTime_ - 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 var expirationTime = fireauth.StsTokenManager.calcOffsetTimestamp_(\n response[fireauth.RpcHandler.AuthServerField.EXPIRES_IN]);\n this.setAccessToken(idToken, expirationTime);\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_;\n // Refresh token could be expired.\n stsTokenManagerResponse[fireauth.RpcHandler.AuthServerField.REFRESH_TOKEN] =\n this.getRefreshToken();\n stsTokenManagerResponse[fireauth.RpcHandler.AuthServerField.EXPIRES_IN] =\n (this.getExpirationTime() - goog.now()) / 1000;\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 this.expirationTime_ = tokenManagerToCopy.expirationTime_;\n};\n\n\n/**\n * @param {number|string} offset The offset to add to the current time, in\n * seconds.\n * @return {number} The timestamp corresponding to the current time plus offset.\n * @private\n */\nfireauth.StsTokenManager.calcOffsetTimestamp_ = function(offset) {\n return goog.now() + parseInt(offset, 10) * 1000;\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_ =\n response[fireauth.RpcHandler.StsServerField.ACCESS_TOKEN];\n // Update expiration time.\n self.expirationTime_ = fireauth.StsTokenManager.calcOffsetTimestamp_(\n response[fireauth.RpcHandler.StsServerField.EXPIRES_IN]);\n self.refreshToken_ =\n response[fireauth.RpcHandler.StsServerField.REFRESH_TOKEN];\n return /** @type {fireauth.StsTokenManager.Response} */ ({\n 'accessToken': self.accessToken_,\n 'expirationTime': self.expirationTime_,\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_,\n 'expirationTime': self.expirationTime_,\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.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 // This routine could be run before init state, make sure it waits for that to\n // complete.\n var credential = null;\n var additionalUserInfo = null;\n var idTokenResolver = self.rpcHandler_.verifyAssertion(request)\n .then(function(response) {\n // Get Auth credential from verify assert request and save it.\n credential = fireauth.AuthProvider.getCredentialFromResponse(response);\n // Get additional IdP data if available in the response.\n additionalUserInfo = fireauth.AdditionalUserInfo.fromPlainObject(\n response);\n return response;\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 var p = self.authStateLoaded_.then(function() {\n return idTokenResolver;\n }).then(function(idTokenResponse) {\n // Use ID token response to sign in the Auth user.\n return self.signInWithIdTokenResponse(idTokenResponse);\n }).then(function() {\n // On sign in success, construct redirect and popup result and return a\n // readonly copy of it.\n return fireauth.object.makeReadonlyCopy({\n 'user': self.currentUser_(),\n 'credential': credential,\n 'additionalUserInfo': additionalUserInfo,\n // Sign in operation type.\n 'operationType': fireauth.constants.OperationType.SIGN_IN\n });\n });\n return /** @type {!goog.Promise<!fireauth.AuthEventManager.Result>} */ (\n this.registerPendingPromise_(p));\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 })\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 * 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 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.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: goog.isString\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: goog.isBoolean\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: goog.isNumber\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: goog.isNull\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.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 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 goog.isString(applicationVerifier.type) &&\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.OAuthCredential');\ngoog.require('fireauth.OAuthProvider');\ngoog.require('fireauth.PhoneAuthCredential');\ngoog.require('fireauth.PhoneAuthProvider');\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 });\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.string('phoneNumber'),\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 });\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\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 '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\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 closures 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 { 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 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 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\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 { DatabaseId, DatabaseInfo } from '../core/database_info';\nimport { ProtoByteString } from '../core/types';\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 /** 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 readonly emptyByteString: ProtoByteString;\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/**\n * Returns the representation of an empty \"proto\" byte string for the\n * platform.\n */\nexport function emptyByteString(): ProtoByteString {\n return PlatformSupport.getPlatform().emptyByteString;\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 for (const staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (PublicConstructor as any)[staticProperty] = (cls as any)[staticProperty];\n }\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 const result: Dict<V> = {};\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\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 */\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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 for (let i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\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 { 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';\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 // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n const binaryString = Array.prototype.map\n .call(array, (char: number) => {\n return String.fromCharCode(char);\n })\n .join('');\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 = new Uint8Array(this._binaryString.length);\n for (let i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\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 { 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 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 '../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\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 { 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 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 drain(): Promise<void> {\n // It should still be possible to drain the queue after it is shutting down.\n return this.enqueueEvenAfterShutdown(() => Promise.resolve());\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 { 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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\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 // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n if (seconds < -62135596800) {\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","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 './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 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { Timestamp } from '../api/timestamp';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { BatchId, ProtoByteString } from '../core/types';\nimport { assert } from '../util/assert';\nimport * as misc from '../util/misc';\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: ProtoByteString,\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: ProtoByteString\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 { 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 =\n | 'readonly'\n | 'readwrite'\n | 'readonly-idempotent'\n | 'readwrite-idempotent';\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.startsWith('readonly');\n const idempotent = mode.endsWith('idempotent');\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 idempotent &&\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, ProtoByteString } 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 { 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 { SimpleDb, 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: ProtoByteString\n ): PersistencePromise<void> {\n return this.getMutationQueueMetadata(transaction).next(metadata => {\n metadata.lastStreamToken = convertStreamToken(streamToken);\n\n return mutationQueuesStore(transaction).put(metadata);\n });\n }\n\n getLastStreamToken(\n transaction: PersistenceTransaction\n ): PersistencePromise<ProtoByteString> {\n return this.getMutationQueueMetadata(transaction).next<ProtoByteString>(\n metadata => metadata.lastStreamToken\n );\n }\n\n setLastStreamToken(\n transaction: PersistenceTransaction,\n streamToken: ProtoByteString\n ): PersistencePromise<void> {\n return this.getMutationQueueMetadata(transaction).next(metadata => {\n metadata.lastStreamToken = convertStreamToken(streamToken);\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\nfunction convertStreamToken(token: ProtoByteString): string {\n if (token instanceof Uint8Array) {\n // TODO(b/78771403): Convert tokens to strings during deserialization\n assert(\n SimpleDb.isMockPersistence(),\n 'Persisting non-string stream tokens is only supported with mock persistence.'\n );\n return token.toString();\n } else {\n return token;\n }\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 { assert } from '../util/assert';\nimport { TargetId } from './types';\n\nconst RESERVED_BITS = 1;\n\nenum 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 { 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 { 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 } 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 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 this.fieldMask.fields.forEach(fieldPath => {\n if (!fieldPath.isEmpty()) {\n const newValue = this.data.field(fieldPath);\n if (newValue !== null) {\n data = data.set(fieldPath, newValue);\n } else {\n data = data.delete(fieldPath);\n }\n }\n });\n return data;\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: ObjectValue | 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.EMPTY.set(\n fieldTransform.field,\n coercedValue\n );\n } else {\n baseObject = baseObject.set(fieldTransform.field, coercedValue);\n }\n }\n }\n return baseObject;\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 for (let i = 0; i < this.fieldTransforms.length; i++) {\n const fieldTransform = this.fieldTransforms[i];\n const fieldPath = fieldTransform.field;\n data = data.set(fieldPath, transformResults[i]);\n }\n return data;\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 { 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 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 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, other);\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 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 set(path: FieldPath, to: FieldValue): ObjectValue {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n } else {\n let child = this.child(path.firstSegment());\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n const newChild = (child as ObjectValue).set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n }\n\n delete(path: FieldPath): ObjectValue {\n assert(\n !path.isEmpty(),\n 'Cannot delete field for empty path on ObjectValue'\n );\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n } else {\n // nested field\n const child = this.child(path.firstSegment());\n if (child instanceof ObjectValue) {\n const newChild = child.delete(path.popFirst());\n return new ObjectValue(\n this.internalValue.insert(path.firstSegment(), newChild)\n );\n } else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\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 private child(childName: string): FieldValue | undefined {\n return this.internalValue.get(childName) || undefined;\n }\n\n private setChild(childName: string, value: FieldValue): ObjectValue {\n return new ObjectValue(this.internalValue.insert(childName, value));\n }\n\n static EMPTY = new ObjectValue(\n new SortedMap<string, FieldValue>(primitiveComparator)\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 let result = ObjectValue.EMPTY;\n obj.forEach(this.proto!.fields || {}, (key: string, value: api.Value) => {\n result = result.set(new FieldPath([key]), this.converter!(value));\n });\n this.objectValue = result;\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\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 { 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 { 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 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 { 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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, ProtoByteString, TargetId } from '../core/types';\nimport { emptyByteString } from '../platform/platform';\n\n/** An enumeration of the different purposes we have for targets. */\nexport 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: ProtoByteString = emptyByteString()\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: ProtoByteString,\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 === other.resumeToken &&\n this.target.isEqual(other.target)\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 { 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';\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 { SimpleDb } from './simple_db';\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 // TODO(b/140573486): Convert to platform representation\n const resumeToken = dbTarget.resumeToken;\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 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 let resumeToken: string;\n\n if (targetData.resumeToken instanceof Uint8Array) {\n // TODO(b/78771403): Convert tokens to strings during deserialization\n assert(\n SimpleDb.isMockPersistence(),\n 'Persisting non-string stream tokens is only supported with mock persistence .'\n );\n resumeToken = targetData.resumeToken.toString();\n } else {\n resumeToken = targetData.resumeToken;\n }\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 { 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { 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 } from './shared_client_state';\nimport { TargetData } from './target_data';\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 | 'readonly-idempotent'\n | 'readwrite-idempotent'\n | 'readwrite-primary-idempotent';\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { 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, ProtoByteString, 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';\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-idempotent',\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(\n 'Locally write mutations',\n 'readwrite-idempotent',\n 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 )\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-idempotent',\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-idempotent',\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-idempotent',\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-idempotent',\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<ProtoByteString> {\n return this.persistence.runTransaction(\n 'Get last stream token',\n 'readonly-idempotent',\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: ProtoByteString): Promise<void> {\n return this.persistence.runTransaction(\n 'Set last stream token',\n 'readwrite-primary-idempotent',\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-idempotent',\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(\n 'Apply remote event',\n 'readwrite-primary-idempotent',\n 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.length > 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 )\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.length > 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.length === 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-idempotent',\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-idempotent',\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(\n 'read document',\n 'readonly-idempotent',\n txn => {\n return this.localDocuments.getDocument(txn, key);\n }\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-idempotent', 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\n ? 'readwrite-idempotent'\n : 'readwrite-primary-idempotent';\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(\n 'Execute query',\n 'readonly-idempotent',\n 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 /**\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-idempotent',\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-idempotent',\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-idempotent',\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-idempotent', 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-idempotent',\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 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 private readonly localStore: LocalStore\n ) {\n this.gcTask = null;\n }\n\n start(): 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();\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(): 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 this.localStore\n .collectGarbage(this.garbageCollector)\n .then(() => this.scheduleGC())\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 { User } from '../auth/user';\nimport { DatabaseInfo } from '../core/database_info';\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} from './lru_garbage_collector';\nimport { MutationQueue } from './mutation_queue';\nimport {\n Persistence,\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 { ClientId } 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 * IndexedDbs “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-idempotent',\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-idempotent', 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-idempotent',\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 );\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-idempotent',\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-idempotent',\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 // TODO(schmidt-sebastian): Simplify once all transactions are idempotent.\n const idempotent = mode.endsWith('idempotent');\n const readonly = mode.startsWith('readonly');\n const simpleDbMode = readonly\n ? idempotent\n ? 'readonly-idempotent'\n : 'readonly'\n : idempotent\n ? 'readwrite-idempotent'\n : '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 (\n mode === 'readwrite-primary' ||\n mode === 'readwrite-primary-idempotent'\n ) {\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 * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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// Untyped Number alias we can use to check for ES6 methods / properties.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NumberAsAny = Number as any;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Minimum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport const MIN_SAFE_INTEGER: number =\n NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n\n/**\n * Maximum safe integer in Javascript because of floating point precision.\n * Added to not rely on ES6 features.\n */\nexport const MAX_SAFE_INTEGER: number =\n NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n\n/**\n * Returns whether an number is an integer, uses native implementation if\n * available.\n * Added to not rely on ES6 features.\n * @param value The value to test for being an integer\n */\nexport const isInteger: (value: unknown) => boolean =\n NumberAsAny.isInteger ||\n (value =>\n typeof value === 'number' &&\n isFinite(value) &&\n Math.floor(value) === value);\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/**\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 isInteger(value) &&\n (value as number) <= MAX_SAFE_INTEGER &&\n (value as number) >= MIN_SAFE_INTEGER\n );\n}\n\n/**\n * Safely checks if the number is NaN.\n */\nexport function safeIsNaN(value: unknown): boolean {\n if (NumberAsAny.IsNaN) {\n return NumberAsAny.IsNaN(value);\n } else {\n return typeof value === 'number' && isNaN(value);\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 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 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 { Timestamp } from '../api/timestamp';\nimport { Query } from '../core/query';\nimport { BatchId, ProtoByteString } 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 { emptyByteString } from '../platform/platform';\nimport { assert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\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: ProtoByteString = emptyByteString();\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: ProtoByteString\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<ProtoByteString> {\n return PersistencePromise.resolve(this.lastStreamToken);\n }\n\n setLastStreamToken(\n transaction: PersistenceTransaction,\n streamToken: ProtoByteString\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 { 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 { fail } from '../util/assert';\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 { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\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 Persistence,\n PersistenceTransaction,\n PersistenceTransactionMode,\n PrimaryStateListener,\n ReferenceDelegate\n} from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { ReferenceSet } from './reference_set';\nimport { ClientId } from './shared_client_state';\nimport { TargetData } from './target_data';\n\nconst LOG_TAG = 'MemoryPersistence';\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: MemoryLruDelegate | MemoryEagerDelegate;\n\n static createLruPersistence(\n clientId: ClientId,\n params: LruParams\n ): MemoryPersistence {\n const factory = (p: MemoryPersistence): MemoryLruDelegate =>\n new MemoryLruDelegate(p, params);\n return new MemoryPersistence(clientId, factory);\n }\n\n static createEagerPersistence(clientId: ClientId): MemoryPersistence {\n const factory = (p: MemoryPersistence): MemoryEagerDelegate =>\n new MemoryEagerDelegate(p);\n return new MemoryPersistence(clientId, factory);\n }\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 private constructor(\n private readonly clientId: ClientId,\n referenceDelegateFactory: (\n p: MemoryPersistence\n ) => MemoryLruDelegate | MemoryEagerDelegate\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 class MemoryEagerDelegate implements ReferenceDelegate {\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","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { ProtoByteString, 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 { emptyByteString } from '../platform/platform';\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 */\nenum 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: ProtoByteString = emptyByteString();\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 = 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.length > 0,\n 'Trying to write mutation without a token'\n );\n\n const request: WriteRequest = {\n // Protos are typed with string, but we support UInt8Array on Node\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n streamToken: this.lastStreamToken as any,\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 { 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 * BatchID is a locally assigned ID for a batch of mutations that have been\n * applied.\n */\nexport type BatchId = number;\n\n/**\n * A locally-assigned ID used to refer to a target being watched via the\n * Watch service.\n */\nexport type TargetId = number;\n\nexport type ListenSequenceNumber = number;\n\n// TODO(b/35918695): In GRPC / node, tokens are Uint8Array. In WebChannel,\n// they're strings. We should probably (de-)serialize to a common internal type.\nexport type ProtoByteString = Uint8Array | string;\n\n/** The different states of a mutation batch. */\nexport type MutationBatchState = 'pending' | 'acknowledged' | 'rejected';\n\n/**\n * Describes the online state of the Firestore client. Note that this does not\n * indicate whether or not the remote store is trying to connect or not. This is\n * primarily used by the View / EventManager code to change their behavior while\n * offline (e.g. get() calls shouldn't wait for data from the server and\n * snapshot events should set metadata.isFromCache=true).\n */\nexport enum OnlineState {\n /**\n * The Firestore client is in an unknown online state. This means the client\n * is either not actively trying to establish a connection or it is currently\n * trying to establish a connection, but it has not succeeded or failed yet.\n * Higher-level components should not operate in offline mode.\n */\n Unknown,\n\n /**\n * The client is connected and the connections are healthy. This state is\n * reached after a successful connection and there has been at least one\n * successful message received from the backends.\n */\n Online,\n\n /**\n * The client is either trying to establish a connection but failing, or it\n * has been explicitly marked offline via a call to disableNetwork().\n * Higher-level components should operate in offline mode.\n */\n Offline\n}\n\n/** The source of an online state event. */\nexport enum OnlineStateSource {\n RemoteStore,\n SharedClientState\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 { 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.\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 { 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 enum ChangeType {\n Added,\n Removed,\n Modified,\n Metadata\n}\n\nexport interface DocumentViewChange {\n type: ChangeType;\n doc: Document;\n}\n\nexport 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 { ProtoByteString, TargetId } from '../core/types';\nimport {\n documentKeySet,\n DocumentKeySet,\n maybeDocumentMap,\n MaybeDocumentMap,\n targetIdSet\n} from '../model/collections';\nimport { emptyByteString } from '../platform/platform';\nimport { SortedSet } from '../util/sorted_set';\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: ProtoByteString,\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 emptyByteString(),\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 { SnapshotVersion } from '../core/snapshot_version';\nimport { ProtoByteString, 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 { emptyByteString } from '../platform/platform';\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';\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 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: ProtoByteString = emptyByteString(),\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: ProtoByteString = emptyByteString();\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(): ProtoByteString {\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: ProtoByteString): void {\n if (resumeToken.length > 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 { 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 { emptyByteString } from '../platform/platform';\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';\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.length > 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 emptyByteString(),\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 = emptyByteString();\n\n return this.localStore\n .setLastStreamToken(emptyByteString())\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 { 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 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\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 { 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 { ProtoByteString, 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 * 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 private emptyByteString(): ProtoByteString {\n if (this.options.useProto3Json) {\n return '';\n } else {\n return new Uint8Array(0);\n }\n }\n\n private unsafeCastProtoByteString(byteString: ProtoByteString): string {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString as string;\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 private toBytes(bytes: Blob): string {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n } else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\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 }\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 }\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 let result = fieldValue.ObjectValue.EMPTY;\n obj.forEach(map, (key, value) => {\n result = result.set(new FieldPath([key]), this.fromValue(value));\n });\n return result;\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.unsafeCastProtoByteString(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 const resumeToken =\n change.targetChange.resumeToken || this.emptyByteString();\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.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(\n targetData.resumeToken\n );\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 { 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 = 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 = 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 { 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 SyncEngines 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 = 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\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 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 onlineState.onlineState in OnlineState &&\n typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(\n onlineState.clientId,\n OnlineState[onlineState.onlineState as keyof typeof 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: OnlineState[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 { CredentialsProvider } from '../api/credentials';\nimport { User } from '../auth/user';\nimport { IndexedDbPersistence } from '../local/indexeddb_persistence';\nimport { IndexFreeQueryEngine } from '../local/index_free_query_engine';\nimport { LocalStore } from '../local/local_store';\nimport { MemoryPersistence } from '../local/memory_persistence';\nimport { Persistence } 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 { JsonProtoSerializer } from '../remote/serializer';\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 {\n LruGarbageCollector,\n LruParams,\n LruScheduler\n} from '../local/lru_garbage_collector';\nimport {\n MemorySharedClientState,\n SharedClientState,\n WebStorageSharedClientState\n} 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 class IndexedDbPersistenceSettings {\n constructor(\n readonly cacheSizeBytes: number,\n readonly synchronizeTabs: boolean\n ) {}\n\n lruParams(): LruParams {\n return LruParams.withCacheSize(this.cacheSizeBytes);\n }\n}\n\nexport class MemoryPersistenceSettings {}\n\nexport type InternalPersistenceSettings =\n | IndexedDbPersistenceSettings\n | MemoryPersistenceSettings;\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 // PORTING NOTE: SharedClientState is only used for multi-tab web.\n private sharedClientState!: SharedClientState;\n\n private lruScheduler?: LruScheduler;\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 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(persistenceSettings: InternalPersistenceSettings): 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(persistenceSettings, persistenceResult, user)\n .then(maybeLruGc => this.initializeRest(user, maybeLruGc))\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 persistenceSettings Settings object to configure offline persistence\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 initializePersistence(\n persistenceSettings: InternalPersistenceSettings,\n persistenceResult: Deferred<void>,\n user: User\n ): Promise<LruGarbageCollector | null> {\n if (persistenceSettings instanceof IndexedDbPersistenceSettings) {\n return this.startIndexedDbPersistence(user, persistenceSettings)\n .then(maybeLruGc => {\n persistenceResult.resolve();\n return maybeLruGc;\n })\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.startMemoryPersistence();\n });\n } else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\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 instanceof FirestoreError) {\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 * Starts IndexedDB-based persistence.\n *\n * @returns A promise indicating success or failure.\n */\n private startIndexedDbPersistence(\n user: User,\n settings: IndexedDbPersistenceSettings\n ): Promise<LruGarbageCollector> {\n // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n const persistenceKey = IndexedDbPersistence.buildStoragePrefix(\n this.databaseInfo\n );\n // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n const serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n\n return Promise.resolve().then(async () => {\n if (\n settings.synchronizeTabs &&\n !WebStorageSharedClientState.isAvailable(this.platform)\n ) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n 'IndexedDB persistence is only available on platforms that support LocalStorage.'\n );\n }\n\n const lruParams = settings.lruParams();\n\n this.sharedClientState = settings.synchronizeTabs\n ? new WebStorageSharedClientState(\n this.asyncQueue,\n this.platform,\n persistenceKey,\n this.clientId,\n user\n )\n : new MemorySharedClientState();\n\n const persistence = await IndexedDbPersistence.createIndexedDbPersistence(\n {\n allowTabSynchronization: settings.synchronizeTabs,\n persistenceKey,\n clientId: this.clientId,\n platform: this.platform,\n queue: this.asyncQueue,\n serializer,\n lruParams,\n sequenceNumberSyncer: this.sharedClientState\n }\n );\n\n this.persistence = persistence;\n return persistence.referenceDelegate.garbageCollector;\n });\n }\n\n /**\n * Starts Memory-backed persistence. In practice this cannot fail.\n *\n * @returns A promise that will successfully resolve.\n */\n private startMemoryPersistence(): Promise<LruGarbageCollector | null> {\n this.persistence = MemoryPersistence.createEagerPersistence(this.clientId);\n this.sharedClientState = new MemorySharedClientState();\n return Promise.resolve(null);\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(\n user: User,\n maybeLruGc: LruGarbageCollector | null\n ): 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\n if (maybeLruGc) {\n // We're running LRU Garbage collection. Set up the scheduler.\n this.lruScheduler = new LruScheduler(\n maybeLruGc,\n this.asyncQueue,\n this.localStore\n );\n }\n\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 (this.lruScheduler) {\n if (isPrimary && !this.lruScheduler.started) {\n this.lruScheduler.start();\n } else if (!isPrimary) {\n this.lruScheduler.stop();\n }\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 if (this.lruScheduler) {\n this.lruScheduler.stop();\n }\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 * 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 { 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 { 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 { 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 */\nenum 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 let updateData = ObjectValue.EMPTY;\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 = updateData.set(path, parsedValue);\n }\n }\n });\n\n const mask = FieldMask.fromSet(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\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 let updateData = ObjectValue.EMPTY;\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 = updateData.set(path, parsedValue);\n }\n }\n }\n\n const mask = FieldMask.fromSet(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n }\n\n /**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */\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 * 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 {\n FirestoreClient,\n IndexedDbPersistenceSettings,\n InternalPersistenceSettings,\n MemoryPersistenceSettings\n} 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 { IndexedDbPersistence } from '../local/indexeddb_persistence';\nimport { LruParams } from '../local/lru_garbage_collector';\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 { Rejecter, Resolver } from '../util/promise';\nimport { Deferred } 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 _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 constructor(\n databaseIdOrApp: FirestoreDatabase | FirebaseApp,\n authProvider: Provider<FirebaseAuthInternalName>\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._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(\n new IndexedDbPersistenceSettings(\n this._settings.cacheSizeBytes,\n synchronizeTabs\n )\n );\n }\n\n clearPersistence(): Promise<void> {\n const persistenceKey = IndexedDbPersistence.buildStoragePrefix(\n this.makeDatabaseInfo()\n );\n const deferred = new Deferred<void>();\n this._queue.enqueueAndForgetEvenAfterShutdown(async () => {\n try {\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 await IndexedDbPersistence.clearPersistence(persistenceKey);\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 MemoryPersistenceSettings());\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 persistenceSettings: InternalPersistenceSettings\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(persistenceSettings);\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 validateArgType('CollectionReference.add', 'object', 1, value);\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 { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\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';\nimport { Component, ComponentType } from '@firebase/component';\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 */\nexport function configureForFirebase(firebase: FirebaseNamespace): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'firestore',\n container => {\n const app = container.getProvider('app').getImmediate()!;\n return new Firestore(app, container.getProvider('auth-internal'));\n },\n ComponentType.PUBLIC\n ).setServiceProps(shallowCopy(firestoreNamespace))\n );\n}\n\n/**\n * Exports the Firestore namespace into the provided `exportObject` object under\n * the key 'firestore'. This is used for wrapped binary that exposes Firestore\n * as a goog module.\n */\nexport function configureForStandalone(exportObject: {\n [key: string]: {};\n}): void {\n const copiedNamespace = shallowCopy(firestoreNamespace);\n // Unlike the use with Firebase, the standalone allows the use of the\n // constructor, so export it's internal class\n copiedNamespace['Firestore'] = Firestore;\n exportObject['firestore'] = copiedNamespace;\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 { 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 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 // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\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 !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 readonly emptyByteString = '';\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","/**\n * @license\n * Copyright 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 firebase from '@firebase/app';\nimport { configureForFirebase } from './src/platform/config';\nimport './src/platform_browser/browser_init';\n\nimport * as types from '@firebase/firestore-types';\nimport { FirebaseNamespace } from '@firebase/app-types';\n\nimport { name, version } from './package.json';\n\nexport function registerFirestore(instance: FirebaseNamespace): void {\n configureForFirebase(instance);\n instance.registerVersion(name, version);\n}\n\nregisterFirestore(firebase);\n\ndeclare module '@firebase/app-types' {\n interface FirebaseNamespace {\n firestore?: {\n (app?: FirebaseApp): types.FirebaseFirestore;\n Blob: typeof types.Blob;\n CollectionReference: typeof types.CollectionReference;\n DocumentReference: typeof types.DocumentReference;\n DocumentSnapshot: typeof types.DocumentSnapshot;\n FieldPath: typeof types.FieldPath;\n FieldValue: typeof types.FieldValue;\n Firestore: typeof types.FirebaseFirestore;\n GeoPoint: typeof types.GeoPoint;\n Query: typeof types.Query;\n QueryDocumentSnapshot: typeof types.QueryDocumentSnapshot;\n QuerySnapshot: typeof types.QuerySnapshot;\n Timestamp: typeof types.Timestamp;\n Transaction: typeof types.Transaction;\n WriteBatch: typeof types.WriteBatch;\n setLogLevel: typeof types.setLogLevel;\n };\n }\n interface FirebaseApp {\n firestore?(): types.FirebaseFirestore;\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 { 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 } & 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 } 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\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 }\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_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n } else {\n return new FailRequest(errorsExports.appDeleted());\n }\n }\n\n /**\n * Stop running requests and prevent more from being created.\n */\n deleteApp(): 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\n/**\n * @template T\n */\nexport function makeRequest<T>(\n requestInfo: RequestInfo<T>,\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 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_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 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 SET_CHECKOUT_OPTION = 'set_checkout_option',\n SHARE = 'share',\n SIGN_UP = 'sign_up',\n TIMING_COMPLETE = 'timing_complete',\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 { 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';\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 => console.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 => console.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 * 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 } 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 };\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","ACCESSORS","argument0","argument1","addTrap","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","__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","LogLevel","ComponentContainer","provider","getProvider","isComponentSet","setComponent","providers","addComponent","defaultLogHandler","logType","logLevel","toISOString","DEBUG","VERBOSE","log","INFO","info","WARN","ERROR","defaultLogLevel","Logger","_logLevel","_logHandler","ERRORS","ERROR_FACTORY","PLATFORM_LOG_STRING","appName","logger","FirebaseAppImpl","checkDestroyed_","automaticDataCollectionEnabled_","name_","options_","firebase_","removeApp","getProviders","isDeleted_","getImmediate","clearInstance","debug","addOrOverwriteComponent","config","automaticDataCollectionEnabled","_addComponent","components","createFirebaseNamespaceCore","firebaseAppImpl","apps","__esModule","initializeApp","rawConfig","app","registerVersion","libraryKeyOrName","variant","library","libraryMismatch","versionMismatch","warning","registerComponent","useAsService","componentName","serviceNamespace","appArg","_getService","firebase","createFirebaseNamespace","extendNamespace","PlatformLoggerService","getComponent","isVersionServiceProvider","logString","sdkVersion","firebaseNamespace","isNode","$jscomp.defineProperty","$jscomp.global","$jscomp.arrayIteratorImpl","$jscomp.polyfill","h","N","wa","ld","$jscomp.makeIterator","goog","goog.global","goog.isBoolean","goog.NONCE_PATTERN_","goog.cspNonce_","goog.typeOf","className","goog.isNull","goog.isArray","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","childCtor.base","me","methodName","opt_msg","goog.debug.Error","stack","goog.asserts.AssertionError","messagePattern","messageArgs","returnString","subLast","splitParts","opt_message","put","item","goog.inherits","goog.async.FreeList","goog.async.WorkQueue.freelist_","goog.async.WorkItem","goog.dom.asserts.assertIsElementType_","typename","doc","win","ex","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.isString","goog.array.forEach","opt_obj","l","arr2","goog.array.map","goog.array.some","goog.array.contains","goog.array.remove","rv","goog.array.removeAllIf","removedCount","goog.array.concat","goog.array.toArray","goog.object.forEach","goog.object.isEmpty","goog.object.clone","goog.object.PROTOTYPE_FIELDS_","goog.object.PROTOTYPE_FIELDS_.length","opt_token","opt_content","goog.string.Const.GOOG_STRING_CONSTRUCTOR_TOKEN_PRIVATE_","goog.string.Const.TYPE_MARKER_","stringConst","goog.string.Const","goog.string.Const.prototype.getTypedStringValue","goog.string.Const.prototype.toString","goog.string.Const.EMPTY","goog.html.TrustedResourceUrl","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.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.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_","safeUrl","goog.html.SafeUrl","goog.html.SafeUrl.prototype.getTypedStringValue","goog.html.SafeUrl.prototype.toString","goog.html.SAFE_URL_PATTERN_","goog.html.SafeUrl.INNOCUOUS_STRING","goog.labs.userAgent.util.userAgent_","goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse","goog.global.navigator","xb","goog.labs.userAgent.util.matchUserAgent","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_","Kb","Nb","goog.html.SafeHtml.EMPTY","subsArguments","goog.string.htmlEscape","goog.string.internal.ALL_RE_.test","goog.async.throwException","exception","goog.global.setTimeout","Channel","goog.dom.safe.setIframeSrc","goog.html.TrustedResourceUrl.createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse","goog.html.TrustedResourceUrl.unwrapTrustedScriptURL","goog.html.SafeHtml.unwrapTrustedHTML","origin","cb","script","script.onreadystatechange","tail","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","goog.async.WorkQueue.prototype.remove","goog.async.run.workQueue_.remove","goog.async.WorkQueue.freelist_.put","resolver","goog.Promise.State_.PENDING","goog.nullFunction","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","goog.Promise.reject","opt_reason","goog.Promise.resolveThen_","goog.Promise.maybeThen_","goog.async.run","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.Thenable.isImplementedBy","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_","goog.Promise.prototype.thenAlways","addCallbackEntry_","goog.Promise.prototype.thenCatch","goog.Promise.prototype.cancel","goog.Promise.prototype.cancelInternal_","parent_","childCount","childEntry","beforeChildEntry","childPromise","cancelInternal_","removeEntryAfter_","popEntry_","executeCallback_","goog.Promise.CancellationError","goog.Promise.prototype","goog.Promise.prototype.unblockAndFulfill_","goog.Promise.prototype.unblockAndReject_","goog.Promise.prototype.executeCallbacks_","goog.Promise.handleRejection_","goog.debug.Error.call","goog.Disposable","goog.Disposable.MONITORING_MODE","OFF","goog.Disposable.prototype.dispose","goog.Disposable.MonitoringMode.OFF","goog.reflect.sinkValue","goog.Disposable.prototype.disposeInternal","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","Ac","Fc","goog.userAgent.isVersionOrHigherCache_","valueFn","cacheObj","order","v1Subs","v2Subs","subCount","subIdx","v1Sub","v2Sub","v1Comp","v2Comp","parseInt","goog.debug.freezeInternal_","HAS_W3C_EVENT_SUPPORT","goog.userAgent.DOCUMENT_MODE","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.prototype.removeByKey","markAsRemoved","goog.events.ListenerMap.findListenerIndex_","listenerArray","opt_useCapture","opt_listenerScope","listenerObj","goog.events.ListenerMap","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.Disposable.call","goog.events.EventTarget.prototype.listen","goog.events.EventTarget.prototype.listenOnce","goog.events.EventTarget.prototype.fireListeners","unlistenByKey","opt_delay","goog.Timer.promise","delay","timerKey","thenCatch","goog.Timer.callOnce","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","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","Pc","rd","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","prefix","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","Cd","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","sb","encodedKey","param","CAN_ADD_NAME_OR_TYPE_ATTRIBUTES","goog.dom.getElementHelper_","goog.dom.setProperties","goog.dom.DIRECT_ATTRIBUTE_MAP_.hasOwnProperty","goog.dom.DIRECT_ATTRIBUTE_MAP_","cellpadding","cellspacing","colspan","frameborder","height","maxlength","nonce","role","rowspan","usemap","valign","width","tagName","opt_attributes","attributes","goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES","tagNameArr","goog.dom.append_","childHandler","child","startIndex","goog.dom.isNodeList","goog.json.Serializer.prototype.serializeInternal","serializeInternal","serializeArray","serializeString_","serializeObject_","serialize","goog.json.Serializer","goog.json.Serializer.charToJsonCharCache_","\"","\\","/","\b","\f","\n","\r","\t","\u000b","goog.json.Serializer.charsToReplace_","ua","fireauth.util.getUserAgentString","fireauth.util.getCurrentUrl","fireauth.util.goTo","opt_window","finalUrl","goog.html.SafeUrl.unwrapTrustedURL","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","safeLinkRef","goog.html.SAFE_URL_PATTERN_.test","click","newWin","sanitizedLinkRef","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.isLocalStorageNotSynchronized","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_","Ye","fireauth.object.setReadonlyProperty","fireauth.object.setReadonlyProperties","fireauth.object.makeReadonlyCopy","fireauth.object.unsafeCreateReadOnlyCopy","copy","email","fireauth.ActionCodeInfo.ServerFieldName.EMAIL","newEmail","fireauth.ActionCodeInfo.ServerFieldName.NEW_EMAIL","fireauth.ActionCodeInfo.ServerFieldName.REQUEST_TYPE","operation","fireauth.ActionCodeInfo.Operation.EMAIL_SIGNIN","fireauth.ActionCodeInfo.DataField.FROM_EMAIL","fireauth.ActionCodeInfo.DataField.EMAIL","fireauth.ActionCodeInfo.PropertyName.OPERATION","fireauth.ActionCodeInfo.PropertyName.DATA","EMAIL_SIGNIN","EMAIL","NEW_EMAIL","REQUEST_TYPE","FROM_EMAIL","DATA","OPERATION","fireauth.AuthError","fireauth.AuthError.ERROR_CODE_PREFIX","fireauth.AuthError.MESSAGES_","fireauth.AuthError.ERROR_CODE_PREFIX.length","fireauth.AuthError.prototype.toPlainObject","fireauth.AuthError.prototype.toJSON","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_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_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","MISSING_ANDROID_PACKAGE_NAME","MISSING_AUTH_DOMAIN","MISSING_APP_CREDENTIAL","MISSING_CODE","MISSING_CONTINUE_URI","MISSING_IFRAME_START","MISSING_IOS_BUNDLE_ID","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","TENANT_ID_MISMATCH","TIMEOUT","TOKEN_EXPIRED","TOO_MANY_ATTEMPTS_TRY_LATER","UNAUTHORIZED_DOMAIN","UNSUPPORTED_PERSISTENCE","UNSUPPORTED_TENANT_OPERATION","USER_CANCELLED","USER_DELETED","USER_DISABLED","USER_MISMATCH","USER_SIGNED_OUT","WEAK_PASSWORD","WEB_STORAGE_UNSUPPORTED","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","signIn","verifyEmail","VERIFY_EMAIL","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.byteToCharMap_","goog.crypt.base64.charToByteMap_","goog.crypt.base64.decodeStringInternal_","pushByte","getByte","default_val","nextCharIndex","goog.crypt.base64.init_","goog.crypt.base64.ENCODED_VALS.charAt","goog.crypt.base64.ENCODED_VALS_WEBSAFE.charAt","tokenString","fireauth.IdToken.parseIdTokenClaims","fireauth.IdToken","padLen","fields","jsonInfo","goog.crypt.base64.decodeString","fireauth.IdToken.prototype.getTenantId","fireauth.IdToken.prototype.isAnonymous","Vf","fireauth.constants.Endpoint","PRODUCTION","firebaseAuthEndpoint","secureTokenEndpoint","STAGING","TEST","opt_id","endpointKey","firebaseEndpoint","endpoint","fireauth.constants.getEndpointConfig","fireauth.idp.RESERVED_OAUTH1_PARAMS","fireauth.idp.RESERVED_OAUTH2_PARAMS","fireauth.idp.Settings","FACEBOOK","languageParam","popupWidth","popupHeight","providerId","reservedOAuthParameters","GITHUB","GOOGLE","TWITTER","APPLE","resp","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.AuthCredential.verifyTokenResponseUid","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","PHONE","allowedKeys","fireauth.PhoneAuthCredential","fireauth.PhoneAuthCredential.prototype.makeVerifyPhoneNumberRequest_","temporaryProof","phoneNumber","sessionInfo","fireauth.PhoneAuthProvider","opt_auth","verificationId","verificationCode","accessTokenSecret","rawNonce","fireauth.OAuthProvider","fireauth.AuthProvider.checkIfOAuthSupported","opt_eventId","opt_urlResponse","opt_sessionId","opt_error","opt_postBody","opt_tenantId","rawResponse","fireauth.AuthEvent","fireauth.AuthError.fromPlainObject","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","applicationVerifier","fireauth.RpcHandler.prototype.sendVerificationCode","fireauth.RpcHandler.ApiMethod.SEND_VERIFICATION_CODE","recaptchaToken","PHONE_SIGN_IN_METHOD","fireauth.AuthEvent.prototype.getUid","fireauth.AuthEvent.prototype.getTenantId","fireauth.AuthEvent.prototype.toPlainObject","eventId","urlResponse","sessionId","hh","fireauth.UniversalLinkSubscriber.instance_","goog.string.subs","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","level","msg","loggerName","opt_time","opt_sequenceNumber","goog.debug.Logger","goog.debug.Logger.Level","fireauth.InvalidOriginError","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","lh","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","nh","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_","opt_xmlHttpFactory","goog.net.XhrIo.ResponseType.DEFAULT","Bh","goog.net.FetchXmlHttp.prototype.open","OPENED","goog.net.FetchXmlHttp.prototype.send","opt_data","requestInit","cache","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","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_","Gh","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_","timeout_","goog.net.jsloader.cleanup_","goog.net.jsloader.Error","goog.net.jsloader.ErrorCode.TIMEOUT","goog.net.jsloader.DEFAULT_TIMEOUT","script.onerror","goog.net.jsloader.ErrorCode.LOAD_ERROR","charset","goog.dom.safe.setScriptSrc","ja","goog.NONCE_PATTERN_.test","goog.net.jsloader.getScriptParentElement_","headElements","scriptNode","goog.dom.TagName.SCRIPT","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.DEFAULT_FIREBASE_TIMEOUT_","fireauth.RpcHandler.DEFAULT_FIREBASE_HEADERS_","fireauth.XmlHttpFactory.prototype.createInstance","fireauth.XmlHttpFactory.prototype.internalGetOptions","si","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.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_","displayName","photoUrl","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_","ni","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","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","GET_ACCOUNT_INFO","GET_EMAIL_SIGNIN_CODE","fireauth.RpcHandler.validateEmailSignInCodeRequest_","GET_EMAIL_VERIFICATION_CODE","fireauth.RpcHandler.validateEmailVerificationCodeRequest_","GET_OOB_CODE","fireauth.RpcHandler.validateOobCodeRequest_","GET_PROJECT_CONFIG","cachebuster","httpMethod","GET","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","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_","fireauth.RpcHandler.prototype.invokeRpc_","fireauth.object.hasNonEmptyFields","opt_fields","field","POST","fireauth.RpcHandler.prototype.requestFirebaseEndpoint","opt_customErrorMap","opt_cachebuster","getApiKey","setParameterValue","isGet","sendXhr_","fireauth.RpcHandler.getDeveloperError_","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_","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","fireauth.iframeclient.IframeUrlBuilder","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","vj","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","Cj","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","Oj","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","Lj","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","Yj","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","Zj","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","ak","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","dk","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","ek","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","mk","qk","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","pk","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_","Fk","numHashBlocks","initHashBlocks","goog.crypt.Sha2.BLOCKSIZE_","goog.crypt.Sha2.Kx_","goog.crypt.Sha2.K_","goog.crypt.Sha2","Hk","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.storage.OAuthHandlerManager","fireauth.CordovaHandler.getError_","fireauth.CordovaHandler.prototype.computeSecureHash_","sha256","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","fireauth.UniversalLinkSubscriber.prototype.subscribe","this.masterCb_","fireauth.CordovaHandler.prototype.getPartialStoredEvent_","fireauth.storage.AuthEventManager.prototype.getAuthEvent","fireauth.storage.AuthEventManager.Keys.AUTH_EVENT","fireauth.storage.PendingRedirectManager","Pk","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","setAppVerificationDisabledForTesting","credentialResolver","auth","appVerifier","verifyPhoneNumber","fireauth.ConfirmationResult","expirationTime","authTime","issuedAtTime","signInProvider","fireauth.ProactiveRefresh","retryPolicy","getWaitDuration","RETRIAL_MIN_WAIT","RETRIAL_MAX_WAIT","fireauth.ProactiveRefresh.prototype.getNextRun_","hasSucceeded","fireauth.StsTokenManager","fireauth.StsTokenManager.prototype.parseServerResponse","refreshToken","fireauth.StsTokenManager.calcOffsetTimestamp_","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.UserEvent","opt_properties","appOptions","stsTokenResponse","opt_accountInfo","clientFullVersion","setLastAccessToken_","setAccountInfo","fireauth.AuthEventManager.getManager","fireauth.AuthUser.prototype.initializeProactiveRefreshUtility_","waitInterval","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","accountInfo","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.AdditionalUserInfo.fromPlainObject","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_","stsTokenManagerResponse","firebaseUser","fireauth.AuthUser","fireauth.storage.RedirectUserManager","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","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","Q","fireauth.AuthUser.prototype.reload","fireauth.AuthUser.returnNothing_","fireauth.AuthUser.prototype","fireauth.AuthUser.prototype.getIdTokenResult","fireauth.IdTokenResult","fireauth.AuthUser.prototype.getIdToken","fireauth.AuthUser.prototype.parseAccountInfo_","users","linkedAccounts","providerInfo","fireauth.AuthUserInfo","extractLinkedAccounts_","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","getAuth_","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.ActionCodeSettings","fireauth.AuthUser.prototype.toJSON","fireauth.AuthUser.prototype.toPlainObject","stsTokenManager","redirectEventId","fireauth.object.makeWritableCopy","fireauth.storage.RedirectUserManager.prototype.removeRedirectUser","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","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.AuthSettings","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","SIGN_IN","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","fireauth.Auth.LanguageCodeChangeEvent","fireauth.Auth.FrameworkChangeEvent","Km","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","getExpirationTime","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.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.ActionCodeInfo","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.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","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","nn","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.applicationVerifier","fireauth.args.or","optionA","optionB","protObj","fnMap","obfuscatedFnName","unobfuscatedFnName","fireauth.exportlib.wrapMethodWithArgumentVerifier_","fireauth.exportlib.exportPrototypeProperties","propMap","obfuscatedPropName","unobfuscatedPropName","getter","expectedArg","fireauth.exportlib.exportFunction","parentObj","func","opt_expectedArgs","argumentsAsArray","shortName","fireauth.exportlib.extractMethodNameFromFullPath_","fireauth.exportlib.exportPrototypeMethods","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","execute","getResponse","thenAlways","appVerificationDisabled","confirm","fireauth.AuthCredential","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","verify","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.string.internal.isEmptyOrWhitespace","Ia","Na","G","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","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","documentMode","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","createWebChannelTransport","ErrorCode","EventType","WebChannel","XhrIo","getLogLevel","FirebaseLogLevel","SILENT","setLogLevel","newLevel","argToString","PlatformSupport","getPlatform","formatJSON","failure","emptyByteString","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","makeConstructorPrivate","cls","optionalMessage","PublicConstructor","FirestoreError","staticProperty","defaulted","defaultValue","forEachNumber","validateNoArgs","functionName","formatPlural","validateExactNumberOfArgs","numberOfArgs","validateAtLeastNumberOfArgs","minNumberOfArgs","validateBetweenNumberOfArgs","maxNumberOfArgs","validateArgType","validateType","validateOptionalArgType","validateNamedType","optionName","validateNamedOptionalType","validateOptionalArrayElements","typeDescription","valueDescription","validateArrayElements","validateNamedOptionalPropertyEquals","inputName","expectedDescription","expected_1","actualDescription","validateNamedPropertyEquals","isPlainObject","customObjectName","tryGetCustomObjectType","validateDefined","validateOptionNames","optionNames","obj.forEach","invalidClassError","validatePositiveNumber","AutoId","autoId","primitiveComparator","arrayEquals","isEqual","immediateSuccessor","assertUint8ArrayAvailable","assertBase64Available","base64Available","char","_binaryString","toBase64","binaryString","PublicBlob","databaseId","ssl","forceLongPolling","DEFAULT_DATABASE_NAME","DatabaseId","projectId","ListenSequence","externalPreviousValue","nextValue","writeNewSequenceNumber","sequenceNumberSyncer","sequenceNumberHandler","sequenceNumber","setPreviousValue","writeSequenceNumber","DOCUMENT_KEY_NAME","BasePath","nameOrPath","construct","potentialChild","end","p1","p2","ResourcePath","toArray","canonicalString","identifierRegExp","FieldPath","isValidIdentifier","current","addCurrentSegment","inBackticks","DocumentKey","collectionId","k1","k2","fromString","isDocumentKey","TimerId","DelayedOperation","asyncQueue","timerId","delayMs","removalCallback","delayedOp","timerHandle","handleDelayElapsed","enqueueAndForget","targetTimeMs","AsyncQueue","_isShuttingDown","enqueue","verifyNotFailed","enqueueInternal","enqueueEvenAfterShutdown","newTail","operationInProgress","log.error","timerIdsToSkip","createAndSchedule","removedOp","removeDelayedOperation","delayedOperations","lastTimerId","drain","All","containsDelayedOperation","skipDelay","escapeChar","encodedSeparatorChar","encodedNul","encodedEscape","encode","encodeSeparator","encodeSegment","resultBuf","EMPTY_PATH","lastReasonableEscapeIndex","segmentBuilder","currentPiece","Timestamp","fromMillis","milliseconds","seconds","toMillis","nanoseconds","SnapshotVersion","_compareTo","prunedNodes","descriptions","EMPTY","nodeStack","isReverse","fixUp","isRed","moveRedLeft","removeMin","rotateRight","moveRedRight","rotateLeft","colorFlip","SortedSet","elem","range","SortedSetIterator","thisIt","otherIt","thisElem","otherElem","targetId","EMPTY_MAYBE_DOCUMENT_MAP","maybeDocumentMap","nullableMaybeDocumentMap","EMPTY_DOCUMENT_MAP","documentMap","EMPTY_DOCUMENT_VERSION_MAP","documentVersionMap","EMPTY_DOCUMENT_KEY_SET","documentKeySet","keys_1","EMPTY_TARGET_ID_SET","targetIdSet","MutationBatch","docKey","maybeDoc","batchResult","mutationResults","mutations","mutation","mutationResult","applyToRemoteDocument","baseMutations","applyToLocalView","localWriteTime","baseDoc","maybeDocs","mutatedDocuments","mutatedDocument","batchId","misc.arrayEquals","MutationBatchResult","batch","commitVersion","streamToken","versionMap","docVersions","PersistencePromise","nextFn","catchFn","callbackAttached","isDone","wrapFailure","wrapSuccess","nextCallback","catchCallback","wrapUserFunction","expectedCount","resolvedCount","predicates","isTrue","predicates_1","waitFor","LOG_TAG","SimpleDb","schemaConverter","indexedDB","onsuccess","onblocked","onupgradeneeded","oldVersion","createOrUpgrade","SCHEMA_VERSION","toPromise","wrapRequest","deleteDatabase","isMockPersistence","iOSVersion","getIOSVersion","isUnsupportedIOS","androidVersion","getAndroidVersion","isUnsupportedAndroid","USE_MOCK_PERSISTENCE","iOSVersionRegex","androidVersionRegex","versionChangeListener","onversionchange","objectStores","transactionFn","readonly","idempotent","endsWith","attemptNumber","SimpleDbTransaction","transactionFnResult","abort","completionPromise","retryable","error_1","IterationController","shouldStop","nextKey","dbCursor","objectStoreNames","completionDeferred","aborted","storeName","SimpleDbStore","oncomplete","onabort","checkForAndReportiOSError","keyOrValue","indexOrRange","iterateCursor","keysOnly","control","optionsOrCallback","cursorRequest","primaryKey","shouldContinue","continue","controller","userResult","userPromise","skipToKey","direction","openKeyCursor","openCursor","reportedIOSError","IOS_ERROR","newError_1","IndexedDbMutationQueue","serializer","indexManager","referenceDelegate","isAuthenticated","IDBKeyRange","bound","userId","mutationsStore","DbMutationBatch","userMutationsIndex","getMutationQueueMetadata","lastStreamToken","convertStreamToken","mutationQueuesStore","documentStore","documentMutationsStore","mutationStore","dbBatch","toDbMutationBatch","collectionParents","mutations_1","DbDocumentMutation","popLast","PLACEHOLDER","addToCollectionParentIndex","addOnCommittedListener","documentKeysByBatchId","fromDbMutationBatch","lookupMutationBatch","nextBatchId","lowerBound","foundBatch","upperBound","loadAll","dbBatches","documentKey","indexPrefix","prefixForPath","indexStart","userID","encodedPath","EncodedResourcePath.decode","documentKeys","uniqueBatchIDs","batchID","lookupMutationBatches","isDocumentQuery","isCollectionGroupQuery","immediateChildrenLength","isPrefixOf","batchIDs","removeMutationBatch","simpleDbTransaction","removedDocuments","removeCachedMutationKeys","removeMutationReference","checkEmpty","startRange","prefixForUser","danglingMutationReferences","mutationQueueContainsKey","DbMutationQueue","indexTxn","only","numDeleted","removePromise","IndexedDbPersistence","getStore","GeneratorIds","TargetIdGenerator","nextId","seek","generatorId","QueryCache","SyncEngine","seed","IndexedDbTargetCache","retrieveMetadata","highestTargetId","targetIdGenerator","after","saveMetadata","fromTimestamp","lastRemoteSnapshotVersion","getHighestListenSequenceNumber","highestListenSequenceNumber","toTimestamp","targetData","saveTargetData","targetCount","updateMetadataFromTargetData","removeMatchingKeysForTargetId","targetsStore","activeTargetIds","fromDbTarget","removeTargetData","DbTargetGlobal","globalTargetStore","toDbTarget","updated","canonicalId","DbTarget","queryTargetsIndexName","found","documentTargetStore","EncodedResourcePath.encode","DbTargetDocument","addReference","removeReference","documentTargetsIndex","forTargetCache","targetGlobal","FieldMask","fieldsAsSet","fieldPath","fieldMaskPath","FieldTransform","transform","MutationType","transformResults","Precondition","exists","updateTime","Document","isNone","misc.equals","Mutation","SetMutation","verifyKeyMatches","hasCommittedMutations","precondition","isValidFor","getPostMutationVersion","hasLocalMutations","PatchMutation","UnknownDocument","patchDocument","fieldMask","ObjectValue","patchObject","Patch","TransformMutation","requireDocument","serverTransformResults","transformObject","localTransformResults","baseObject","fieldTransforms","fieldTransform","existingValue","coercedValue","computeBaseValue","Transform","DeleteMutation","NoDocument","forDeletedDoc","Delete","TypeOrder","ServerTimestampBehavior","VerifyMutation","Verify","FieldValueOptions","timestampsInSnapshots","serverTimestamps","Estimate","Previous","serverTimestampBehavior","FieldValue","typeOrder","NullValue","defaultCompareTo","BooleanValue","internalValue","TRUE","FALSE","NumberValue","numericComparator","numericEquals","IntegerValue","DoubleValue","NaN","StringValue","TimestampValue","toDate","ServerTimestampValue","approximateByteSize","BlobValue","_approximateByteSize","RefValue","GeoPointValue","it1","it2","next1","next2","setChild","firstSegment","popFirst","pathSegment","currentPath","nestedFields","nestedPath","fromSet","ArrayValue","minLength","totalSize","MaybeDocument","d1","d2","objectValue","fieldValueCache","canonicalPath","protoValue","getProtoField","converter","result_1","mapValue","v1","v2","ObjectMap","mapKeyFn","matches_1","objUtil.forEach","entries_1","objUtil.isEmpty","RemoteDocumentChangeBuffer","_readTime","maybeDocument","readTime","assertNotApplied","bufferedEntry","getFromCache","getAllFromCache","changesApplied","applyChanges","IndexedDbRemoteDocumentCache","remoteDocumentsStore","dbKey","sizeDelta","getMetadata","byteSize","dbRemoteDoc","maybeDecodeDocument","dbDocumentSize","forEachDbEntry","sizeMap","maybeDocuments","keyIter","potentialKeyRaw","potentialKey","fromSegments","skip","sinceReadTime","immediateChildrenPathLength","iterationOptions","collectionKey","readTimeKey","toDbTimestampKey","DbRemoteDocument","collectionReadTimeIndex","fromDbRemoteDocument","changedDocs","lastReadTime","documentsStore","readTimeIndex","fromDbTimestampKey","trackRemovals","documentGlobalStore","DbRemoteDocumentGlobal","class_1","previousSize","documentSizes","documentCache","toDbRemoteDocument","addEntry","deletedDoc","removeEntry","updateMetadata","getSizedEntry","getResult","getSizedEntries","unknownDocument","noDocument","MemoryIndexManager","collectionPath","collectionParentIndex","getEntries","MemoryCollectionParentIndex","lastSegment","existingParents","added","SchemaConverter","fromVersion","toVersion","createObjectStore","DbPrimaryClient","createPrimaryClientStore","autoIncrement","createIndex","userMutationsKeyPath","unique","createMutationQueue","createQueryCache","createRemoteDocumentCache","deleteObjectStore","dropQueryCache","globalStore","writeEmptyTargetGlobalEntry","existingMutations","v3MutationsStore","writeAll","upgradeMutationBatchSchemaAndMigrateData","DbClientMetadata","createClientMetadataStore","removeAcknowledgedMutations","createDocumentGlobalStore","addDocumentGlobal","ensureSequenceNumbers","createCollectionParentIndex","dropRemoteDocumentChangesStore","remoteDocumentStore","readTimeIndexPath","collectionReadTimeIndexPath","createRemoteDocumentReadTimeIndex","byteCount","queuesStore","queues","lastAcknowledgedBatchId","currentSequenceNumber","docSentinelKey","sentinelKey","maybeSentinel","writeSentinelKey","collectionParentsStore","DbCollectionParent","pathSegments","ownerId","allowTabSynchronization","leaseTimestampMs","localWriteTimeMs","resumeToken","lastListenSequenceNumber","lastLimboFreeSnapshotVersion","documentTargetsKeyPath","queryTargetsKeyPath","clientId","updateTimeMs","networkEnabled","inForeground","TargetPurpose","ALL_STORES","IndexedDbIndexManager","collectionParentsCache","collectionParent","parentPaths","TargetData","purpose","snapshotVersion","LocalSerializer","remoteDoc","remoteSerializer","fromDocument","fromDbTimestamp","dbReadTime","toDocument","readTime_1","toDbTimestamp","DbNoDocument","readTime_2","DbUnknownDocument","dbTimestampKey","DbTimestamp","dbTimestamp","serializedBaseMutations","toMutation","serializedMutations","fromMutation","encodedKeys","encodedPaths","encodedPaths_1","dbTarget","dbQuery","documents","fromDocumentsTarget","fromQueryTarget","Listen","queryProto","dbLastLimboFreeTimestamp","toDocumentsTarget","toQueryTarget","LocalDocumentsView","mutationQueue","getAllMutationBatchesAffectingDocumentKey","batches","getDocumentInternal","inBatches","remoteDocumentCache","inBatches_1","docs","localView","batches_1","getLocalViewOfDocuments","baseDocs","getAllMutationBatchesAffectingDocumentKeys","applyLocalMutationsToDocuments","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","docPath","getDocument","collectionGroup","getCollectionParents","parents","collectionQuery","asCollectionQueryAtPath","mutationBatches","getDocumentsMatchingQuery","queryResults","getAllMutationBatchesAffectingQuery","matchingMutationBatches","addMissingBaseDocuments","mergedDocuments","mutationBatches_1","mutatedDoc","existingDocuments","missingBaseDocEntriesForPatching","matchingMutationBatches_1","missingBaseDocs","PRIMARY_LEASE_LOST_ERROR_MSG","PersistenceTransaction","onCommittedListeners","ReferenceSet","refsByKey","DocReference","refsByTarget","removeRef","emptyKey","startRef","endRef","forEachInRange","firstRef","firstAfterOrEqual","compareByKey","compareByTargetId","targetOrBatchId","LocalStore","synchronizeLastDocumentChangeReadTime","newMutationQueue","newLocalDocuments","localDocuments","runTransaction","oldBatches","getAllMutationBatches","promisedOldBatches","getMutationQueue","remoteDocuments","getIndexManager","newBatches","removedBatchIds","addedBatchIds","changedKeys","oldBatches_1","newBatches_1","getDocuments","affectedDocuments","queryEngine","setLocalDocumentsView","existingDocs","baseValue","extractBaseValue","addMutationBatch","applyToLocalDocumentSet","lookupMutationKeys","affected","documentBuffer","newChangeBuffer","acknowledgeBatch","applyWriteToRemoteDocuments","performConsistencyCheck","affectedKeys","getHighestUnacknowledgedBatchId","getLastStreamToken","setLastStreamToken","targetCache","getLastRemoteSnapshotVersion","remoteEvent","remoteVersion","newTargetDataByTargetMap","targetDataByTarget","objUtils.forEachNumber","targetChanges","oldTargetData","removeMatchingKeys","addMatchingKeys","addedDocuments","newTargetData","withResumeToken","withSequenceNumber","shouldPersistTargetData","updateTargetData","updatedKeys","documentUpdates","existingDoc","hasPendingWrites","log.debug","resolvedLimboDocuments","updateLimboDocument","updateRemoteVersion","setTargetsMetadata","toMicroseconds","RESUME_TOKEN_MAX_AGE_MICROS","modifiedDocuments","viewChanges","viewChanges_1","viewChange","localViewReferences","addReferences","addedKeys","removeReferences","removedKeys","fromCache","updatedTargetData","withLastLimboFreeSnapshotVersion","afterBatchId","getNextMutationBatchAfterBatchId","getTargetData","cached","allocateTargetId","addTargetData","targetIdByTarget","keepPersistedTargetData","removeReferencesForId","removeTarget","usePreviousResults","remoteKeys","toTarget","getMatchingKeysForTargetId","getActiveClients","setNetworkEnabled","docKeys","promiseChain","ackVersion","garbageCollector","collect","cachedTargetData","getTargetDataForTarget","getNewDocumentChanges","lastDocumentChangeReadTime","getLastReadTime","initialUser","started","setInMemoryPins","getRemoteDocumentCache","getTargetCache","ignoreIfPrimaryLeaseLoss","bufferEntryComparator","aSequence","aIndex","bSequence","bIndex","seqCmp","RollingSequenceNumberBuffer","previousIndex","nextIndex","maxElements","highestValue","GC_DID_NOT_RUN","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","LruParams","cacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","COLLECTION_DISABLED","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","LruScheduler","gcTask","scheduleGC","hasRun","enqueueAfterDelay","LruGarbageCollection","localStore","collectGarbage","LruGarbageCollector","percentile","delegate","getSequenceNumberCount","INVALID","forEachTarget","addElement","forEachOrphanedDocumentSequenceNumber","maxValue","removeTargets","removeOrphanedDocuments","getCacheSize","runGarbageCollection","upperBoundSequenceNumber","sequenceNumbersToCollect","countedTargetsTs","foundUpperBoundTs","removedTargetsTs","removedDocumentsTs","startTs","calculateTargetCount","sequenceNumbers","nthSequenceNumber","numTargetsRemoved","log.getLogLevel","log.LogLevel","PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","IndexedDbTransaction","lruParams","openOrCreate","dbName","simpleDb","updateClientMetadataAndTryBecomePrimary","attachVisibilityHandler","attachWindowUnloadHook","scheduleClientMetadataAndPrimaryLeaseRefreshes","listenSequence","_started","primaryStateListener","primaryState","isPrimary","databaseDeletedListener","setVersionChangeListener","newVersion","clientMetadataStore","verifyPrimaryLease","canActAsPrimary","releasePrimaryLeaseIfHeld","acquireOrExtendPrimaryLease","primaryClientStore","primaryClient","isLocalClient","isWithinAge","lastGarbageCollectionTime","metadataStore","existingClients","active","filterActiveClients","inactive","client","inactiveClient","localStorage","zombiedClientLocalStorageKey","clientMetadataRefresher","ClientMetadataRefresh","maybeGarbageCollectMultiClientState","currentPrimary","isClientZombied","otherClient","otherClientHasBetterNetworkState","otherClientHasBetterVisibility","otherClientHasSameNetworkState","markClientZombied","detachVisibilityHandler","detachWindowUnloadHook","removeClientMetadata","removeClientZombiedEntry","clients","activityThresholdMs","clientMetadata","MAIN_DATABASE","forUser","transactionOperation","persistenceTransaction","simpleDbMode","simpleDbTxn","holdsPrimaryLease","verifyAllowTabSynchronization","raiseOnCommittedEvent","newPrimary","databaseInfo","isDefaultDatabase","maxAgeMs","documentVisibilityHandler","visibilityState","removeEventListener","windowUnloadHandler","shutdown","isZombied","webStorage","ZOMBIED_CLIENTS_KEY_PREFIX","IndexedDbLruDelegate","docCountPromise","orphanedDocmentCount","getTargetCount","docCount","orphanedCount","forEachOrphanedDocument","inMemoryPins","iterateSerial","mutationQueuesContainKey","changeBuffer","documentCount","isPinned","nextPath","nextToReport","getSize","sentinelRow","NumberAsAny","MIN_SAFE_INTEGER","isNullOrUndefined","isSafeInteger","LimitType","Target","memoizedCanonicalId","filters","memoizedOrderBy","inequalityField","getInequalityFilterField","firstOrderByField","getFirstOrderByField","isKeyField","KEY_ORDERING_ASC","OrderBy","foundKeyOrdering","explicitOrderBy","lastDirection","dir","Direction","ASCENDING","KEY_ORDERING_DESC","FieldFilter","isInequality","newFilters","limitType","newOrderBy","First","Last","comparedOnKeyField","comp","matchesPathAndCollectionGroup","matchesOrderBy","matchesFilters","matchesBounds","operators","memoizedTarget","orderBys","DESCENDING","Bound","before","hasCollectionId","isImmediateParentOf","sortsBeforeDocument","assertValidBound","Operator","LESS_THAN","LESS_THAN_OR_EQUAL","EQUAL","GREATER_THAN_OR_EQUAL","GREATER_THAN","ARRAY_CONTAINS","IN","ARRAY_CONTAINS_ANY","Filter","KeyFieldInFilter","KeyFieldFilter","INSTANCE","NAN","ArrayContainsFilter","InFilter","ArrayContainsAnyFilter","matchesComparison","comparison","refValue","arrayValue","lhsElem","orderByComponent","docValue","thisPosition","otherPosition","isKeyOrderBy","compareByField","keyField","IndexFreeQueryEngine","localDocumentsView","matchesAllDocuments","executeFullCollectionScan","previousResults","applyQuery","hasLimitToFirst","hasLimitToLast","needsRefill","updatedResults","docComparator","sortedPreviousResults","limboFreeSnapshotVersion","docAtLimitEdge","MemoryMutationQueue","batchIndex","indexOfExistingBatchId","batchesByDocumentKey","findMutationBatch","mutationBatch","rawIndex","indexOfBatchId","findMutationBatches","startPath","forEachWhile","rowKeyPath","references","MemoryRemoteDocumentCache","currentSize","sizer","MemoryTargetCache","targets","highestSequenceNumber","nextTargetId","removals","matchingKeys","referencesForId","MemoryPersistence","MemoryLruDelegate","MemoryEagerDelegate","mutationQueues","toKey","MemoryTransaction","onTransactionStarted","onTransactionCommitted","or","vs","obj\r\n .values","referenceDelegateFactory","documentSize","_orphanedDocuments","orphanedDocuments","isReferenced","orphanedDocumentCount","orphanedSequenceNumbers","forEachDocumentKey","orphanedAt","ExponentialBackoff","currentBaseMs","maxDelayMs","desiredDelayWithJitterMs","jitterDelayMs","delaySoFarMs","lastAttemptTime","remainingDelayMs","timerPromise","backoffFactor","initialDelayMs","PersistentStreamState","PersistentStream","Starting","Open","Backoff","Initial","performBackoff","isStarted","backoff","isOpen","idleTimer","idleTimerId","handleIdleCloseTimer","cancelIdleCheck","finalState","closeCount","resetToMax","credentialsProvider","invalidateToken","tearDown","dispatchIfNotClosed","getCloseGuardedDispatcher","startStream","rpcError","handleStreamClose","startRpc","backoffAndRun","startCloseCount","connectionTimerId","connection","PersistentListenStream","openStream","watchChangeProto","watchChange","fromWatchChange","versionFromListenResponse","onWatchChange","encodedDatabaseId","addTarget","labels","toListenRequestLabels","ListenStreamConnectionBackoff","ListenStreamIdle","PersistentWriteStream","handshakeComplete_","writeMutations","responseProto","fromWriteResults","writeResults","commitTime","onMutationResult","onHandshakeComplete","WriteStreamConnectionBackoff","WriteStreamIdle","Datastore","invokeRPC","toName","invokeStreamingRPC","fromMaybeDocument","rpcName","OnlineState","OnlineStateSource","Transaction","ensureCommitNotCalled","datastore","lookup","recordVersion","toMutations","writtenDocs","preconditionForUpdate","lastWriteError","unwritten","readVersions","_version","commit","docVersion","existingVersion","RpcCode","OnlineStateTracker","watchStreamFailures","setAndBroadcast","Unknown","onlineStateTimer","OnlineStateTimeout","logClientOfflineWarningIfNecessary","Offline","Online","clearOnlineStateTimer","newState","shouldWarnClientIsOffline","onlineStateHandler","details","isPermanentError","mapCodeFromRpcCode","ChangeType","SyncState","DocumentSet","oldSet","keyedMap","sortedSet","thisDoc","otherDoc","docStrings","DocumentChangeSet","Added","Metadata","Removed","Modified","ViewSnapshot","mutatedKeys","emptySet","syncStateChanged","oldDocs","docChanges","otherChanges","excludesMetadataChanges","RemoteEvent","TargetChange","createSynthesizedTargetChangeForCurrentChange","targetMismatches","WatchTargetChangeState","updatedTargetIds","removedTargetIds","newDoc","existenceFilter","targetIds","cause","TargetState","_current","_resumeToken","_hasPendingChanges","documentChanges","changeType","snapshotChangesMap","WatchChangeAggregator","docChange","addDocumentToTarget","removeDocumentFromTarget","targetChange","targetState","ensureTargetState","NoChange","isActiveTarget","updateResumeToken","recordTargetResponse","isPending","clearPendingChanges","Current","markCurrent","Reset","resetTarget","targetStates","targetDataForActiveTarget","getCurrentDocumentCountForTarget","pendingTargetResets","pendingDocumentUpdates","targetContainsDocument","hasPendingChanges","toTargetChange","pendingDocumentTargetMapping","isOnlyLimboTarget","LimboResolution","documentTargetMap","addDocumentChange","ensureDocumentTargetMapping","updatedDocument","removeDocumentChange","metadataProvider","getRemoteKeysForTarget","recordPendingTargetRequest","targetMapping","targetActive","RemoteStore","enableNetwork","canUseNetwork","writeStream","shouldStartWatchStream","startWatchStream","onlineStateTracker","fillWritePipeline","disableNetworkInternal","watchStream","writePipeline","cleanUpWatchStreamState","connectivityMonitor","objUtils.contains","listenTargets","sendWatchRequest","sendUnwatchRequest","objUtils.isEmpty","markIdle","syncEngine","watchChangeAggregator","watch","unwatch","handleWatchStreamStart","handleWatchStreamFailure","WatchTargetChange","handleTargetError","DocumentWatchChange","handleDocumentChange","ExistenceFilterChange","handleExistenceFilter","handleTargetChange","raiseWatchSnapshot","createRemoteEvent","requestTargetData","ExistenceFilterMismatch","applyRemoteEvent","rejectListen","canAddToWritePipeline","lastBatchIdRetrieved","nextMutationBatch","addToWritePipeline","shouldStartWriteStream","startWriteStream","handshakeComplete","writeHandshake","applySuccessfulWrite","handleWriteError","handleHandshakeError","isPermanentWriteError","inhibitBackoff","rejectFailedWrite","restartNetwork","addCallback","newPersistentWatchStream","onWatchStreamOpen","onWatchStreamClose","onWatchStreamChange","newPersistentWriteStream","onWriteStreamOpen","onWriteStreamClose","onWriteHandshakeComplete","GeoPoint","_lat","_long","latitude","longitude","ServerTimestampTransform","transformResult","ArrayUnionTransformOperation","coercedFieldValuesArray","toUnion","elements","ArrayRemoveTransformOperation","toRemove","NumericIncrementTransformOperation","operand","sum","ExistenceFilter","dirs","DIRECTIONS","OPERATORS","ISO_REG_EXP","assertPresent","typeUtils.isNullOrUndefined","parseInt64","JsonProtoSerializer","useProto3Json","byteString","nanos","fromIso8601String","utc","fraction","nanoStr","unsafeCastProtoByteString","toUint8Array","fromBase64String","fromUint8Array","fullyQualifiedPrefixPath","resource","isValidResourceName","toResourceName","fromResourceName","extractLocalPathFromResourceName","resourceName","fieldValue.NullValue","nullValue","fieldValue.BooleanValue","booleanValue","fieldValue.IntegerValue","integerValue","fieldValue.DoubleValue","doubleValue","fieldValue.StringValue","stringValue","fieldValue.ObjectValue","toMapValue","fieldValue.ArrayValue","toArrayValue","fieldValue.TimestampValue","timestampValue","fieldValue.GeoPointValue","geoPointValue","fieldValue.BlobValue","bytesValue","toBytes","fieldValue.RefValue","referenceValue","fromFields","fromValue","fromBlob","dbId","toFields","fromName","toValue","missing","fromFound","fromMissing","documentChange","documentDelete","documentRemove","mapRpcCodeFromCode","targetChangeType","toWatchTargetChangeState","fromWatchTargetChangeState","causeProto","fromRpcStatus","entityChange","docDelete","docRemove","toMutationDocument","updateMask","toDocumentMask","toFieldTransform","currentDocument","toPrecondition","fromPrecondition","fromDocumentMask","fromFieldTransform","MutationResult","protos","fromWriteResult","setToServerValue","appendMissingElements","removeAllFromArray","increment","fieldValue.NumberValue","fromServerFormat","toQueryPath","documentsTarget","atPath","fromQueryPath","structuredQuery","allDescendants","toFilter","toOrder","toInt32Value","toCursor","fromCount","filterBy","fromFilter","fromOrder","fromInt32Value","fromCursor","toLabel","goog-listen-tags","toUnaryOrFieldFilter","compositeFilter","unaryFilter","fromUnaryFilter","fieldFilter","fromFieldFilter","toPropertyOrder","fromPropertyOrder","fieldReference","toFieldPathReference","toDirection","fromFieldPathReference","fromDirection","fromOperatorName","toOperatorName","nanField","nullField","canonicalFields","fieldPaths","fromArray","EventManager","firstListen","queryInfo","QueryListenersInfo","applyOnlineStateChange","onlineState","viewSnap","onViewSnapshot","raiseSnapshotsInSyncEvent","lastListen","viewSnaps","raisedEvent","viewSnaps_1","snapshotsInSyncListeners","QueryListener","includeMetadataChanges","raisedInitialEvent","shouldRaiseEvent","queryObserver","shouldRaiseInitialEvent","raiseInitialEvent","maybeOnline","waitForSyncWhenOnline","hasPendingWritesChanged","fromInitialDocuments","LocalViewChanges","viewSnapshot","_syncedDocuments","previousChanges","changeSet","oldDocumentSet","documentSet","newMutatedKeys","newDocumentSet","lastDocInLimit","firstDocInLimit","newMaybeDoc","oldDoc","oldDocHadPendingMutations","newDocHasPendingMutations","changeApplied","track","shouldWaitForSyncedDocument","updateLimboDocuments","compareChangeType","applyTargetChange","limboChanges","newSyncState","limboDocuments","Synced","Local","syncState","oldLimboDocuments","shouldBeInLimbo","RemovedLimboDocument","AddedLimboDocument","queryResult","computeDocChanges","TransactionRunner","runWithBackOff","remoteStore","createTransaction","tryRunUpdateFunction","commitError","handleTransactionError","userPromiseError","updateFunction","retries","isRetryableTransactionError","RetryTransaction","syncEngineListener","assertSubscribed","queryView","queryViewsByQuery","sharedClientState","addLocalQueryTarget","computeInitialSnapshot","allocateTarget","status_1","initializeViewAndComputeSnapshot","executeQuery","viewDocChanges","synthesizedTargetChange","QueryView","queriesByTarget","synchronizeWithPersistedState","updateTrackedLimbos","removeLocalQueryTarget","isActiveQueryTarget","releaseTarget","clearQueryState","removeAndCleanupTarget","localWrite","addPendingMutation","addMutationCallback","emitNewSnapsAndNotifyLocalStore","objUtils.forEach","limboResolution","limboResolutionsByTarget","receivedDocument","SharedClientState","newViewSnapshots_1","onOnlineStateChange","setOnlineState","updateQueryState","limboKey","limboTargetsByKey","event_1","batchState","lookupMutationDocuments","processUserCallback","removeCachedMutationBatchMetadata","mutationBatchResult","triggerPendingWritesCallbacks","updateMutationState","rejectBatch","highestBatchId","pendingWritesCallbacks","newCallbacks","mutationUserCallbacks","onWatchError","limboKeys","limboDocumentRefs","removeLimboTarget","limboTargetId","limboChanges_1","limboChange","trackLimboChange","limboTargetIdGenerator","newSnaps","docChangesInAllViews","queriesProcessed","fromSnapshot","notifyLocalViewChanges","userChanged","rejectOutstandingPendingWritesCallbacks","handleUserChange","handleCredentialChange","applyPrimaryState","activeTargets","getAllActiveQueryTargets","synchronizeQueryViewsAndRaiseSnapshots","activeQueries","activeQueries_1","activeTargets_1","p_1","isLocalQueryTarget","resetLimboDocuments","removeAllReferences","newViewSnapshots","targets_1","synchronizeViewAndComputeSnapshot","getTarget","synthesizeTargetToQuery","synthesizedRemoteEvent","createSynthesizedRemoteEventForCurrentChange","added_1","removed_1","disableNetwork","keySet","queries_2","unionWith","syncedDocuments","forSyncEngine","CLIENT_STATE_KEY_PREFIX","createWebStorageClientStateKey","MUTATION_BATCH_KEY_PREFIX","createWebStorageMutationBatchKey","mutationKey","QUERY_TARGET_KEY_PREFIX","createWebStorageQueryTargetMetadataKey","ONLINE_STATE_KEY_PREFIX","SEQUENCE_NUMBER_KEY_PREFIX","MutationMetadata","validData","firestoreError","batchMetadata","QueryTargetMetadata","RemoteClientState","clientState","activeTargetIdsSet","SharedOnlineState","LocalClientState","WebStorageSharedClientState","existingClients_1","localClientId","storageItem","fromWebStorageEntry","activeClients","persistClientState","onlineStateJSON","onlineStateKey","fromWebStorageOnlineState","handleOnlineStateEvent","earlyEvents","handleWebStorageEvent","sequenceNumberKey","persistMutationState","removeMutationState","queryState","localClientState","addQueryTarget","removeQueryTarget","persistQueryTargetState","persistOnlineState","storageListener","localClientStorageKey","storageArea","clientStateKeyRe","fromWebStorageClientStateKey","handleClientStateEvent","fromWebStorageClientState","mutationBatchKeyRe","mutationMetadata","fromWebStorageMutationMetadata","handleMutationBatchEvent","queryTargetKeyRe","queryTargetMetadata","fromWebStorageQueryTargetMetadata","handleQueryTargetEvent","seqString","parsed","fromWebStorageSequenceNumber","toWebStorageJSON","mutationState","targetKey","targetMetadata","applyBatchState","applyTargetState","existingTargets","newTargets","addedTargets","removedTargets","applyActiveTargetsChange","escapedPersistenceKey","createWebStorageSequenceNumberKey","createWebStorageOnlineStateKey","MemorySharedClientState","localState","IndexedDbPersistenceSettings","withCacheSize","cacheSizeBytes","synchronizeTabs","FirestoreClient","persistenceSettings","verifyNotTerminated","initializationDone","persistenceResult","initialized","setChangeListener","initializePersistence","maybeLruGc","initializeRest","startIndexedDbPersistence","canFallback","startMemoryPersistence","DOMException","isShuttingDown","buildStoragePrefix","createIndexedDbPersistence","createEagerPersistence","loadConnection","lruScheduler","newConnectivityMonitor","newSerializer","remoteStoreOnlineStateChangedHandler","sharedClientStateOnlineStateChangedHandler","eventMgr","setPrimaryStateListener","setDatabaseDeletedListener","terminate","verifyOperationInProgress","enqueueAndInitiateShutdown","removeChangeListener","registerPendingWritesCallback","clientTerminated","readDocument","addSnapshotsInSyncListener","removeSnapshotsInSyncListener","newId","AsyncObserver","scheduleEvent","muted","eventHandler","_DOCUMENT_ID","_internalPath","InternalFieldPath","fieldNames","minNumberOfElements","validateNamedArrayAtLeastNumberOfElements","RESERVED","authHeaders","EmptyCredentialsProvider","changeListener","FirebaseCredentialsProvider","tokenListener","initialTokenCounter","tokenCounter","tokenData","OAuthToken","receivedInitialUser","currentUid","getUser","FirstPartyToken","X-Goog-AuthUser","sessionIndex","authHeader","gapi","getAuthHeaderValueForFirstParty","FIRST_PARTY","FirstPartyCredentialsProvider","isPartialObserver","FieldValueImpl","DeleteFieldValueImpl","ServerTimestampFieldValueImpl","ArrayUnionFieldValueImpl","ArrayRemoveFieldValueImpl","NumericIncrementFieldValueImpl","_methodName","_elements","_operand","PublicFieldValue","RESERVED_FIELD_REGEX","ParsedSetData","UserDataSource","ParsedUpdateData","isWrite","dataSource","MergeSet","Update","Argument","ArrayArgument","ParseContext","validatePathSegment","validatePath","fieldDescription","createError","arrayElement","UserDataConverter","validatePlainObject","updateData","parseData","validatedFieldPaths","fieldPaths_1","stringOrFieldPath","ExternalFieldPath","fieldPathFromDotSeparatedString","covers","fieldMaskPaths","childContext","childContextForFieldPath","runPreConverter","parsedValue","moreFieldsAndValues","fieldPathFromArgument","value_1","allowArrays","preConverter","looksLikeJsonObject","parseObject","parseSentinelFieldValue","parseArray","parseScalarValue","childContextForField","entryIndex","array_1","parsedEntry","childContextForArray","parsedElements","parseArrayTransformElements","arrayUnion","arrayRemove","parseQueryValue","numericIncrement","typeUtils.isSafeInteger","fromDate","DocumentKeyReference","fromDotSeparatedString","CACHE_SIZE_UNLIMITED","FirestoreSettings","objUtils.defaulted","DEFAULT_CACHE_SIZE_BYTES","MINIMUM_CACHE_SIZE_BYTES","experimentalForceLongPolling","Firestore","settingsLiteral","newSettings","_firestoreClient","_settings","_credentials","makeCredentialsProvider","ensureClientConfigured","experimentalTabSynchronization","configureClient","makeDatabaseInfo","_queue","enqueueAndForgetEvenAfterShutdown","clearPersistence","e_1","_removeServiceInstance","waitForPendingWrites","onSnapshotsInSyncInternal","asyncObserver","mute","MemoryPersistenceSettings","DatabaseInfo","_databaseId","_persistenceKey","DocumentReference","thisDb","otherDb","firestore","_firebaseApp","CollectionReference","forPath","InternalQuery","WriteBatch","log.setLogLevel","databaseIdOrApp","databaseIdFromApp","external_1","_dataConverter","createDataConverter","documentRef","validateReference","_firestore","_transaction","DocumentSnapshot","_converter","validateSetOptions","convertedValue","mergeFields","parseMergeData","parseSetData","fieldOrUpdateData","parseUpdateVarargs","parseUpdateData","verifyNotCommitted","_mutations","_committed","currArg","internalOptions","onSnapshotInternal","errHandler","internalListener","validateGetOptions","getDocumentFromLocalCache","getViaSnapshotListener","SnapshotMetadata","validateSnapshotOptions","_document","QueryDocumentSnapshot","_fromCache","_hasPendingWrites","fromFirestore","toJSObject","fromSnapshotOptions","_areTimestampsInSnapshotsEnabled","toJSValue","toJSArray","opStr","enums","validateStringEnum","operator","validateDisjunctiveFilterElements","referenceList","parseDocumentIdValue","validateNewFilter","_query","addFilter","directionStr","validateNewOrderBy","addOrderBy","withLimitToFirst","withLimitToLast","docOrField","boundFromDocOrFields","withStartAt","withEndAt","boundFromDocument","allFields","boundFromFields","rawValue","wrapped","validateHasExplicitOrderByForLimitToLast","QuerySnapshot","firestoreClient","getDocumentsFromLocalCache","documentIdValue","arrayOps","disjunctiveOps","isArrayOp","isDisjunctiveOp","existingField","validateOrderByAndInequalityMatch","conflictingOp","findFilterOperator","inequality","_snapshot","convertToDocumentImpl","_originalQuery","_cachedChanges","_cachedChangesIncludeMetadataChanges","lastDoc_1","index_1","oldIndex","indexTracker_1","resultChangeType","changesFromSnapshot","throwDocChangesMethodError","docRef","_path","applyFirestoreDataConverter","toFirestore","PublicFirestore","PublicTransaction","PublicWriteBatch","PublicDocumentReference","PublicDocumentSnapshot","PublicQueryDocumentSnapshot","PublicQuery","PublicQuerySnapshot","PublicCollectionReference","firestoreNamespace","configureForFirebase","shallowCopy","NoopConnectivityMonitor","BrowserConnectivityMonitor","networkAvailableListener","networkUnavailableListener","onNetworkAvailable","onNetworkUnavailable","configureNetworkMonitoring","StreamBridge","wrappedOnOpen","wrappedOnClose","wrappedOnMessage","closeFn","sendFn","RPC_NAME_REST_MAPPING","BatchGetDocuments","Commit","X_GOOG_API_CLIENT_VALUE","WebChannelConnection","makeUrl","getLastErrorCode","getResponseJson","responseError","firestoreErrorCode","serverError","mapCodeFromHttpResponseErrorStatus","getLastError","jsonObj","requestString","modifyHeadersForRequest","urlParts","baseUrl","webchannelTransport","backgroundChannelTest","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","isIE","runtime","chrome","browser","isBrowserExtension","unguardedEventListen","createWebChannel","opened","closed","streamBridge","callOnClose","msgData","msgDataOrError","status_2","mapCodeFromRpcStatus","callOnMessage","callOnOpen","urlRpcName","BrowserPlatform","setPlatform","errorCodeMap","HttpsErrorImpl","_errorForResponse","bodyJSON","codeForHTTPStatus","errorJSON","ContextProvider","messaging","Notification","permission","getAuthToken","getInstanceIdToken","instanceIdToken","messagingProvider","Serializer","Service","region","region_","emulatorOrigin","_url","contextProvider","getContext","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","nativeObject","getAll","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","crypto","msCrypto","getRandomValues","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","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","hasVisibleClients","createNewMessage","clientList_2","sendMessageToWindowClients","notificationDetails","notification","notificationInformation","getNotificationData","title","actions","maxActions","showNotification","stopImmediatePropagation","fcmOptions","click_action","getLink","clientList_1","getWindowClient","openWindow","focus","waitUntil","onPush","onSubChange","onNotificationClick","matchAll","includeUncontrolled","NAMESPACE_EXPORTS","PushSubscription","cookieEnabled","messagingSenderId","DEFAULT_HOST","CONFIG_STORAGE_BUCKET_KEY","FirebaseStorageError","prependCode","codeProp","serverResponse_","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","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","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","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_","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","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","Authorization","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","_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,EAAeF,GACvB,IAAIG,EAAWC,KAAKC,IAAIN,GACxBK,KAAKC,IAAIN,GAAQI,EAAWA,EAAS,IAAIH,EAAQA,GAGnDH,EAAQT,UAAkB,OAAI,SAASW,UAC9BK,KAAKC,IAAIJ,EAAcF,KAGhCF,EAAQT,UAAUkB,IAAM,SAASP,GAE/B,OADAA,EAAOE,EAAcF,GACdK,KAAKG,IAAIR,GAAQK,KAAKC,IAAIN,GAAQ,MAG3CF,EAAQT,UAAUmB,IAAM,SAASR,GAC/B,OAAOK,KAAKC,IAAIG,eAAeP,EAAcF,KAG/CF,EAAQT,UAAUqB,IAAM,SAASV,EAAMC,GACrCI,KAAKC,IAAIJ,EAAcF,IAASG,EAAeF,IAGjDH,EAAQT,UAAUsB,QAAU,SAASC,EAAUC,GAC7C,IAAK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